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
ff00635f387af8ca1e5060bc528e0712ed76bcc1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/properties.lean
48bbb2f1e03d3ed1c14bdd90e0bf51105f99da4d
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
13,838
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebraic_geometry.AffineScheme import ring_theory.nilpotent import topology.sheaves.sheaf_condition.sites import algebra.category.Ring.constructions import ring_theory.local_properties /-! # Basic properties of schemes We provide some basic properties of schemes ## Main definition * `algebraic_geometry.is_integral`: A scheme is integral if it is nontrivial and all nontrivial components of the structure sheaf are integral domains. * `algebraic_geometry.is_reduced`: A scheme is reduced if all the components of the structure sheaf is reduced. -/ open topological_space opposite category_theory category_theory.limits Top namespace algebraic_geometry variable (X : Scheme) instance : t0_space X.carrier := begin refine t0_space.of_open_cover (λ x, _), obtain ⟨U, R, ⟨e⟩⟩ := X.local_affine x, let e' : U.1 ≃ₜ prime_spectrum R := homeo_of_iso ((LocallyRingedSpace.forget_to_SheafedSpace ⋙ SheafedSpace.forget _).map_iso e), exact ⟨U.1.1, U.2, U.1.2, e'.embedding.t0_space⟩ end instance : quasi_sober X.carrier := begin apply_with (quasi_sober_of_open_cover (set.range (λ x, set.range $ (X.affine_cover.map x).1.base))) { instances := ff }, { rintro ⟨_,i,rfl⟩, exact (X.affine_cover.is_open i).base_open.open_range }, { rintro ⟨_,i,rfl⟩, exact @@open_embedding.quasi_sober _ _ _ (homeomorph.of_embedding _ (X.affine_cover.is_open i).base_open.to_embedding) .symm.open_embedding prime_spectrum.quasi_sober }, { rw [set.top_eq_univ, set.sUnion_range, set.eq_univ_iff_forall], intro x, exact ⟨_, ⟨_, rfl⟩, X.affine_cover.covers x⟩ } end /-- A scheme `X` is reduced if all `𝒪ₓ(U)` are reduced. -/ class is_reduced : Prop := (component_reduced : ∀ U, _root_.is_reduced (X.presheaf.obj (op U)) . tactic.apply_instance) attribute [instance] is_reduced.component_reduced lemma is_reduced_of_stalk_is_reduced [∀ x : X.carrier, _root_.is_reduced (X.presheaf.stalk x)] : is_reduced X := begin refine ⟨λ U, ⟨λ s hs, _⟩⟩, apply presheaf.section_ext X.sheaf U s 0, intro x, rw ring_hom.map_zero, change X.presheaf.germ x s = 0, exact (hs.map _).eq_zero end instance stalk_is_reduced_of_reduced [is_reduced X] (x : X.carrier) : _root_.is_reduced (X.presheaf.stalk x) := begin constructor, rintros g ⟨n, e⟩, obtain ⟨U, hxU, s, rfl⟩ := X.presheaf.germ_exist x g, rw [← map_pow, ← map_zero (X.presheaf.germ ⟨x, hxU⟩)] at e, obtain ⟨V, hxV, iU, iV, e'⟩ := X.presheaf.germ_eq x hxU hxU _ 0 e, rw [map_pow, map_zero] at e', replace e' := (is_nilpotent.mk _ _ e').eq_zero, erw ← concrete_category.congr_hom (X.presheaf.germ_res iU ⟨x, hxV⟩) s, rw [comp_apply, e', map_zero] end lemma is_reduced_of_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f] [is_reduced Y] : is_reduced X := begin constructor, intro U, have : U = (opens.map f.1.base).obj (H.base_open.is_open_map.functor.obj U), { ext1, exact (set.preimage_image_eq _ H.base_open.inj).symm }, rw this, exact is_reduced_of_injective (inv $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U)) (as_iso $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U) : Y.presheaf.obj _ ≅ _).symm .CommRing_iso_to_ring_equiv.injective end instance {R : CommRing} [H : _root_.is_reduced R] : is_reduced (Scheme.Spec.obj $ op R) := begin apply_with is_reduced_of_stalk_is_reduced { instances := ff }, intro x, dsimp, haveI : _root_.is_reduced (CommRing.of $ localization.at_prime (prime_spectrum.as_ideal x)), { dsimp, apply_instance }, exact is_reduced_of_injective (structure_sheaf.stalk_iso R x).hom (structure_sheaf.stalk_iso R x).CommRing_iso_to_ring_equiv.injective, end lemma affine_is_reduced_iff (R : CommRing) : is_reduced (Scheme.Spec.obj $ op R) ↔ _root_.is_reduced R := begin refine ⟨_, λ h, by exactI infer_instance⟩, intro h, resetI, haveI : _root_.is_reduced (LocallyRingedSpace.Γ.obj (op $ Spec.to_LocallyRingedSpace.obj $ op R)), { change _root_.is_reduced ((Scheme.Spec.obj $ op R).presheaf.obj $ op ⊤), apply_instance }, exact is_reduced_of_injective (to_Spec_Γ R) ((as_iso $ to_Spec_Γ R).CommRing_iso_to_ring_equiv.injective) end lemma is_reduced_of_is_affine_is_reduced [is_affine X] [h : _root_.is_reduced (X.presheaf.obj (op ⊤))] : is_reduced X := begin haveI : is_reduced (Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))), { rw affine_is_reduced_iff, exact h }, exact is_reduced_of_open_immersion X.iso_Spec.hom, end /-- To show that a statement `P` holds for all open subsets of all schemes, it suffices to show that 1. In any scheme `X`, if `P` holds for an open cover of `U`, then `P` holds for `U`. 2. For an open immerison `f : X ⟶ Y`, if `P` holds for the entire space of `X`, then `P` holds for the image of `f`. 3. `P` holds for the entire space of an affine scheme. -/ lemma reduce_to_affine_global (P : ∀ (X : Scheme) (U : opens X.carrier), Prop) (h₁ : ∀ (X : Scheme) (U : opens X.carrier), (∀ (x : U), ∃ {V} (h : x.1 ∈ V) (i : V ⟶ U), P X V) → P X U) (h₂ : ∀ {X Y} (f : X ⟶ Y) [hf : is_open_immersion f], ∃ {U : set X.carrier} {V : set Y.carrier} (hU : U = ⊤) (hV : V = set.range f.1.base), P X ⟨U, hU.symm ▸ is_open_univ⟩ → P Y ⟨V, hV.symm ▸ hf.base_open.open_range⟩) (h₃ : ∀ (R : CommRing), P (Scheme.Spec.obj $ op R) ⊤) : ∀ (X : Scheme) (U : opens X.carrier), P X U := begin intros X U, apply h₁, intro x, obtain ⟨_,⟨j,rfl⟩,hx,i⟩ := X.affine_basis_cover_is_basis.exists_subset_of_mem_open x.prop U.2, let U' : opens _ := ⟨_, (X.affine_basis_cover.is_open j).base_open.open_range⟩, let i' : U' ⟶ U := hom_of_le i, refine ⟨U', hx, i', _⟩, obtain ⟨_,_,rfl,rfl,h₂'⟩ := h₂ (X.affine_basis_cover.map j), apply h₂', apply h₃ end . lemma reduce_to_affine_nbhd (P : ∀ (X : Scheme) (x : X.carrier), Prop) (h₁ : ∀ (R : CommRing) (x : prime_spectrum R), P (Scheme.Spec.obj $ op R) x) (h₂ : ∀ {X Y} (f : X ⟶ Y) [is_open_immersion f] (x : X.carrier), P X x → P Y (f.1.base x)) : ∀ (X : Scheme) (x : X.carrier), P X x := begin intros X x, obtain ⟨y, e⟩ := X.affine_cover.covers x, convert h₂ (X.affine_cover.map (X.affine_cover.f x)) y _, { rw e }, apply h₁, end lemma eq_zero_of_basic_open_eq_bot {X : Scheme} [hX : is_reduced X] {U : opens X.carrier} (s : X.presheaf.obj (op U)) (hs : X.basic_open s = ⊥) : s = 0 := begin apply Top.presheaf.section_ext X.sheaf U, simp_rw ring_hom.map_zero, unfreezingI { revert X U hX s }, refine reduce_to_affine_global _ _ _ _, { intros X U hx hX s hs x, obtain ⟨V, hx, i, H⟩ := hx x, unfreezingI { specialize H (X.presheaf.map i.op s) }, erw Scheme.basic_open_res at H, rw [hs, ← subtype.coe_injective.eq_iff, inf_bot_eq] at H, specialize H rfl ⟨x, hx⟩, erw Top.presheaf.germ_res_apply at H, exact H }, { rintros X Y f hf, have e : (f.val.base) ⁻¹' set.range ⇑(f.val.base) = ⊤, { rw [← set.image_univ, set.preimage_image_eq _ hf.base_open.inj, set.top_eq_univ] }, refine ⟨_, _, e, rfl, _⟩, rintros H hX s hs ⟨_, x, rfl⟩, unfreezingI { haveI := is_reduced_of_open_immersion f }, specialize H (f.1.c.app _ s) _ ⟨x, by { change x ∈ (f.val.base) ⁻¹' _, rw e, trivial }⟩, { rw [← Scheme.preimage_basic_open, hs], ext1, simp [opens.map] }, { erw ← PresheafedSpace.stalk_map_germ_apply f.1 ⟨_,_⟩ ⟨x,_⟩ at H, apply_fun (inv $ PresheafedSpace.stalk_map f.val x) at H, erw [category_theory.is_iso.hom_inv_id_apply, map_zero] at H, exact H } }, { intros R hX s hs x, erw [basic_open_eq_of_affine', prime_spectrum.basic_open_eq_bot_iff] at hs, replace hs := (hs.map (Spec_Γ_identity.app R).inv), -- what the hell?! replace hs := @is_nilpotent.eq_zero _ _ _ _ (show _, from _) hs, rw iso.hom_inv_id_apply at hs, rw [hs, map_zero], exact @@is_reduced.component_reduced hX ⊤ } end @[simp] lemma basic_open_eq_bot_iff {X : Scheme} [is_reduced X] {U : opens X.carrier} (s : X.presheaf.obj $ op U) : X.basic_open s = ⊥ ↔ s = 0 := begin refine ⟨eq_zero_of_basic_open_eq_bot s, _⟩, rintro rfl, simp, end /-- A scheme `X` is integral if its carrier is nonempty, and `𝒪ₓ(U)` is an integral domain for each `U ≠ ∅`. -/ class is_integral : Prop := (nonempty : nonempty X.carrier . tactic.apply_instance) (component_integral : ∀ (U : opens X.carrier) [_root_.nonempty U], is_domain (X.presheaf.obj (op U)) . tactic.apply_instance) attribute [instance] is_integral.component_integral is_integral.nonempty instance [h : is_integral X] : is_domain (X.presheaf.obj (op ⊤)) := @@is_integral.component_integral _ _ (by simp) @[priority 900] instance is_reduced_of_is_integral [is_integral X] : is_reduced X := begin constructor, intro U, cases U.1.eq_empty_or_nonempty, { have : U = ∅ := subtype.eq h, haveI := CommRing.subsingleton_of_is_terminal (X.sheaf.is_terminal_of_eq_empty this), change _root_.is_reduced (X.sheaf.val.obj (op U)), apply_instance }, { haveI : nonempty U := by simpa, apply_instance } end instance is_irreducible_of_is_integral [is_integral X] : irreducible_space X.carrier := begin by_contradiction H, replace H : ¬ is_preirreducible (⊤ : set X.carrier) := λ h, H { to_preirreducible_space := ⟨h⟩, to_nonempty := infer_instance }, simp_rw [is_preirreducible_iff_closed_union_closed, not_forall, not_or_distrib] at H, rcases H with ⟨S, T, hS, hT, h₁, h₂, h₃⟩, erw not_forall at h₂ h₃, simp_rw not_forall at h₂ h₃, haveI : nonempty (⟨Sᶜ, hS.1⟩ : opens X.carrier) := ⟨⟨_, h₂.some_spec.some_spec⟩⟩, haveI : nonempty (⟨Tᶜ, hT.1⟩ : opens X.carrier) := ⟨⟨_, h₃.some_spec.some_spec⟩⟩, haveI : nonempty (⟨Sᶜ, hS.1⟩ ⊔ ⟨Tᶜ, hT.1⟩ : opens X.carrier) := ⟨⟨_, or.inl h₂.some_spec.some_spec⟩⟩, let e : X.presheaf.obj _ ≅ CommRing.of _ := (X.sheaf.is_product_of_disjoint ⟨_, hS.1⟩ ⟨_, hT.1⟩ _) .cone_point_unique_up_to_iso (CommRing.prod_fan_is_limit _ _), apply_with false_of_nontrivial_of_product_domain { instances := ff }, { exact e.symm.CommRing_iso_to_ring_equiv.is_domain _ }, { apply X.to_LocallyRingedSpace.component_nontrivial }, { apply X.to_LocallyRingedSpace.component_nontrivial }, { ext x, split, { rintros ⟨hS,hT⟩, cases h₁ (show x ∈ ⊤, by trivial), exacts [hS h, hT h] }, { intro x, exact x.rec _ } } end lemma is_integral_of_is_irreducible_is_reduced [is_reduced X] [H : irreducible_space X.carrier] : is_integral X := begin split, refine λ U hU, ⟨λ a b e, _, (@@LocallyRingedSpace.component_nontrivial X.to_LocallyRingedSpace U hU).1⟩, simp_rw [← basic_open_eq_bot_iff, ← opens.not_nonempty_iff_eq_bot], by_contra' h, obtain ⟨_, ⟨x, hx₁, rfl⟩, ⟨x, hx₂, e'⟩⟩ := @@nonempty_preirreducible_inter _ H.1 (X.basic_open a).2 (X.basic_open b).2 h.1 h.2, replace e' := subtype.eq e', subst e', replace e := congr_arg (X.presheaf.germ x) e, rw [ring_hom.map_mul, ring_hom.map_zero] at e, refine zero_ne_one' (X.presheaf.stalk x.1) (is_unit_zero_iff.1 _), convert hx₁.mul hx₂, exact e.symm end lemma is_integral_iff_is_irreducible_and_is_reduced : is_integral X ↔ irreducible_space X.carrier ∧ is_reduced X := ⟨λ _, by exactI ⟨infer_instance, infer_instance⟩, λ ⟨_, _⟩, by exactI is_integral_of_is_irreducible_is_reduced X⟩ lemma is_integral_of_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f] [is_integral Y] [nonempty X.carrier] : is_integral X := begin constructor, intros U hU, have : U = (opens.map f.1.base).obj (H.base_open.is_open_map.functor.obj U), { ext1, exact (set.preimage_image_eq _ H.base_open.inj).symm }, rw this, haveI : is_domain (Y.presheaf.obj (op (H.base_open.is_open_map.functor.obj U))), { apply_with is_integral.component_integral { instances := ff }, apply_instance, refine ⟨⟨_, _, hU.some.prop, rfl⟩⟩ }, exact (as_iso $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U) : Y.presheaf.obj _ ≅ _).symm.CommRing_iso_to_ring_equiv.is_domain _ end instance {R : CommRing} [H : is_domain R] : is_integral (Scheme.Spec.obj $ op R) := begin apply_with is_integral_of_is_irreducible_is_reduced { instances := ff }, { apply_instance }, { dsimp [Spec.Top_obj], apply_instance }, end lemma affine_is_integral_iff (R : CommRing) : is_integral (Scheme.Spec.obj $ op R) ↔ is_domain R := ⟨λ h, by exactI ring_equiv.is_domain ((Scheme.Spec.obj $ op R).presheaf.obj _) (as_iso $ to_Spec_Γ R).CommRing_iso_to_ring_equiv, λ h, by exactI infer_instance⟩ lemma is_integral_of_is_affine_is_domain [is_affine X] [nonempty X.carrier] [h : is_domain (X.presheaf.obj (op ⊤))] : is_integral X := begin haveI : is_integral (Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))), { rw affine_is_integral_iff, exact h }, exact is_integral_of_open_immersion X.iso_Spec.hom, end lemma map_injective_of_is_integral [is_integral X] {U V : opens X.carrier} (i : U ⟶ V) [H : nonempty U] : function.injective (X.presheaf.map i.op) := begin rw injective_iff_map_eq_zero, intros x hx, rw ← basic_open_eq_bot_iff at ⊢ hx, rw Scheme.basic_open_res at hx, revert hx, contrapose!, simp_rw [← opens.not_nonempty_iff_eq_bot, not_not], apply nonempty_preirreducible_inter U.prop (RingedSpace.basic_open _ _).prop, simpa using H end end algebraic_geometry
af2997a07859549f848e03ba9dad72858a1771b9
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/field_theory/tower.lean
063b004b6e375a48a1cce02c223df0f82100e8d1
[ "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
5,082
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.algebra_tower import linear_algebra.matrix /-! # Tower of field extensions In this file we prove the tower law for arbitrary extensions and finite extensions. Suppose `L` is a field extension of `K` and `K` is a field extension of `F`. Then `[L:F] = [L:K] [K:F]` where `[E₁:E₂]` means the `E₂`-dimension of `E₁`. In fact we generalize it to vector spaces, where `L` is not necessarily a field, but just a vector space over `K`. ## Implementation notes We prove two versions, since there are two notions of dimensions: `vector_space.dim` which gives the dimension of an arbitrary vector space as a cardinal, and `finite_dimensional.findim` which gives the dimension of a finitely-dimensional vector space as a natural number. ## Tags tower law -/ universes u v w u₁ v₁ w₁ open_locale classical big_operators section field open cardinal variables (F : Type u) (K : Type v) (A : Type w) variables [field F] [field K] [add_comm_group A] variables [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim' : (cardinal.lift.{v w} (vector_space.dim F K) * cardinal.lift.{w v} (vector_space.dim K A) : cardinal.{max w v}) = cardinal.lift.{w v} (vector_space.dim F A) := let ⟨b, hb⟩ := exists_is_basis F K, ⟨c, hc⟩ := exists_is_basis K A in by rw [← (vector_space.dim F K).lift_id, ← hb.mk_eq_dim, ← (vector_space.dim K A).lift_id, ← hc.mk_eq_dim, ← lift_umax.{w v}, ← (hb.smul hc).mk_eq_dim, mk_prod, lift_mul, lift_lift, lift_lift, lift_lift, lift_lift, lift_umax] /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim (F : Type u) (K A : Type v) [field F] [field K] [add_comm_group A] [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] : vector_space.dim F K * vector_space.dim K A = vector_space.dim F A := by convert dim_mul_dim' F K A; rw lift_id namespace finite_dimensional theorem trans [finite_dimensional F K] [finite_dimensional K A] : finite_dimensional F A := let ⟨b, hb⟩ := exists_is_basis_finset F K in let ⟨c, hc⟩ := exists_is_basis_finset K A in of_finite_basis $ hb.smul hc lemma right [hf : finite_dimensional F A] : finite_dimensional K A := let ⟨b, hb⟩ := iff_fg.1 hf in iff_fg.2 ⟨b, @submodule.restrict_scalars'_injective F _ _ _ _ _ _ _ _ _ _ _ $ by { rw [submodule.restrict_scalars'_top, eq_top_iff, ← hb, submodule.span_le], exact submodule.subset_span }⟩ /-- Tower law: if `A` is a `K`-algebra and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem findim_mul_findim [finite_dimensional F K] [finite_dimensional K A] : findim F K * findim K A = findim F A := let ⟨b, hb⟩ := exists_is_basis_finset F K in let ⟨c, hc⟩ := exists_is_basis_finset K A in by rw [findim_eq_card_basis hb, findim_eq_card_basis hc, findim_eq_card_basis (hb.smul hc), fintype.card_prod] instance linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [vector_space F V] [add_comm_group W] [vector_space F W] [finite_dimensional F V] [finite_dimensional F W] : finite_dimensional F (V →ₗ[F] W) := let ⟨b, hb⟩ := exists_is_basis_finset F V in let ⟨c, hc⟩ := exists_is_basis_finset F W in (linear_equiv_matrix hb hc).symm.finite_dimensional lemma findim_linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [vector_space F V] [add_comm_group W] [vector_space F W] [finite_dimensional F V] [finite_dimensional F W] : findim F (V →ₗ[F] W) = findim F V * findim F W := let ⟨b, hb⟩ := exists_is_basis_finset F V in let ⟨c, hc⟩ := exists_is_basis_finset F W in by rw [linear_equiv.findim_eq (linear_equiv_matrix hb hc), matrix.findim_matrix, findim_eq_card_basis hb, findim_eq_card_basis hc, mul_comm] -- TODO: generalize by removing [finite_dimensional F K] -- V = ⊕F, -- (V →ₗ[F] K) = ((⊕F) →ₗ[F] K) = (⊕ (F →ₗ[F] K)) = ⊕K instance linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [vector_space F V] [finite_dimensional F V] : finite_dimensional K (V →ₗ[F] K) := right F _ _ lemma findim_linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [vector_space F V] [finite_dimensional F V] : findim K (V →ₗ[F] K) = findim F V := (nat.mul_right_inj $ show 0 < findim F K, from findim_pos).1 $ calc findim F K * findim K (V →ₗ[F] K) = findim F (V →ₗ[F] K) : findim_mul_findim _ _ _ ... = findim F V * findim F K : findim_linear_map F V K ... = findim F K * findim F V : mul_comm _ _ end finite_dimensional end field
8891a28beef14ef5d9a0a8b3997d65c1f875205f
4727251e0cd73359b15b664c3170e5d754078599
/src/data/rbtree/main.lean
605c3eef0f73a50fe12d73c2fd6c0f59de7ab2ae
[ "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
8,381
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree.find import data.rbtree.insert import data.rbtree.min_max universes u namespace rbnode variables {α : Type u} {lt : α → α → Prop} lemma is_searchable_of_well_formed {t : rbnode α} [is_strict_weak_order α lt] : t.well_formed lt → is_searchable lt t none none := begin intro h, induction h, { constructor, simp [lift] }, { subst h_n', apply is_searchable_insert, assumption } end open color lemma is_red_black_of_well_formed {t : rbnode α} : t.well_formed lt → ∃ c n, is_red_black t c n := begin intro h, induction h, { existsi black, existsi 0, constructor }, { cases h_ih with c ih, cases ih with n ih, subst h_n', apply insert_is_red_black, assumption } end end rbnode namespace rbtree variables {α : Type u} {lt : α → α → Prop} lemma balanced (t : rbtree α lt) : t.depth max ≤ 2 * t.depth min + 1 := begin cases t with n p, simp only [depth], have := rbnode.is_red_black_of_well_formed p, cases this with _ this, cases this with _ this, apply rbnode.balanced, assumption end lemma not_mem_mk_rbtree : ∀ (a : α), a ∉ mk_rbtree α lt := by simp [has_mem.mem, rbtree.mem, rbnode.mem, mk_rbtree] lemma not_mem_of_empty {t : rbtree α lt} (a : α) : t.empty = tt → a ∉ t := by cases t with n p; cases n; simp [empty, has_mem.mem, rbtree.mem, rbnode.mem, false_implies_iff] lemma mem_of_mem_of_eqv [is_strict_weak_order α lt] {t : rbtree α lt} {a b : α} : a ∈ t → a ≈[lt] b → b ∈ t := begin cases t with n p; simp [has_mem.mem, rbtree.mem]; clear p; induction n; simp only [rbnode.mem, strict_weak_order.equiv, false_implies_iff]; intros h₁ h₂; blast_disjs, iterate 2 { { have : rbnode.mem lt b n_lchild := n_ih_lchild h₁ h₂, simp [this] }, { simp [incomp_trans_of lt h₂.swap h₁] }, { have : rbnode.mem lt b n_rchild := n_ih_rchild h₁ h₂, simp [this] } } end section dec variables [decidable_rel lt] lemma insert_ne_mk_rbtree (t : rbtree α lt) (a : α) : t.insert a ≠ mk_rbtree α lt := begin cases t with n p, simp [insert, mk_rbtree], intro h, injection h with h', apply rbnode.insert_ne_leaf lt n a h' end lemma find_correct [is_strict_weak_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ (∃ b, t.find a = some b ∧ a ≈[lt] b) := begin cases t, apply rbnode.find_correct, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_correct_of_total [is_strict_total_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ t.find a = some a := iff.intro (λ h, match iff.mp (find_correct a t) h with | ⟨b, heq, heqv⟩ := by simp [heq, (eq_of_eqv_lt heqv).symm] end) (λ h, iff.mpr (find_correct a t) ⟨a, ⟨h, refl a⟩⟩) lemma find_correct_exact [is_strict_total_order α lt] (a : α) (t : rbtree α lt) : mem_exact a t ↔ t.find a = some a := begin cases t, apply rbnode.find_correct_exact, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_eqv [is_strict_weak_order α lt] (t : rbtree α lt) {x y} : x ≈[lt] y → (t.insert x).find y = some x := begin cases t, intro h, apply rbnode.find_insert_of_eqv lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert [is_strict_weak_order α lt] (t : rbtree α lt) (x) : (t.insert x).find x = some x := find_insert_of_eqv t (refl x) lemma find_insert_of_disj [is_strict_weak_order α lt] {x y : α} (t : rbtree α lt) : lt x y ∨ lt y x → (t.insert x).find y = t.find y := begin cases t, intro h, apply rbnode.find_insert_of_disj lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {x y : α} (t : rbtree α lt) : ¬ x ≈[lt] y → (t.insert x).find y = t.find y := begin cases t, intro h, apply rbnode.find_insert_of_not_eqv lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_ne [is_strict_total_order α lt] {x y : α} (t : rbtree α lt) : x ≠ y → (t.insert x).find y = t.find y := begin cases t, intro h, have : ¬ x ≈[lt] y := λ h', h (eq_of_eqv_lt h'), apply rbnode.find_insert_of_not_eqv lt this, apply rbnode.is_searchable_of_well_formed, assumption end lemma not_mem_of_find_none [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.find a = none → a ∉ t := λ h, iff.mpr (not_iff_not_of_iff (find_correct a t)) $ begin intro h, cases h with _ h, cases h with h₁ h₂, rw [h] at h₁, contradiction end lemma eqv_of_find_some [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a ≈[lt] b := begin cases t, apply rbnode.eqv_of_find_some, apply rbnode.is_searchable_of_well_formed, assumption end lemma eq_of_find_some [is_strict_total_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a = b := λ h, suffices a ≈[lt] b, from eq_of_eqv_lt this, eqv_of_find_some h lemma mem_of_find_some [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a ∈ t := λ h, iff.mpr (find_correct a t) ⟨b, ⟨h, eqv_of_find_some h⟩⟩ lemma find_eq_find_of_eqv [is_strict_weak_order α lt] {a b : α} (t : rbtree α lt) : a ≈[lt] b → t.find a = t.find b := begin cases t, apply rbnode.find_eq_find_of_eqv, apply rbnode.is_searchable_of_well_formed, assumption end lemma contains_correct [is_strict_weak_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ (t.contains a = tt) := begin have h := find_correct a t, simp [h, contains], apply iff.intro, { intro h', cases h' with _ h', cases h', simp [*], simp [option.is_some] }, { intro h', cases heq : find t a with v, simp [heq, option.is_some] at h', contradiction, existsi v, simp, apply eqv_of_find_some heq } end lemma mem_insert_of_incomp {a b : α} (t : rbtree α lt) : (¬ lt a b ∧ ¬ lt b a) → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_incomp end lemma mem_insert [is_irrefl α lt] : ∀ (a : α) (t : rbtree α lt), a ∈ t.insert a := begin intros, apply mem_insert_of_incomp, split; apply irrefl_of lt end lemma mem_insert_of_equiv {a b : α} (t : rbtree α lt) : a ≈[lt] b → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_incomp end lemma mem_insert_of_mem [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} (b : α) : a ∈ t → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_mem end lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → a ≈[lt] b ∨ a ∈ t := begin cases t, apply rbnode.equiv_or_mem_of_mem_insert end lemma incomp_or_mem_of_mem_ins [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → (¬ lt a b ∧ ¬ lt b a) ∨ a ∈ t := equiv_or_mem_of_mem_insert lemma eq_or_mem_of_mem_ins [is_strict_total_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → a = b ∨ a ∈ t := λ h, suffices a ≈[lt] b ∨ a ∈ t, by simp [eqv_lt_iff_eq] at this; assumption, incomp_or_mem_of_mem_ins h end dec lemma mem_of_min_eq [is_irrefl α lt] {a : α} {t : rbtree α lt} : t.min = some a → a ∈ t := begin cases t, apply rbnode.mem_of_min_eq end lemma mem_of_max_eq [is_irrefl α lt] {a : α} {t : rbtree α lt} : t.max = some a → a ∈ t := begin cases t, apply rbnode.mem_of_max_eq end lemma eq_leaf_of_min_eq_none {t : rbtree α lt} : t.min = none → t = mk_rbtree α lt := begin cases t, intro h, congr, apply rbnode.eq_leaf_of_min_eq_none h end lemma eq_leaf_of_max_eq_none {t : rbtree α lt} : t.max = none → t = mk_rbtree α lt := begin cases t, intro h, congr, apply rbnode.eq_leaf_of_max_eq_none h end lemma min_is_minimal [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.min = some a → ∀ {b}, b ∈ t → a ≈[lt] b ∨ lt a b := by { classical, cases t, apply rbnode.min_is_minimal, apply rbnode.is_searchable_of_well_formed, assumption } lemma max_is_maximal [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.max = some a → ∀ {b}, b ∈ t → a ≈[lt] b ∨ lt b a := by { cases t, apply rbnode.max_is_maximal, apply rbnode.is_searchable_of_well_formed, assumption } end rbtree
8e22ffa62fed1b38f49e4793da2922dedcef7c98
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/category/CommRing/adjunctions.lean
9cb12d59e49ca27ad92c4ece0e0840a74757e517
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
1,626
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl -/ import algebra.category.CommRing.basic import data.mv_polynomial.comm_ring /-! Multivariable polynomials on a type is the left adjoint of the forgetful functor from commutative rings to types. -/ noncomputable theory universe u open mv_polynomial open category_theory namespace CommRing open_locale classical /-- The free functor `Type u ⥤ CommRing` sending a type `X` to the multivariable (commutative) polynomials with variables `x : X`. -/ def free : Type u ⥤ CommRing.{u} := { obj := λ α, of (mv_polynomial α ℤ), map := λ X Y f, (↑(rename f : _ →ₐ[ℤ] _) : (mv_polynomial X ℤ →+* mv_polynomial Y ℤ)), -- TODO these next two fields can be done by `tidy`, but the calls in `dsimp` and `simp` it -- generates are too slow. map_id' := λ X, ring_hom.ext $ rename_id, map_comp' := λ X Y Z f g, ring_hom.ext $ λ p, (rename_rename f g p).symm } @[simp] lemma free_obj_coe {α : Type u} : (free.obj α : Type u) = mv_polynomial α ℤ := rfl @[simp] lemma free_map_coe {α β : Type u} {f : α → β} : ⇑(free.map f) = rename f := rfl /-- The free-forgetful adjunction for commutative rings. -/ def adj : free ⊣ forget CommRing.{u} := adjunction.mk_of_hom_equiv { hom_equiv := λ X R, hom_equiv, hom_equiv_naturality_left_symm' := λ _ _ Y f g, ring_hom.ext $ λ x, eval₂_cast_comp f (int.cast_ring_hom Y) g x } instance : is_right_adjoint (forget CommRing.{u}) := ⟨_, adj⟩ end CommRing
e7066cf227df61d578f8187207328e1cabb22d5a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/modular_forms/basic.lean
01c52760e61b2cf66a43f3faee060c193ccd1c5a
[ "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
11,276
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import analysis.complex.upper_half_plane.functions_bounded_at_infty import analysis.complex.upper_half_plane.manifold import number_theory.modular_forms.slash_invariant_forms /-! # Modular forms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines modular forms and proves some basic properties about them. We begin by defining modular forms and cusp forms as extension of `slash_invariant_forms` then we define the space of modular forms, cusp forms and prove that the product of two modular forms is a modular form. -/ open complex upper_half_plane open_locale topology manifold upper_half_plane noncomputable theory local prefix `↑ₘ`:1024 := @coe _ (matrix (fin 2) (fin 2) _) _ local notation `GL(` n `, ` R `)`⁺ := matrix.GL_pos (fin n) R local notation `SL(` n `, ` R `)` := matrix.special_linear_group (fin n) R section modular_form open modular_form variables (F : Type*) (Γ : subgroup SL(2, ℤ)) (k : ℤ) open_locale modular_form set_option old_structure_cmd true /--These are `slash_invariant_form`'s that are holomophic and bounded at infinity. -/ structure modular_form extends slash_invariant_form Γ k := (holo' : mdifferentiable 𝓘(ℂ) 𝓘(ℂ) (to_fun : ℍ → ℂ)) (bdd_at_infty' : ∀ (A : SL(2, ℤ)), is_bounded_at_im_infty (to_fun ∣[k] A)) /-- The `slash_invariant_form` associated to a `modular_form`. -/ add_decl_doc modular_form.to_slash_invariant_form /--These are `slash_invariant_form`s that are holomophic and zero at infinity. -/ structure cusp_form extends slash_invariant_form Γ k := (holo' : mdifferentiable 𝓘(ℂ) 𝓘(ℂ) (to_fun : ℍ → ℂ)) (zero_at_infty' : ∀ (A : SL(2, ℤ)), is_zero_at_im_infty (to_fun ∣[k] A)) /-- The `slash_invariant_form` associated to a `cusp_form`. -/ add_decl_doc cusp_form.to_slash_invariant_form /--`modular_form_class F Γ k` says that `F` is a type of bundled functions that extend `slash_invariant_form_class` by requiring that the functions be holomorphic and bounded at infinity. -/ class modular_form_class extends slash_invariant_form_class F Γ k := (holo: ∀ f : F, mdifferentiable 𝓘(ℂ) 𝓘(ℂ) (f : ℍ → ℂ)) (bdd_at_infty : ∀ (f : F) (A : SL(2, ℤ)), is_bounded_at_im_infty (f ∣[k] A)) /--`cusp_form_class F Γ k` says that `F` is a type of bundled functions that extend `slash_invariant_form_class` by requiring that the functions be holomorphic and zero at infinity. -/ class cusp_form_class extends slash_invariant_form_class F Γ k := (holo: ∀ f : F, mdifferentiable 𝓘(ℂ) 𝓘(ℂ) (f : ℍ → ℂ)) (zero_at_infty : ∀ (f : F) (A : SL(2, ℤ)), is_zero_at_im_infty (f ∣[k] A)) @[priority 100] instance modular_form_class.modular_form : modular_form_class (modular_form Γ k) Γ k := { coe := modular_form.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', slash_action_eq := modular_form.slash_action_eq', holo:= modular_form.holo', bdd_at_infty := modular_form.bdd_at_infty' } @[priority 100] instance cusp_form_class.cusp_form : cusp_form_class (cusp_form Γ k) Γ k := { coe := cusp_form.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', slash_action_eq := cusp_form.slash_action_eq', holo:= cusp_form.holo', zero_at_infty := cusp_form.zero_at_infty' } variables {F Γ k} @[simp] lemma modular_form_to_fun_eq_coe {f : modular_form Γ k} : f.to_fun = (f : ℍ → ℂ) := rfl @[simp] lemma cusp_form_to_fun_eq_coe {f : cusp_form Γ k} : f.to_fun = (f : ℍ → ℂ) := rfl @[ext] theorem modular_form.ext {f g : modular_form Γ k} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h @[ext] theorem cusp_form.ext {f g : cusp_form Γ k} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h /-- Copy of a `modular_form` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def modular_form.copy (f : modular_form Γ k) (f' : ℍ → ℂ) (h : f' = ⇑f) : modular_form Γ k := { to_fun := f', slash_action_eq' := h.symm ▸ f.slash_action_eq', holo' := h.symm ▸ f.holo', bdd_at_infty' := λ A, h.symm ▸ f.bdd_at_infty' A } /-- Copy of a `cusp_form` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def cusp_form.copy (f : cusp_form Γ k) (f' : ℍ → ℂ) (h : f' = ⇑f) : cusp_form Γ k := { to_fun := f', slash_action_eq' := h.symm ▸ f.slash_action_eq', holo' := h.symm ▸ f.holo', zero_at_infty' := λ A, h.symm ▸ f.zero_at_infty' A } end modular_form namespace modular_form open slash_invariant_form variables {F : Type*} {Γ : subgroup SL(2, ℤ)} {k : ℤ} instance has_add : has_add (modular_form Γ k) := ⟨ λ f g, { holo' := f.holo'.add g.holo', bdd_at_infty' := λ A, by simpa using (f.bdd_at_infty' A).add (g.bdd_at_infty' A), .. (f : slash_invariant_form Γ k) + g }⟩ @[simp] lemma coe_add (f g : modular_form Γ k) : ⇑(f + g) = f + g := rfl @[simp] lemma add_apply (f g : modular_form Γ k) (z : ℍ) : (f + g) z = f z + g z := rfl instance has_zero : has_zero (modular_form Γ k) := ⟨ { holo' := (λ _, mdifferentiable_at_const 𝓘(ℂ, ℂ) 𝓘(ℂ, ℂ)), bdd_at_infty' := λ A, by simpa using zero_form_is_bounded_at_im_infty, .. (0 : slash_invariant_form Γ k) } ⟩ @[simp] lemma coe_zero : ⇑(0 : modular_form Γ k) = (0 : ℍ → ℂ) := rfl @[simp] lemma zero_apply (z : ℍ) : (0 : modular_form Γ k) z = 0 := rfl section variables {α : Type*} [has_smul α ℂ] [is_scalar_tower α ℂ ℂ] instance has_smul : has_smul α (modular_form Γ k) := ⟨ λ c f, { to_fun := c • f, holo' := by simpa using f.holo'.const_smul (c • (1 : ℂ)), bdd_at_infty' := λ A, by simpa using (f.bdd_at_infty' A).const_smul_left (c • (1 : ℂ)), .. c • (f : slash_invariant_form Γ k)}⟩ @[simp] lemma coe_smul (f : (modular_form Γ k)) (n : α) : ⇑(n • f) = n • f := rfl @[simp] lemma smul_apply (f : (modular_form Γ k)) (n : α) (z : ℍ) : (n • f) z = n • (f z) := rfl end instance has_neg : has_neg (modular_form Γ k) := ⟨λ f, { to_fun := -f, holo' := f.holo'.neg, bdd_at_infty':= λ A, by simpa using (f.bdd_at_infty' A).neg, .. -(f : slash_invariant_form Γ k) }⟩ @[simp] lemma coe_neg (f : modular_form Γ k) : ⇑(-f) = -f := rfl @[simp] lemma neg_apply (f : modular_form Γ k) (z : ℍ) : (-f) z = - (f z) := rfl instance has_sub : has_sub (modular_form Γ k) := ⟨ λ f g, f + -g ⟩ @[simp] lemma coe_sub (f g : (modular_form Γ k)) : ⇑(f - g) = f - g := rfl @[simp] lemma sub_apply (f g : modular_form Γ k) (z : ℍ) : (f - g) z = f z - g z := rfl instance : add_comm_group (modular_form Γ k) := fun_like.coe_injective.add_comm_group _ rfl coe_add coe_neg coe_sub coe_smul coe_smul /--Additive coercion from `modular_form` to `ℍ → ℂ`. -/ @[simps] def coe_hom : (modular_form Γ k) →+ (ℍ → ℂ) := { to_fun := λ f, f, map_zero' := coe_zero, map_add' := λ _ _, rfl } instance : module ℂ (modular_form Γ k) := function.injective.module ℂ coe_hom fun_like.coe_injective (λ _ _, rfl) instance : inhabited (modular_form Γ k) := ⟨0⟩ /--The modular form of weight `k_1 + k_2` given by the product of two modular forms of weights `k_1` and `k_2`. -/ def mul {k_1 k_2 : ℤ} {Γ : subgroup SL(2, ℤ)} (f : (modular_form Γ k_1)) (g : (modular_form Γ k_2)) : (modular_form Γ (k_1 + k_2)) := { to_fun := f * g, slash_action_eq' := λ A, by simp_rw [mul_slash_subgroup, modular_form_class.slash_action_eq], holo' := f.holo'.mul g.holo', bdd_at_infty' := λ A, by simpa using (f.bdd_at_infty' A).mul (g.bdd_at_infty' A) } @[simp] lemma mul_coe {k_1 k_2 : ℤ} {Γ : subgroup SL(2, ℤ)} (f : (modular_form Γ k_1)) (g : (modular_form Γ k_2)) : ((f.mul g) : ℍ → ℂ) = f * g := rfl instance : has_one (modular_form Γ 0) := ⟨{ holo' := λ x, mdifferentiable_at_const 𝓘(ℂ, ℂ) 𝓘(ℂ, ℂ), bdd_at_infty' := λ A, by simpa using at_im_infty.const_bounded_at_filter (1:ℂ), .. (1 : slash_invariant_form Γ 0) }⟩ @[simp] lemma one_coe_eq_one : ((1 : modular_form Γ 0) : ℍ → ℂ) = 1 := rfl end modular_form namespace cusp_form open modular_form variables {F : Type*} {Γ : subgroup SL(2, ℤ)} {k : ℤ} instance has_add : has_add (cusp_form Γ k) := ⟨ λ f g, { to_fun := f + g, holo' := f.holo'.add g.holo', zero_at_infty' := λ A, by simpa using (f.zero_at_infty' A).add (g.zero_at_infty' A), .. (f : slash_invariant_form Γ k) + g }⟩ @[simp] lemma coe_add (f g : cusp_form Γ k) : ⇑(f + g) = f + g := rfl @[simp] lemma add_apply (f g : cusp_form Γ k) (z : ℍ) : (f + g) z = f z + g z := rfl instance has_zero : has_zero (cusp_form Γ k) := ⟨ { to_fun := 0, holo' := (λ _, mdifferentiable_at_const 𝓘(ℂ, ℂ) 𝓘(ℂ, ℂ)), zero_at_infty' := by simpa using filter.zero_zero_at_filter _, .. (0 : slash_invariant_form Γ k) }⟩ @[simp] lemma coe_zero : ⇑(0 : cusp_form Γ k) = (0 : ℍ → ℂ) := rfl @[simp] lemma zero_apply (z : ℍ) : (0 : cusp_form Γ k) z = 0 := rfl section variables {α : Type*} [has_smul α ℂ] [is_scalar_tower α ℂ ℂ] instance has_smul : has_smul α (cusp_form Γ k) := ⟨ λ c f, { to_fun := c • f, holo' := by simpa using f.holo'.const_smul (c • (1 : ℂ)), zero_at_infty' := λ A, by simpa using (f.zero_at_infty' A).smul (c • (1 : ℂ)), .. c • (f : slash_invariant_form Γ k) }⟩ @[simp] lemma coe_smul (f : (cusp_form Γ k)) (n : α) : ⇑(n • f) = n • f := rfl @[simp] lemma smul_apply (f : (cusp_form Γ k)) (n : α) {z : ℍ} : (n • f) z = n • (f z) := rfl end instance has_neg : has_neg (cusp_form Γ k) := ⟨λ f, { to_fun := -f, holo' := f.holo'.neg, zero_at_infty':= λ A, by simpa using (f.zero_at_infty' A).neg, .. -(f : slash_invariant_form Γ k)} ⟩ @[simp] lemma coe_neg (f : cusp_form Γ k) : ⇑(-f) = -f := rfl @[simp] lemma neg_apply (f : cusp_form Γ k) (z : ℍ) : (-f) z = -(f z) := rfl instance has_sub : has_sub (cusp_form Γ k) := ⟨ λ f g, f + -g ⟩ @[simp] lemma coe_sub (f g : cusp_form Γ k) : ⇑(f - g) = f - g := rfl @[simp] lemma sub_apply (f g : cusp_form Γ k) (z : ℍ) : (f - g) z = f z - g z := rfl instance : add_comm_group (cusp_form Γ k) := fun_like.coe_injective.add_comm_group _ rfl coe_add coe_neg coe_sub coe_smul coe_smul /--Additive coercion from `cusp_form` to `ℍ → ℂ`. -/ @[simps] def coe_hom : (cusp_form Γ k) →+ (ℍ → ℂ) := { to_fun := λ f, f, map_zero' := cusp_form.coe_zero, map_add' := λ _ _, rfl } instance : module ℂ (cusp_form Γ k) := function.injective.module ℂ coe_hom fun_like.coe_injective (λ _ _, rfl) instance : inhabited (cusp_form Γ k) := ⟨0⟩ @[priority 99] instance [cusp_form_class F Γ k] : modular_form_class F Γ k := { coe := fun_like.coe, coe_injective' := fun_like.coe_injective', slash_action_eq := cusp_form_class.slash_action_eq, holo:= cusp_form_class.holo, bdd_at_infty := λ _ _, (cusp_form_class.zero_at_infty _ _).bounded_at_filter} end cusp_form
e325d51f5608abe86ed5dd4ed6452ba66b7b96d4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/coe1.lean
3f402f4acc6044a90a116b1ab1191ac99fb03f81
[ "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
866
lean
check if tt then "a" else "b" /- Remark: in the standard library nat_to_int and int_to_real are has_lift instances instead of has_coe. -/ constant int : Type constant real : Type constant nat_to_int : has_coe nat int constant int_to_real : has_coe int real attribute [instance] nat_to_int int_to_real constant sine : real → real constants n m : nat constants i j : int constants x y : real check sine x check sine n check sine i constant int_has_add : has_add int constant real_has_add : has_add real attribute [instance] int_has_add real_has_add check x + i /- The following one does not work because the implicit argument ?A of add is bound to int when x is processed. -/ check i + x -- FAIL /- The workaround is to use the explicit lift -/ check ↑i + x check x + n check n + x -- FAIL check ↑n + x check (i:real) + x check (n:real) + x
61ac6f0363ff4f238f1a4efdf831d5751e6b26db
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/sheaves/sheaf.lean
794e94d5c2aa88bfdeebacd54d6b18a97ff70b11
[ "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
5,257
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.sheaf_condition.equalizer_products import category_theory.full_subcategory import category_theory.limits.unit import category_theory.sites.sheaf import category_theory.sites.spaces /-! # Sheaves We define sheaves on a topological space, with values in an arbitrary category. A presheaf on a topological space `X` is a sheaf presicely when it is a sheaf under the grothendieck topology on `opens X`, which expands out to say: For each open cover `{ Uᵢ }` of `U`, and a family of compatible functions `A ⟶ F(Uᵢ)` for an `A : X`, there exists an unique gluing `A ⟶ F(U)` compatible with the restriction. See the docstring of `Top.presheaf.is_sheaf` for an explanation on the design descisions and a list of equivalent conditions. We provide the instance `category (sheaf C X)` as the full subcategory of presheaves, and the fully faithful functor `sheaf.forget : sheaf C X ⥤ presheaf C X`. -/ universes w v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] variables {X : Top.{w}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf open sheaf_condition_equalizer_products /-- The sheaf condition has several different equivalent formulations. The official definition chosen here is in terms of grothendieck topologies so that the results on sites could be applied here easily, and this condition does not require additional constraints on the value category. The equivalent formulations of the sheaf condition on `presheaf C X` are as follows : 1. `Top.presheaf.is_sheaf`: (the official definition) It is a sheaf with respect to the grothendieck topology on `opens X`, which is to say: For each open cover `{ Uᵢ }` of `U`, and a family of compatible functions `A ⟶ F(Uᵢ)` for an `A : X`, there exists an unique gluing `A ⟶ F(U)` compatible with the restriction. 2. `Top.presheaf.is_sheaf_equalizer_products`: (requires `C` to have all products) For each open cover `{ Uᵢ }` of `U`, `F(U) ⟶ ∏ F(Uᵢ)` is the equalizer of the two morphisms `∏ F(Uᵢ) ⟶ ∏ F(Uᵢ ∩ Uⱼ)`. See `Top.presheaf.is_sheaf_iff_is_sheaf_equalizer_products`. 3. `Top.presheaf.is_sheaf_opens_le_cover`: Each `F(U)` is the (inverse) limit of all `F(V)` with `V ⊆ U`. See `Top.presheaf.is_sheaf_iff_is_sheaf_opens_le_cover`. 4. `Top.presheaf.is_sheaf_pairwise_intersections`: For each open cover `{ Uᵢ }` of `U`, `F(U)` is the limit of all `F(Uᵢ)` and all `F(Uᵢ ∩ Uⱼ)`. See `Top.presheaf.is_sheaf_iff_is_sheaf_pairwise_intersections`. The following requires `C` to be concrete and complete, and `forget C` to reflect isomorphisms and preserve limits. This applies to most "algebraic" categories, e.g. groups, abelian groups and rings. 5. `Top.presheaf.is_sheaf_unique_gluing`: (requires `C` to be concrete and complete; `forget C` to reflect isomorphisms and preserve limits) For each open cover `{ Uᵢ }` of `U`, and a compatible family of elements `x : F(Uᵢ)`, there exists a unique gluing `x : F(U)` that restricts to the given elements. See `Top.presheaf.is_sheaf_iff_is_sheaf_unique_gluing`. 6. The underlying sheaf of types is a sheaf. See `Top.presheaf.is_sheaf_iff_is_sheaf_comp` and `category_theory.presheaf.is_sheaf_iff_is_sheaf_forget`. -/ def is_sheaf (F : presheaf.{w v u} C X) : Prop := presheaf.is_sheaf (opens.grothendieck_topology X) F /-- The presheaf valued in `unit` over any topological space is a sheaf. -/ lemma is_sheaf_unit (F : presheaf (category_theory.discrete unit) X) : F.is_sheaf := λ x U S hS x hx, ⟨eq_to_hom (subsingleton.elim _ _), by tidy, by tidy⟩ lemma is_sheaf_iso_iff {F G : presheaf C X} (α : F ≅ G) : F.is_sheaf ↔ G.is_sheaf := presheaf.is_sheaf_of_iso_iff α /-- Transfer the sheaf condition across an isomorphism of presheaves. -/ lemma is_sheaf_of_iso {F G : presheaf C X} (α : F ≅ G) (h : F.is_sheaf) : G.is_sheaf := (is_sheaf_iso_iff α).1 h end presheaf variables (C X) /-- A `sheaf C X` is a presheaf of objects from `C` over a (bundled) topological space `X`, satisfying the sheaf condition. -/ @[derive category] def sheaf : Type (max u v w) := Sheaf (opens.grothendieck_topology X) C variables {C X} /-- The underlying presheaf of a sheaf -/ abbreviation sheaf.presheaf (F : X.sheaf C) : Top.presheaf C X := F.1 variables (C X) -- Let's construct a trivial example, to keep the inhabited linter happy. instance sheaf_inhabited : inhabited (sheaf (category_theory.discrete punit) X) := ⟨⟨functor.star _, presheaf.is_sheaf_unit _⟩⟩ namespace sheaf /-- The forgetful functor from sheaves to presheaves. -/ @[derive [full, faithful]] def forget : Top.sheaf C X ⥤ Top.presheaf C X := Sheaf_to_presheaf _ _ -- Note: These can be proved by simp. lemma id_app (F : sheaf C X) (t) : (𝟙 F : F ⟶ F).1.app t = 𝟙 _ := rfl lemma comp_app {F G H : sheaf C X} (f : F ⟶ G) (g : G ⟶ H) (t) : (f ≫ g).1.app t = f.1.app t ≫ g.1.app t := rfl end sheaf end Top
2f9903986b88f40adb6a3d0e19183af067352596
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/prime_counting.lean
6a699a1ae127d1d80886515bc4b40dbd30633349
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,485
lean
/- Copyright (c) 2021 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import data.nat.prime_fin import data.nat.totient import data.finset.locally_finite import data.nat.count import data.nat.nth /-! # The Prime Counting Function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define the prime counting function: the function on natural numbers that returns the number of primes less than or equal to its input. ## Main Results The main definitions for this file are - `nat.prime_counting`: The prime counting function π - `nat.prime_counting'`: π(n - 1) We then prove that these are monotone in `nat.monotone_prime_counting` and `nat.monotone_prime_counting'`. The last main theorem `nat.prime_counting'_add_le` is an upper bound on `π'` which arises by observing that all numbers greater than `k` and not coprime to `k` are not prime, and so only at most `φ(k)/k` fraction of the numbers from `k` to `n` are prime. ## Notation We use the standard notation `π` to represent the prime counting function (and `π'` to represent the reindexed version). -/ namespace nat open finset /-- A variant of the traditional prime counting function which gives the number of primes *strictly* less than the input. More convenient for avoiding off-by-one errors. -/ def prime_counting' : ℕ → ℕ := nat.count prime /-- The prime counting function: Returns the number of primes less than or equal to the input. -/ def prime_counting (n : ℕ) : ℕ := prime_counting' (n + 1) localized "notation (name := prime_counting) `π` := nat.prime_counting" in nat localized "notation (name := prime_counting') `π'` := nat.prime_counting'" in nat lemma monotone_prime_counting' : monotone prime_counting' := count_monotone prime lemma monotone_prime_counting : monotone prime_counting := monotone_prime_counting'.comp (monotone_id.add_const _) @[simp] lemma prime_counting'_nth_eq (n : ℕ) : π' (nth prime n) = n := count_nth_of_infinite infinite_set_of_prime _ @[simp] lemma prime_nth_prime (n : ℕ) : prime (nth prime n) := nth_mem_of_infinite infinite_set_of_prime _ /-- A linear upper bound on the size of the `prime_counting'` function -/ lemma prime_counting'_add_le {a k : ℕ} (h0 : 0 < a) (h1 : a < k) (n : ℕ) : π' (k + n) ≤ π' k + nat.totient a * (n / a + 1) := calc π' (k + n) ≤ ((range k).filter (prime)).card + ((Ico k (k + n)).filter (prime)).card : begin rw [prime_counting', count_eq_card_filter_range, range_eq_Ico, ←Ico_union_Ico_eq_Ico (zero_le k) (le_self_add), filter_union], apply card_union_le, end ... ≤ π' k + ((Ico k (k + n)).filter (prime)).card : by rw [prime_counting', count_eq_card_filter_range] ... ≤ π' k + ((Ico k (k + n)).filter (coprime a)).card : begin refine add_le_add_left (card_le_of_subset _) k.prime_counting', simp only [subset_iff, and_imp, mem_filter, mem_Ico], intros p succ_k_le_p p_lt_n p_prime, split, { exact ⟨succ_k_le_p, p_lt_n⟩, }, { rw coprime_comm, exact coprime_of_lt_prime h0 (gt_of_ge_of_gt succ_k_le_p h1) p_prime, }, end ... ≤ π' k + totient a * (n / a + 1) : begin rw [add_le_add_iff_left], exact Ico_filter_coprime_le k n h0, end end nat
47a3d8353c7a323a1703d99c0fe3bfcbec5e0d19
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world8/level2.lean
5db05a15521f62cc8f86b7ca37bb0546b7b60286
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,429
lean
import mynat.definition -- hide import mynat.add -- hide import game.world8.level1 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 2: `succ_succ_inj`. -/ /- In the below theorem, we need to apply `succ_inj` twice. Once to prove $succ(succ(a))=succ(succ(b))\implies succ(a)=succ(b)$, and then again to prove $succ(a)=succ(b)\implies a=b$. However `succ(a)=succ(b)` is nowhere to be found, it's neither an assumption or a goal when we start this level. You can make it with `have` or you can use `apply`. -/ /- Theorem For all naturals $a$ and $b$, if we assume $succ(succ(a))=succ(succ(b))$, then we can deduce $a=b$. -/ theorem succ_succ_inj {a b : mynat} (h : succ(succ(a)) = succ(succ(b))) : a = b := begin [less_leaky] have h2 : succ(a)=succ(b), exact succ_inj(h), exact succ_inj(h2), end /- ## Sample solutions to this level. Make sure you understand them all. And remember that `rw` is no use to us here, `rw` works only with equalities or `↔` statements, not implications or functions. -/ example {a b : mynat} (h : succ(succ(a)) = succ(succ(b))) : a = b := begin apply succ_inj, apply succ_inj, exact h end example {a b : mynat} (h : succ(succ(a)) = succ(succ(b))) : a = b := begin apply succ_inj, exact succ_inj(h), end example {a b : mynat} (h : succ(succ(a)) = succ(succ(b))) : a = b := begin exact succ_inj(succ_inj(h)), end end mynat -- hide
8f32a1104d9ca6cfed60dbac5e48f5440270332c
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/category/CommRing/adjunctions.lean
b5f826c7d3c73d1a83da34fa4ac09b9b69252bcd
[ "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
1,446
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl -/ import algebra.category.CommRing.basic import data.mv_polynomial /-! Multivariable polynomials on a type is the left adjoint of the forgetful functor from commutative rings to types. -/ noncomputable theory universe u open mv_polynomial open category_theory namespace CommRing open_locale classical /-- The free functor `Type u ⥤ CommRing` sending a type `X` to the multivariable (commutative) polynomials with variables `x : X`. -/ def free : Type u ⥤ CommRing := { obj := λ α, of (mv_polynomial α ℤ), map := λ X Y f, (rename f), -- TODO these next two fields can be done by `tidy`, but the calls in `dsimp` and `simp` it generates are too slow. map_id' := λ X, ring_hom.ext $ rename_id, map_comp' := λ X Y Z f g, ring_hom.ext $ λ p, (rename_rename f g p).symm } @[simp] lemma free_obj_coe {α : Type u} : (free.obj α : Type u) = mv_polynomial α ℤ := rfl @[simp] lemma free_map_coe {α β : Type u} {f : α → β} : ⇑(free.map f) = rename f := rfl /-- The free-forgetful adjunction for commutative rings. -/ def adj : free ⊣ forget CommRing := adjunction.mk_of_hom_equiv { hom_equiv := λ X R, hom_equiv, hom_equiv_naturality_left_symm' := by intros; ext; apply eval₂_cast_comp f (int.cast_ring_hom Y) g x } end CommRing
7c24bda888c89e4cf4df6edf11767a2d6c205c1d
88892181780ff536a81e794003fe058062f06758
/src/100_theorems/t007.lean
bd6392f796232d054efc67b2bb215d6847efe752
[]
no_license
AtnNn/lean-sandbox
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
8c68afbdc09213173aef1be195da7a9a86060a97
refs/heads/master
1,623,004,395,876
1,579,969,507,000
1,579,969,507,000
146,666,368
0
0
null
null
null
null
UTF-8
Lean
false
false
257
lean
import data.zmod.quadratic_reciprocity open zmodp theorem t007 {p q : ℕ} : Π (hp : nat.prime p) (hq : nat.prime q), p % 2 = 1 → q % 2 = 1 → p ≠ q → legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := quadratic_reciprocity
dec071e35de6a8bc0effd6236dd2491fccba5793
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Compiler/IR/Format.lean
ddd7cf7eea1c60c001c9314acfe16cb4bf7f9bbb
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
7,086
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.Basic namespace Lean namespace IR private def formatArg : Arg → Format | Arg.var id => format id | Arg.irrelevant => "◾" instance : ToFormat Arg := ⟨formatArg⟩ def formatArray {α : Type} [ToFormat α] (args : Array α) : Format := args.foldl (fun r a => r ++ " " ++ format a) Format.nil private def formatLitVal : LitVal → Format | LitVal.num v => format v | LitVal.str v => format (repr v) instance : ToFormat LitVal := ⟨formatLitVal⟩ private def formatCtorInfo : CtorInfo → Format | { name := name, cidx := cidx, usize := usize, ssize := ssize, .. } => Id.run do let mut r := f!"ctor_{cidx}" if usize > 0 || ssize > 0 then r := f!"{r}.{usize}.{ssize}" if name != Name.anonymous then r := f!"{r}[{name}]" r instance : ToFormat CtorInfo := ⟨formatCtorInfo⟩ private def formatExpr : Expr → Format | Expr.ctor i ys => format i ++ formatArray ys | Expr.reset n x => "reset[" ++ format n ++ "] " ++ format x | Expr.reuse x i u ys => "reuse" ++ (if u then "!" else "") ++ " " ++ format x ++ " in " ++ format i ++ formatArray ys | Expr.proj i x => "proj[" ++ format i ++ "] " ++ format x | Expr.uproj i x => "uproj[" ++ format i ++ "] " ++ format x | Expr.sproj n o x => "sproj[" ++ format n ++ ", " ++ format o ++ "] " ++ format x | Expr.fap c ys => format c ++ formatArray ys | Expr.pap c ys => "pap " ++ format c ++ formatArray ys | Expr.ap x ys => "app " ++ format x ++ formatArray ys | Expr.box _ x => "box " ++ format x | Expr.unbox x => "unbox " ++ format x | Expr.lit v => format v | Expr.isShared x => "isShared " ++ format x | Expr.isTaggedPtr x => "isTaggedPtr " ++ format x instance : ToFormat Expr := ⟨formatExpr⟩ instance : ToString Expr := ⟨fun e => Format.pretty (format e)⟩ private partial def formatIRType : IRType → Format | IRType.float => "float" | IRType.uint8 => "u8" | IRType.uint16 => "u16" | IRType.uint32 => "u32" | IRType.uint64 => "u64" | IRType.usize => "usize" | IRType.irrelevant => "◾" | IRType.object => "obj" | IRType.tobject => "tobj" | IRType.struct _ tys => let _ : ToFormat IRType := ⟨formatIRType⟩ "struct " ++ Format.bracket "{" (Format.joinSep tys.toList ", ") "}" | IRType.union _ tys => let _ : ToFormat IRType := ⟨formatIRType⟩ "union " ++ Format.bracket "{" (Format.joinSep tys.toList ", ") "}" instance : ToFormat IRType := ⟨formatIRType⟩ instance : ToString IRType := ⟨toString ∘ format⟩ private def formatParam : Param → Format | { x := name, borrow := b, ty := ty } => "(" ++ format name ++ " : " ++ (if b then "@& " else "") ++ format ty ++ ")" instance : ToFormat Param := ⟨formatParam⟩ def formatAlt (fmt : FnBody → Format) (indent : Nat) : Alt → Format | Alt.ctor i b => format i.name ++ " →" ++ Format.nest indent (Format.line ++ fmt b) | Alt.default b => "default →" ++ Format.nest indent (Format.line ++ fmt b) def formatParams (ps : Array Param) : Format := formatArray ps def formatFnBodyHead : FnBody → Format | FnBody.vdecl x ty e _ => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e | FnBody.jdecl j xs _ _ => format j ++ formatParams xs ++ " := ..." | FnBody.set x i y _ => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.uset x i y _ => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.sset x i o y ty _ => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y | FnBody.setTag x cidx _ => "setTag " ++ format x ++ " := " ++ format cidx | FnBody.inc x n _ _ _ => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.dec x n _ _ _ => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.del x _ => "del " ++ format x | FnBody.mdata d _ => "mdata " ++ format d | FnBody.case _ x _ _ => "case " ++ format x ++ " of ..." | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" @[export lean_ir_format_fn_body_head] private def formatFnBodyHead' (fn : FnBody) : String := formatFnBodyHead fn |>.pretty partial def formatFnBody (fnBody : FnBody) (indent : Nat := 2) : Format := let rec loop : FnBody → Format | FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e ++ ";" ++ Format.line ++ loop b | FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " :=" ++ Format.nest indent (Format.line ++ loop v) ++ ";" ++ Format.line ++ loop b | FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx ++ ";" ++ Format.line ++ loop b | FnBody.inc x n _ _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.dec x n _ _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.del x b => "del " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.mdata d b => "mdata " ++ format d ++ ";" ++ Format.line ++ loop b | FnBody.case _ x xType cs => "case " ++ format x ++ " : " ++ format xType ++ " of" ++ cs.foldl (fun r c => r ++ Format.line ++ formatAlt loop indent c) Format.nil | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" loop fnBody instance : ToFormat FnBody := ⟨formatFnBody⟩ instance : ToString FnBody := ⟨fun b => (format b).pretty⟩ def formatDecl (decl : Decl) (indent : Nat := 2) : Format := match decl with | Decl.fdecl f xs ty b _ => "def " ++ format f ++ formatParams xs ++ format " : " ++ format ty ++ " :=" ++ Format.nest indent (Format.line ++ formatFnBody b indent) | Decl.extern f xs ty _ => "extern " ++ format f ++ formatParams xs ++ format " : " ++ format ty instance : ToFormat Decl := ⟨formatDecl⟩ @[export lean_ir_decl_to_string] def declToString (d : Decl) : String := (format d).pretty instance : ToString Decl := ⟨declToString⟩ end Lean.IR
ba269858e4290c68076885816e9ca8a36c92527d
82e44445c70db0f03e30d7be725775f122d72f3e
/src/group_theory/perm/support.lean
756db5e046eea854ff3ff1de2e1b463d90ed66c3
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
19,313
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Aaron Anderson, Yakov Pechersky -/ import data.finset.sort import data.fintype.basic import group_theory.perm.basic /-! # Support of a permutation ## Main definitions In the following, `f g : equiv.perm α`. * `equiv.perm.disjoint`: two permutations `f` and `g` are `disjoint` if every element is fixed either by `f`, or by `g`. Equivalently, `f` and `g` are `disjoint` iff their `support` are disjoint. * `equiv.perm.is_swap`: `f = swap x y` for `x ≠ y`. * `equiv.perm.support`: the elements `x : α` that are not fixed by `f`. -/ open equiv finset namespace equiv.perm variables {α : Type*} section disjoint /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x variables {f g h : perm α} @[symm] lemma disjoint.symm : disjoint f g → disjoint g f := by simp only [disjoint, or.comm, imp_self] lemma disjoint.symmetric : symmetric (@disjoint α) := λ _ _, disjoint.symm lemma disjoint_comm : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint.commute (h : disjoint f g) : commute f g := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_iff_eq_or_eq : disjoint f g ↔ ∀ (x : α), f x = x ∨ g x = x := iff.rfl @[simp] lemma disjoint_refl_iff : disjoint f f ↔ f = 1 := begin refine ⟨λ h, _, λ h, h.symm ▸ disjoint_one_left 1⟩, ext x, cases h x with hx hx; simp [hx] end lemma disjoint.inv_left (h : disjoint f g) : disjoint f⁻¹ g := begin intro x, rw [inv_eq_iff_eq, eq_comm], exact h x end lemma disjoint.inv_right (h : disjoint f g) : disjoint f g⁻¹ := h.symm.inv_left.symm @[simp] lemma disjoint_inv_left_iff : disjoint f⁻¹ g ↔ disjoint f g := begin refine ⟨λ h, _, disjoint.inv_left⟩, convert h.inv_left, exact (inv_inv _).symm end @[simp] lemma disjoint_inv_right_iff : disjoint f g⁻¹ ↔ disjoint f g := by rw [disjoint_comm, disjoint_inv_left_iff, disjoint_comm] lemma disjoint.mul_left (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint.mul_right (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by { rw disjoint_comm, exact H1.symm.mul_left H2.symm } lemma disjoint_prod_right (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons, exact (h _ (list.mem_cons_self _ _)).mul_right (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint.commute lemma nodup_of_pairwise_disjoint {l : list (perm α)} (h1 : (1 : perm α) ∉ l) (h2 : l.pairwise disjoint) : l.nodup := begin refine list.pairwise.imp_of_mem _ h2, rintros σ - h_mem - h_disjoint rfl, suffices : σ = 1, { rw this at h_mem, exact h1 h_mem }, exact ext (λ a, (or_self _).mp (h_disjoint a)), end lemma pow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by { rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← f.injective.eq_iff, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm], exact pow_apply_eq_of_apply_apply_eq_self hffx _ } lemma disjoint.mul_apply_eq_iff {σ τ : perm α} (hστ : disjoint σ τ) {a : α} : (σ * τ) a = a ↔ σ a = a ∧ τ a = a := begin refine ⟨λ h, _, λ h, by rw [mul_apply, h.2, h.1]⟩, cases hστ a with hσ hτ, { exact ⟨hσ, σ.injective (h.trans hσ.symm)⟩ }, { exact ⟨(congr_arg σ hτ).symm.trans h, hτ⟩ }, end lemma disjoint.mul_eq_one_iff {σ τ : perm α} (hστ : disjoint σ τ) : σ * τ = 1 ↔ σ = 1 ∧ τ = 1 := by simp_rw [ext_iff, one_apply, hστ.mul_apply_eq_iff, forall_and_distrib] lemma disjoint.gpow_disjoint_gpow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℤ) : disjoint (σ ^ m) (τ ^ n) := λ x, or.imp (λ h, gpow_apply_eq_self_of_apply_eq_self h m) (λ h, gpow_apply_eq_self_of_apply_eq_self h n) (hστ x) lemma disjoint.pow_disjoint_pow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℕ) : disjoint (σ ^ m) (τ ^ n) := hστ.gpow_disjoint_gpow m n end disjoint section is_swap variable [decidable_eq α] /-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/ def is_swap (f : perm α) : Prop := ∃ x y, x ≠ y ∧ f = swap x y lemma is_swap.of_subtype_is_swap {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : f.is_swap) : (of_subtype f).is_swap := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by { simp only [ne.def] at hxy, exact hxy.1 }, equiv.ext $ λ z, begin rw [hxy.2, of_subtype], simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk], split_ifs; rw subtype.coe_mk <|> cc, end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end end is_swap section support variables [decidable_eq α] [fintype α] {f g : perm α} /-- The `finset` of nonfixed points of a permutation. -/ def support (f : perm α) : finset α := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support {x : α} : x ∈ f.support ↔ f x ≠ x := by rw [support, mem_filter, and_iff_right (mem_univ x)] lemma not_mem_support {x : α} : x ∉ f.support ↔ f x = x := by simp @[simp] lemma support_eq_empty_iff {σ : perm α} : σ.support = ∅ ↔ σ = 1 := by simp_rw [finset.ext_iff, mem_support, finset.not_mem_empty, iff_false, not_not, equiv.perm.ext_iff, one_apply] @[simp] lemma support_one : (1 : perm α).support = ∅ := by rw support_eq_empty_iff @[simp] lemma support_refl : support (equiv.refl α) = ∅ := support_one lemma support_congr (h : f.support ⊆ g.support) (h' : ∀ x ∈ g.support, f x = g x) : f = g := begin ext x, by_cases hx : x ∈ g.support, { exact h' x hx }, { rw [not_mem_support.mp hx, ←not_mem_support], exact λ H, hx (h H) } end lemma support_mul_le (f g : perm α) : (f * g).support ≤ f.support ⊔ g.support := λ x, begin rw [sup_eq_union, mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], rintro ⟨hf, hg⟩, rw [hg, hf] end lemma exists_mem_support_of_mem_support_prod {l : list (perm α)} {x : α} (hx : x ∈ l.prod.support) : ∃ f : perm α, f ∈ l ∧ x ∈ f.support := begin contrapose! hx, simp_rw [mem_support, not_not] at hx ⊢, induction l with f l ih generalizing hx, { refl }, { rw [list.prod_cons, mul_apply, ih (λ g hg, hx g (or.inr hg)), hx f (or.inl rfl)] }, end lemma support_pow_le (σ : perm α) (n : ℕ) : (σ ^ n).support ≤ σ.support := λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (pow_apply_eq_self_of_apply_eq_self h2 n)) @[simp] lemma support_inv (σ : perm α) : support (σ⁻¹) = σ.support := by simp_rw [finset.ext_iff, mem_support, not_iff_not, (inv_eq_iff_eq).trans eq_comm, iff_self, imp_true_iff] @[simp] lemma apply_mem_support {x : α} : f x ∈ f.support ↔ x ∈ f.support := by rw [mem_support, mem_support, ne.def, ne.def, not_iff_not, apply_eq_iff_eq] @[simp] lemma pow_apply_mem_support {n : ℕ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin induction n with n ih, { refl }, rw [pow_succ, perm.mul_apply, apply_mem_support, ih] end @[simp] lemma gpow_apply_mem_support {n : ℤ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin cases n, { rw [int.of_nat_eq_coe, gpow_coe_nat, pow_apply_mem_support] }, { rw [gpow_neg_succ_of_nat, ← support_inv, ← inv_pow, pow_apply_mem_support] } end lemma pow_eq_on_of_mem_support (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) (k : ℕ) : ∀ (x ∈ f.support ∩ g.support), (f ^ k) x = (g ^ k) x := begin induction k with k hk, { simp }, { intros x hx, rw [pow_succ', mul_apply, pow_succ', mul_apply, h _ hx, hk], rwa [mem_inter, apply_mem_support, ←h _ hx, apply_mem_support, ←mem_inter] } end lemma disjoint_iff_disjoint_support : disjoint f g ↔ _root_.disjoint f.support g.support := by simp [disjoint_iff_eq_or_eq, disjoint_iff, finset.ext_iff, not_and_distrib] lemma disjoint.disjoint_support (h : disjoint f g) : _root_.disjoint f.support g.support := disjoint_iff_disjoint_support.1 h lemma disjoint.support_mul (h : disjoint f g) : (f * g).support = f.support ∪ g.support := begin refine le_antisymm (support_mul_le _ _) (λ a, _), rw [mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], exact (h a).elim (λ hf h, ⟨hf, f.apply_eq_iff_eq.mp (h.trans hf.symm)⟩) (λ hg h, ⟨(congr_arg f hg).symm.trans h, hg⟩), end lemma support_prod_of_pairwise_disjoint (l : list (perm α)) (h : l.pairwise disjoint) : l.prod.support = (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.pairwise_cons] at h, have : disjoint hd tl.prod := disjoint_prod_right _ h.left, simp [this.support_mul, hl h.right] } end lemma support_prod_le (l : list (perm α)) : l.prod.support ≤ (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.prod_cons, list.map_cons, list.foldr_cons], refine (support_mul_le hd tl.prod).trans _, exact sup_le_sup (le_refl _) hl } end lemma support_gpow_le (σ : perm α) (n : ℤ) : (σ ^ n).support ≤ σ.support := λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (gpow_apply_eq_self_of_apply_eq_self h2 n)) @[simp] lemma support_swap {x y : α} (h : x ≠ y) : support (swap x y) = {x, y} := begin ext z, by_cases hx : z = x; by_cases hy : z = y, any_goals { simpa [hx, hy] using h.symm }, { simp [swap_apply_of_ne_of_ne, hx, hy] } end lemma support_swap_iff (x y : α) : support (swap x y) = {x, y} ↔ x ≠ y := begin refine ⟨λ h H, _, support_swap⟩, subst H, simp only [swap_self, support_refl, insert_singleton_self_eq] at h, have : x ∈ ∅, { rw h, exact mem_singleton.mpr rfl }, simpa end lemma support_swap_mul_swap {x y z : α} (h : list.nodup [x, y, z]) : support (swap x y * swap y z) = {x, y, z} := begin simp only [list.not_mem_nil, and_true, list.mem_cons_iff, not_false_iff, list.nodup_cons, list.mem_singleton, and_self, list.nodup_nil] at h, push_neg at h, apply le_antisymm, { convert support_mul_le _ _, rw [support_swap h.left.left, support_swap h.right], ext, simp [or.comm, or.left_comm] }, { intro, simp only [mem_insert, mem_singleton], rintro (rfl | rfl | rfl | _); simp [swap_apply_of_ne_of_ne, h.left.left, h.left.left.symm, h.left.right, h.left.right.symm, h.right.symm] } end lemma support_swap_mul_ge_support_diff (f : perm α) (x y : α) : f.support \ {x, y} ≤ (swap x y * f).support := begin intro, simp only [and_imp, perm.coe_mul, function.comp_app, ne.def, mem_support, mem_insert, mem_sdiff, mem_singleton], push_neg, rintro ha ⟨hx, hy⟩ H, rw [swap_apply_eq_iff, swap_apply_of_ne_of_ne hx hy] at H, exact ha H end lemma support_swap_mul_eq (f : perm α) (x : α) (h : f (f x) ≠ x) : (swap x (f x) * f).support = f.support \ {x} := begin by_cases hx : f x = x, { simp [hx, sdiff_singleton_eq_erase, not_mem_support.mpr hx, erase_eq_of_not_mem] }, ext z, by_cases hzx : z = x, { simp [hzx] }, by_cases hzf : z = f x, { simp [hzf, hx, h, swap_apply_of_ne_of_ne], }, by_cases hzfx : f z = x, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx] }, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx, f.injective.ne hzx, swap_apply_of_ne_of_ne] } end lemma mem_support_swap_mul_imp_mem_support_ne {x y : α} (hy : y ∈ support (swap x (f x) * f)) : y ∈ support f ∧ y ≠ x := begin simp only [mem_support, swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end lemma disjoint.mem_imp (h : disjoint f g) {x : α} (hx : x ∈ f.support) : x ∉ g.support := λ H, h.disjoint_support (mem_inter_of_mem hx H) lemma eq_on_support_mem_disjoint {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : ∀ (x ∈ f.support), f x = l.prod x := begin induction l with hd tl IH, { simpa using h }, { intros x hx, rw list.pairwise_cons at hl, rw list.mem_cons_iff at h, rcases h with rfl|h, { rw [list.prod_cons, mul_apply, not_mem_support.mp ((disjoint_prod_right tl hl.left).mem_imp hx)] }, { rw [list.prod_cons, mul_apply, ←IH h hl.right _ hx, eq_comm, ←not_mem_support], refine (hl.left _ h).symm.mem_imp _, simpa using hx } } end lemma disjoint.mono {x y : perm α} (h : disjoint f g) (hf : x.support ≤ f.support) (hg : y.support ≤ g.support) : disjoint x y := begin rw disjoint_iff_disjoint_support at h ⊢, intros a ha, exact h (mem_inter_of_mem (hf (mem_of_mem_inter_left ha)) (hg (mem_of_mem_inter_right ha))) end lemma support_le_prod_of_mem {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : f.support ≤ l.prod.support := begin intros x hx, rwa [mem_support, ←eq_on_support_mem_disjoint h hl _ hx, ←mem_support], end section extend_domain variables {β : Type*} [decidable_eq β] [fintype β] {p : β → Prop} [decidable_pred p] @[simp] lemma support_extend_domain (f : α ≃ subtype p) {g : perm α} : support (g.extend_domain f) = g.support.map f.as_embedding := begin ext b, simp only [exists_prop, function.embedding.coe_fn_mk, to_embedding_apply, mem_map, ne.def, function.embedding.trans_apply, mem_support], by_cases pb : p b, { rw [extend_domain_apply_subtype _ _ pb], split, { rintro h, refine ⟨f.symm ⟨b, pb⟩, _, by simp⟩, contrapose! h, simp [h] }, { rintro ⟨a, ha, hb⟩, contrapose! ha, obtain rfl : a = f.symm ⟨b, pb⟩, { rw eq_symm_apply, exact subtype.coe_injective hb }, rw eq_symm_apply, exact subtype.coe_injective ha } }, { rw [extend_domain_apply_not_subtype _ _ pb], simp only [not_exists, false_iff, not_and, eq_self_iff_true, not_true], rintros a ha rfl, exact pb (subtype.prop _) } end lemma card_support_extend_domain (f : α ≃ subtype p) {g : perm α} : (g.extend_domain f).support.card = g.support.card := by simp end extend_domain section card @[simp] lemma card_support_eq_zero {f : perm α} : f.support.card = 0 ↔ f = 1 := by rw [finset.card_eq_zero, support_eq_empty_iff] lemma one_lt_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 1 < f.support.card := begin simp_rw [one_lt_card_iff, mem_support, ←not_or_distrib], contrapose! h, ext a, specialize h (f a) a, rwa [apply_eq_iff_eq, or_self, or_self] at h, end lemma card_support_ne_one (f : perm α) : f.support.card ≠ 1 := begin by_cases h : f = 1, { exact ne_of_eq_of_ne (card_support_eq_zero.mpr h) zero_ne_one }, { exact ne_of_gt (one_lt_card_support_of_ne_one h) }, end @[simp] lemma card_support_le_one {f : perm α} : f.support.card ≤ 1 ↔ f = 1 := by rw [le_iff_lt_or_eq, nat.lt_succ_iff, nat.le_zero_iff, card_support_eq_zero, or_iff_not_imp_right, imp_iff_right f.card_support_ne_one] lemma two_le_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 2 ≤ f.support.card := one_lt_card_support_of_ne_one h lemma card_support_swap_mul {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, (mem_support_swap_mul_imp_mem_support_ne hz).left, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩, from congr_arg card $ by simp [support_swap hxy, *, finset.ext_iff] @[simp] lemma card_support_eq_two {f : perm α} : f.support.card = 2 ↔ is_swap f := begin split; intro h, { obtain ⟨x, t, hmem, hins, ht⟩ := card_eq_succ.1 h, obtain ⟨y, rfl⟩ := card_eq_one.1 ht, rw mem_singleton at hmem, refine ⟨x, y, hmem, _⟩, ext a, have key : ∀ b, f b ≠ b ↔ _ := λ b, by rw [←mem_support, ←hins, mem_insert, mem_singleton], by_cases ha : f a = a, { have ha' := not_or_distrib.mp (mt (key a).mpr (not_not.mpr ha)), rw [ha, swap_apply_of_ne_of_ne ha'.1 ha'.2] }, { have ha' := (key (f a)).mp (mt f.apply_eq_iff_eq.mp ha), obtain rfl | rfl := ((key a).mp ha), { rw [or.resolve_left ha' ha, swap_apply_left] }, { rw [or.resolve_right ha' ha, swap_apply_right] } } }, { obtain ⟨x, y, hxy, rfl⟩ := h, exact card_support_swap hxy } end lemma disjoint.card_support_mul (h : disjoint f g) : (f * g).support.card = f.support.card + g.support.card := begin rw ←finset.card_disjoint_union, { congr, ext, simp [h.support_mul] }, { simpa using h.disjoint_support } end lemma card_support_prod_list_of_pairwise_disjoint {l : list (perm α)} (h : l.pairwise disjoint) : l.prod.support.card = (l.map (finset.card ∘ support)).sum := begin induction l with a t ih, { exact card_support_eq_zero.mpr rfl, }, { obtain ⟨ha, ht⟩ := list.pairwise_cons.1 h, rw [list.prod_cons, list.map_cons, list.sum_cons, ←ih ht], exact (disjoint_prod_right _ ha).card_support_mul } end end card end support end equiv.perm
4bfd6fee6912c8ca9e7e1904e5f9e4a36be3bf26
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1682.lean
fd3e7b9e63a77f3c541151ca0bee60bd5888136a
[ "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
244
lean
#check let t := to_fmt "foo" in format.to_string t options.mk #check let t := to_fmt "foo" in t.to_string #check let t := to_fmt "foo" in t.to_string options.mk variable t : format set_option pp.all true #check t.to_string options.mk
e29e2067e60fc7b0cd5d02c8854f9abce06db26f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/gmonoid.lean
0c6c7a8b25eb1253673b08e4ac957dfc9abd5769
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,146
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.direct_sum.ring import data.fin.tuple.basic /-! # Tuples `fin n → α` form a graded monoid with `*` as `fin.append` Defining multiplication as concatenation isn't particularly canonical, so we do not provide this in mathlib. We could safely provide this instance on a type alias, but for now we just put this in `tests` to verify that this definition is possible. -/ namespace fin variables {α : Type*} {α' : Type*} {na nb nc : ℕ} example {α : Type*} : graded_monoid.gmonoid (λ n, fin n → α) := { mul := λ i j, fin.append, one := fin.elim0, one_mul := λ b, sigma_eq_of_eq_comp_cast _ (elim0'_append _), mul_one := λ a, sigma_eq_of_eq_comp_cast _ (append_elim0' _), mul_assoc := λ a b c, sigma_eq_of_eq_comp_cast (add_assoc _ _ _) $ (append_assoc a.2 b.2 c.2).trans rfl, gnpow := λ n i a, repeat n a, gnpow_zero' := λ a, sigma_eq_of_eq_comp_cast _ (repeat_zero _), gnpow_succ' := λ a n, sigma_eq_of_eq_comp_cast _ (repeat_succ _ _) } end fin
014800460e781d03d58c1755a59e2f5bd139d2cf
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/deprecated/subfield.lean
1f92b33e49ce541e82642fffcf9aad01bef6a7cb
[ "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
5,511
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import deprecated.subring import algebra.group_with_zero.power variables {F : Type*} [field F] (S : set F) class is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) lemma is_subfield.div_mem {S : set F} [is_subfield S] {x y : F} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := by { rw div_eq_mul_inv, exact is_submonoid.mul_mem hx (is_subfield.inv_mem hy) } instance is_subfield.field [is_subfield S] : field S := by letI cr_inst : comm_ring S := subset.comm_ring; exact { inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩, div := λ x y, ⟨x / y, is_subfield.div_mem x.2 y.2⟩, div_eq_mul_inv := λ x y, subtype.ext $ div_eq_mul_inv (x : F) y, exists_pair_ne := ⟨0, 1, λ h, zero_ne_one (subtype.ext_iff_val.1 h)⟩, mul_inv_cancel := λ a ha, subtype.ext_iff_val.2 (mul_inv_cancel (λ h, ha $ subtype.ext_iff_val.2 h)), inv_zero := subtype.ext_iff_val.2 inv_zero, .. cr_inst } lemma is_subfield.pow_mem {a : F} {n : ℤ} {s : set F} [is_subfield s] (h : a ∈ s) : a ^ n ∈ s := begin cases n, { rw gpow_of_nat, exact is_submonoid.pow_mem h }, { rw gpow_neg_succ_of_nat, exact is_subfield.inv_mem (is_submonoid.pow_mem h) }, end instance univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial } /- note: in the next two declarations, if we let type-class inference figure out the instance `ring_hom.is_subring_preimage` then that instance only applies when particular instances of `is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones). If we specify it explicitly, then it doesn't complain. -/ instance preimage.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [f.map_inv], exact is_subfield.inv_mem ha }, ..f.is_subring_preimage s } instance image.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv _⟩, ..f.is_subring_image s } instance range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply_instance } namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩ instance closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem hp hr, q * s, is_submonoid.mul_mem hq hs, (div_mul_div _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem } instance closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs) (is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, classical, by_cases hp0 : p = 0, by simp [hp0, h0], exact ⟨q, hq, p, hp, inv_div.symm⟩ end } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_subfield.div_mem (ring.closure_subset H hp) (ring.closure_subset H hq) theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set F) [∀ i, is_subfield (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed s directed } instance is_subfield.inter (S₁ S₂ : set F) [is_subfield S₁] [is_subfield S₂] : is_subfield (S₁ ∩ S₂) := { inv_mem := λ x hx, ⟨is_subfield.inv_mem hx.1, is_subfield.inv_mem hx.2⟩ } instance is_subfield.Inter {ι : Sort*} (S : ι → set F) [h : ∀ y : ι, is_subfield (S y)] : is_subfield (set.Inter S) := { inv_mem := λ x hx, set.mem_Inter.2 $ λ y, is_subfield.inv_mem $ set.mem_Inter.1 hx y }
89599d18c35e8a8e8cf9fe8a2c53166b382f605c
b794ca1df49bc5a3bd3fd5552eed3bc4f63b8b93
/src/mywork/practice_2.lean
e88e47e77a53491f1e5e78d3476ed0730ec6a436
[]
no_license
akraisinger/cs2120f21
8235ac98375e04ffcec504cff5cab7833ee69e54
4ef83d7151bb6a284028092aa4f1d509c0eb8237
refs/heads/main
1,691,714,771,612
1,632,889,465,000
1,632,889,465,000
399,946,508
0
0
null
null
null
null
UTF-8
Lean
false
false
4,611
lean
-- Anna Kraisinger alk6tx -- due wednesday /- Prove the following simple logical conjectures. Give a formal and an English proof of each one. Your English language proofs should be complete in the sense that they identify all the axioms and/or theorems that you use. -/ example : true := true.intro example : false := _ -- trick question? why? /- No proof for false, because then false would be true, and then everything would be true. False is not true, so cannot have proof that it is. -/ -- 1 example : ∀ (P : Prop), P ∨ P ↔ P := begin assume P, apply iff.intro _ _, -- iff intro rule you must prove → both ways -- forward assume porp, apply or.elim porp, -- left disjunct assume p, exact p, -- right disjunct assume p, exact p, -- backwards assume p, exact or.intro_left P p, -- can also use or.intro_right end -- 2 example : ∀ (P : Prop), P ∧ P ↔ P := begin assume P, apply iff.intro _ _, -- forward assume pandp, exact and.elim_left pandp, -- backward assume p, exact and.intro p p, end -- 3 example : ∀ (P Q : Prop), P ∨ Q ↔ Q ∨ P := begin assume P Q, apply iff.intro _ _, -- forward assume porq, apply or.elim porq, assume P, apply or.intro_right, exact P, assume Q, apply or.intro_left, exact Q, -- backward assume qorp, apply or.elim qorp, assume Q, apply or.intro_right, exact Q, assume P, apply or.intro_left, exact P, end -- 4 example : ∀ (P Q : Prop), P ∧ Q ↔ Q ∧ P := begin assume P Q, apply iff.intro _ _, -- forward assume pandq, exact and.intro(and.elim_right pandq)(and.elim_left pandq), -- backward assume qandp, exact and.intro(and.elim_right qandp)(and.elim_left qandp), end -- 5 example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := begin assume P Q R, apply iff.intro _ _, -- forward assume e, have p := and.elim_left e, have qr := and.elim_right e, cases qr, apply or.intro_left, exact and.intro p qr, apply or.intro_right, exact and.intro p qr, -- backward assume e, apply and.intro, cases e, have p := and.elim_left e, exact p, have p := and.elim_left e, exact p, cases e, apply or.intro_left, have q := and.elim_right e, exact q, apply or.intro_right, have r := and.elim_right e, exact r, end -- 6 example : ∀ (P Q R : Prop), P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := begin assume P Q R, apply iff.intro, -- forward assume e, apply and.intro, cases e, apply or.intro_left, exact e, apply or.intro_right, exact (and.elim_left e), cases e, apply or.intro_left, exact e, apply or.intro_right, exact (and.elim_right e), -- backward assume e, have pq := and.elim_left e, cases pq, apply or.intro_left, exact pq, have pr := and.elim_right e, cases pr, apply or.intro_left, exact pr, apply or.intro_right, exact and.intro pq pr, end -- 7 example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P := begin assume P Q, apply iff.intro, -- forward assume e, have p := and.elim_left e, exact p, -- backward assume e, apply and.intro, exact e, apply or.intro_left, exact e, end -- 8 example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P := begin assume P Q, apply iff.intro, -- forward assume e, cases e, exact e, have p := and.elim_left e, exact p, -- backward assume e, apply or.intro_left, exact e, end -- 9 example : ∀ (P : Prop), P ∨ true ↔ true := begin assume P, apply iff.intro, -- forward assume e, cases e, apply true.intro, exact e, -- backward assume e, apply or.intro_right, exact e, end -- 10 example : ∀ (P : Prop), P ∨ false ↔ P := begin assume P, apply iff.intro, -- forward assume e, cases e, exact e, apply false.elim, exact e, -- backward assume e, apply or.intro_left, exact e, end -- 11 example : ∀ (P : Prop), P ∧ true ↔ P := begin assume P, apply iff.intro, -- forward assume e, apply and.elim_left e, -- backward assume e, apply and.intro, exact e, apply true.intro, end -- 12 example : ∀ (P : Prop), P ∧ false ↔ false := begin assume P, apply iff.intro, -- forward assume e, apply and.elim_right e, -- backward assume e, apply and.intro, apply false.elim, exact e, exact e, end
1efbd1568af68be9ac47156dfaaf1e6b3889d143
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/preserves/filtered.lean
149eba878f831ff93c35534ff086308493c8047f
[ "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,711
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import category_theory.limits.preserves.basic import category_theory.filtered /-! # Preservation of filtered colimits and cofiltered limits. Typically forgetful functors from algebraic categories preserve filtered colimits (although not general colimits). See e.g. `algebra/category/Mon/filtered_colimits`. ## Future work This could be generalised to allow diagrams in lower universes. -/ open category_theory open category_theory.functor namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables {E : Type u₃} [category.{v} E] variables {J : Type v} [small_category J] {K : J ⥤ C} /-- A functor is said to preserve filtered colimits, if it preserves all colimits of shape `J`, where `J` is a filtered category. -/ class preserves_filtered_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_filtered_colimits : Π (J : Type v) [small_category J] [is_filtered J], preserves_colimits_of_shape J F) attribute [instance, priority 100] preserves_filtered_colimits.preserves_filtered_colimits @[priority 100] instance preserves_colimits.preserves_filtered_colimits (F : C ⥤ D) [preserves_colimits F] : preserves_filtered_colimits F := { preserves_filtered_colimits := infer_instance } instance comp_preserves_filtered_colimits (F : C ⥤ D) (G : D ⥤ E) [preserves_filtered_colimits F] [preserves_filtered_colimits G] : preserves_filtered_colimits (F ⋙ G) := { preserves_filtered_colimits := λ J _ _, by exactI infer_instance } /-- A functor is said to preserve cofiltered limits, if it preserves all limits of shape `J`, where `J` is a cofiltered category. -/ class preserves_cofiltered_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_cofiltered_limits : Π (J : Type v) [small_category J] [is_cofiltered J], preserves_limits_of_shape J F) attribute [instance, priority 100] preserves_cofiltered_limits.preserves_cofiltered_limits @[priority 100] instance preserves_limits.preserves_cofiltered_limits (F : C ⥤ D) [preserves_limits F] : preserves_cofiltered_limits F := { preserves_cofiltered_limits := infer_instance } instance comp_preserves_cofiltered_limits (F : C ⥤ D) (G : D ⥤ E) [preserves_cofiltered_limits F] [preserves_cofiltered_limits G] : preserves_cofiltered_limits (F ⋙ G) := { preserves_cofiltered_limits := λ J _ _, by exactI infer_instance } end category_theory.limits
8b67649df49040b4e3b0d24a1f50aada6cd21c51
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/finset/noncomm_prod.lean
0be829d663094afc92586c2be99bb3a5a94b392f
[ "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
8,511
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import algebra.big_operators.basic /-! # Products (respectively, sums) over a finset or a multiset. The regular `finset.prod` and `multiset.prod` require `[comm_monoid α]`. Often, there are collections `s : finset α` where `[monoid α]` and we know, in a dependent fashion, that for all the terms `∀ (x ∈ s) (y ∈ s), commute x y`. This allows to still have a well-defined product over `s`. ## Main definitions - `finset.noncomm_prod`, requiring a proof of commutativity of held terms - `multiset.noncomm_prod`, requiring a proof of commutativity of held terms ## Implementation details While `list.prod` is defined via `list.foldl`, `noncomm_prod` is defined via `multiset.foldr` for neater proofs and definitions. By the commutativity assumption, the two must be equal. -/ variables {α β : Type*} (f : α → β → β) (op : α → α → α) namespace multiset /-- Fold of a `s : multiset α` with `f : α → β → β`, given a proof that `left_commutative f` on all elements `x ∈ s`. -/ def noncomm_foldr (s : multiset α) (comm : ∀ (x ∈ s) (y ∈ s) b, f x (f y b) = f y (f x b)) (b : β) : β := s.attach.foldr (f ∘ subtype.val) (λ ⟨x, hx⟩ ⟨y, hy⟩, comm x hx y hy) b @[simp] lemma noncomm_foldr_coe (l : list α) (comm : ∀ (x ∈ (l : multiset α)) (y ∈ (l : multiset α)) b, f x (f y b) = f y (f x b)) (b : β) : noncomm_foldr f (l : multiset α) comm b = l.foldr f b := begin simp only [noncomm_foldr, coe_foldr, coe_attach, list.attach], rw ←list.foldr_map, simp [list.map_pmap, list.pmap_eq_map] end @[simp] lemma noncomm_foldr_empty (h : ∀ (x ∈ (0 : multiset α)) (y ∈ (0 : multiset α)) b, f x (f y b) = f y (f x b)) (b : β) : noncomm_foldr f (0 : multiset α) h b = b := rfl lemma noncomm_foldr_cons (s : multiset α) (a : α) (h : ∀ (x ∈ (a ::ₘ s)) (y ∈ (a ::ₘ s)) b, f x (f y b) = f y (f x b)) (h' : ∀ (x ∈ s) (y ∈ s) b, f x (f y b) = f y (f x b)) (b : β) : noncomm_foldr f (a ::ₘ s) h b = f a (noncomm_foldr f s h' b) := begin induction s using quotient.induction_on, simp end lemma noncomm_foldr_eq_foldr (s : multiset α) (h : left_commutative f) (b : β) : noncomm_foldr f s (λ x _ y _, h x y) b = foldr f h b s := begin induction s using quotient.induction_on, simp end variables [assoc : is_associative α op] include assoc /-- Fold of a `s : multiset α` with an associative `op : α → α → α`, given a proofs that `op` is commutative on all elements `x ∈ s`. -/ def noncomm_fold (s : multiset α) (comm : ∀ (x ∈ s) (y ∈ s), op x y = op y x) (a : α) : α := noncomm_foldr op s (λ x hx y hy b, by rw [←assoc.assoc, comm _ hx _ hy, assoc.assoc]) a @[simp] lemma noncomm_fold_coe (l : list α) (comm : ∀ (x ∈ (l : multiset α)) (y ∈ (l : multiset α)), op x y = op y x) (a : α) : noncomm_fold op (l : multiset α) comm a = l.foldr op a := by simp [noncomm_fold] @[simp] lemma noncomm_fold_empty (h : ∀ (x ∈ (0 : multiset α)) (y ∈ (0 : multiset α)), op x y = op y x) (a : α) : noncomm_fold op (0 : multiset α) h a = a := rfl lemma noncomm_fold_cons (s : multiset α) (a : α) (h : ∀ (x ∈ a ::ₘ s) (y ∈ a ::ₘ s), op x y = op y x) (h' : ∀ (x ∈ s) (y ∈ s), op x y = op y x) (x : α) : noncomm_fold op (a ::ₘ s) h x = op a (noncomm_fold op s h' x) := begin induction s using quotient.induction_on, simp end lemma noncomm_fold_eq_fold (s : multiset α) [is_commutative α op] (a : α) : noncomm_fold op s (λ x _ y _, is_commutative.comm x y) a = fold op a s := begin induction s using quotient.induction_on, simp end omit assoc variables [monoid α] /-- Product of a `s : multiset α` with `[monoid α]`, given a proof that `*` commutes on all elements `x ∈ s`. -/ @[to_additive "Sum of a `s : multiset α` with `[add_monoid α]`, given a proof that `+` commutes on all elements `x ∈ s`." ] def noncomm_prod (s : multiset α) (comm : ∀ (x ∈ s) (y ∈ s), commute x y) : α := s.noncomm_fold (*) comm 1 @[simp, to_additive] lemma noncomm_prod_coe (l : list α) (comm : ∀ (x ∈ (l : multiset α)) (y ∈ (l : multiset α)), commute x y) : noncomm_prod (l : multiset α) comm = l.prod := begin rw [noncomm_prod], simp only [noncomm_fold_coe], induction l with hd tl hl, { simp }, { rw [list.prod_cons, list.foldr, hl], intros x hx y hy, exact comm x (list.mem_cons_of_mem _ hx) y (list.mem_cons_of_mem _ hy) } end @[simp, to_additive] lemma noncomm_prod_empty (h : ∀ (x ∈ (0 : multiset α)) (y ∈ (0 : multiset α)), commute x y) : noncomm_prod (0 : multiset α) h = 1 := rfl @[simp, to_additive] lemma noncomm_prod_cons (s : multiset α) (a : α) (comm : ∀ (x ∈ a ::ₘ s) (y ∈ a ::ₘ s), commute x y) : noncomm_prod (a ::ₘ s) comm = a * noncomm_prod s (λ x hx y hy, comm _ (mem_cons_of_mem hx) _ (mem_cons_of_mem hy)) := begin induction s using quotient.induction_on, simp end @[to_additive] lemma noncomm_prod_cons' (s : multiset α) (a : α) (comm : ∀ (x ∈ a ::ₘ s) (y ∈ a ::ₘ s), commute x y) : noncomm_prod (a ::ₘ s) comm = noncomm_prod s (λ x hx y hy, comm _ (mem_cons_of_mem hx) _ (mem_cons_of_mem hy)) * a := begin induction s using quotient.induction_on with s, simp only [quot_mk_to_coe, cons_coe, noncomm_prod_coe, list.prod_cons], induction s with hd tl IH, { simp }, { rw [list.prod_cons, mul_assoc, ←IH, ←mul_assoc, ←mul_assoc], { congr' 1, apply comm; simp }, { intros x hx y hy, simp only [quot_mk_to_coe, list.mem_cons_iff, mem_coe, cons_coe] at hx hy, apply comm, { cases hx; simp [hx] }, { cases hy; simp [hy] } } } end @[to_additive] lemma noncomm_prod_eq_prod {α : Type*} [comm_monoid α] (s : multiset α) : noncomm_prod s (λ _ _ _ _, commute.all _ _) = prod s := begin induction s using quotient.induction_on, simp end end multiset namespace finset variables [monoid β] /-- Product of a `s : finset α` mapped with `f : α → β` with `[monoid β]`, given a proof that `*` commutes on all elements `f x` for `x ∈ s`. -/ @[to_additive "Sum of a `s : finset α` mapped with `f : α → β` with `[add_monoid β]`, given a proof that `+` commutes on all elements `f x` for `x ∈ s`."] def noncomm_prod (s : finset α) (f : α → β) (comm : ∀ (x ∈ s) (y ∈ s), commute (f x) (f y)) : β := (s.1.map f).noncomm_prod (by simpa [multiset.mem_map, ←finset.mem_def] using comm) @[simp, to_additive] lemma noncomm_prod_to_finset [decidable_eq α] (l : list α) (f : α → β) (comm : ∀ (x ∈ l.to_finset) (y ∈ l.to_finset), commute (f x) (f y)) (hl : l.nodup) : noncomm_prod l.to_finset f comm = (l.map f).prod := begin rw ←list.erase_dup_eq_self at hl, simp [noncomm_prod, hl] end @[simp, to_additive] lemma noncomm_prod_empty (f : α → β) (h : ∀ (x ∈ (∅ : finset α)) (y ∈ (∅ : finset α)), commute (f x) (f y)) : noncomm_prod (∅ : finset α) f h = 1 := rfl @[simp, to_additive] lemma noncomm_prod_insert_of_not_mem [decidable_eq α] (s : finset α) (a : α) (f : α → β) (comm : ∀ (x ∈ insert a s) (y ∈ insert a s), commute (f x) (f y)) (ha : a ∉ s) : noncomm_prod (insert a s) f comm = f a * noncomm_prod s f (λ x hx y hy, comm _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy)) := by simp [insert_val_of_not_mem ha, noncomm_prod] @[to_additive] lemma noncomm_prod_insert_of_not_mem' [decidable_eq α] (s : finset α) (a : α) (f : α → β) (comm : ∀ (x ∈ insert a s) (y ∈ insert a s), commute (f x) (f y)) (ha : a ∉ s) : noncomm_prod (insert a s) f comm = noncomm_prod s f (λ x hx y hy, comm _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy)) * f a := by simp [noncomm_prod, insert_val_of_not_mem ha, multiset.noncomm_prod_cons'] @[simp, to_additive] lemma noncomm_prod_singleton (a : α) (f : α → β) : noncomm_prod ({a} : finset α) f (λ x hx y hy, by by rw [mem_singleton.mp hx, mem_singleton.mp hy]) = f a := by simp [noncomm_prod] @[to_additive] lemma noncomm_prod_eq_prod {β : Type*} [comm_monoid β] (s : finset α) (f : α → β) : noncomm_prod s f (λ _ _ _ _, commute.all _ _) = s.prod f := begin classical, induction s using finset.induction_on with a s ha IH, { simp }, { simp [ha, IH] } end end finset
55a3b6c139d9af89dba28a5f65e8ad765438fb9a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/t7.lean
8ed803eeda04c9b4725a3ebdd32f0de8fc093823
[ "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
71
lean
constant A : Type.{1} constant f : A → A → A print raw f _ (f _ _)
35f4c3bb3c170843ec9efc26c86280a0ef82d3b9
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/tactic/interactive.lean
7266bbcce6d72a7be47fb8fb7b4e67909e22fbe2
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
27,791
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import tactic.sanity_check open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- Similar to `constructor`, but does not reorder goals. -/ meta def fconstructor : tactic unit := concat_tags tactic.fconstructor /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end /-- `rotate n` cyclically shifts the goals `n` times. `rotate` defaults to `rotate 1`. -/ meta def rotate (n := 1) : tactic unit := tactic.rotate n /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h meta def apply_iff_congr_core : tactic unit := applyc ``iff_of_eq meta def congr_core' : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core <|> apply_iff_congr_core <|> fail "congr tactic failed" /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core' >> all_goals (reflexivity <|> `[apply proof_irrel_heq] <|> `[apply proof_irrel] <|> try (congr' (nat.pred <$> o))))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- Make every propositions in the context decidable -/ meta def classical := tactic.classical private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux @[sanity_skip] lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end /-- Similar to `refine` but generates equality proof obligations for every discrepancy between the goal and the type of the rule. `convert e using n` (with `n : ℕ`) bounds the depth of the search for discrepancies, analogous to `congr' n`. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], try (congr' n), gs' ← get_goals, set_goals $ gs' ++ gs meta def compact_decl_aux : list name → binder_info → expr → list expr → tactic (list (list name × binder_info × expr)) | ns bi t [] := pure [(ns.reverse, bi, t)] | ns bi t (v'@(local_const n pp bi' t') :: xs) := do t' ← infer_type v', if bi = bi' ∧ t = t' then compact_decl_aux (pp :: ns) bi t xs else do vs ← compact_decl_aux [pp] bi' t' xs, pure $ (ns.reverse, bi, t) :: vs | ns bi t (_ :: xs) := compact_decl_aux ns bi t xs meta def compact_decl : list expr → tactic (list (list name × binder_info × expr)) | [] := pure [] | (v@(local_const n pp bi t) :: xs) := do t ← infer_type v, compact_decl_aux [pp] bi t xs | (_ :: xs) := compact_decl xs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ``` refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (t = e) /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ meta def guard_target_strict (p : parse texpr) : tactic unit := do t ← target, guard_expr_strict t p /-- `guard_hyp_strict h := t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) /-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with error message `msg` (for test writing purposes). -/ meta def success_if_fail_with_msg (tac : tactic.interactive.itactic) := tactic.success_if_fail_with_msg tac meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ``` refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ``` refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. example, with or without user attribute: ``` @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules -- any of the following lines would also work: -- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 -- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] -- by apply_rules [mono_rules] ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit := tactic.apply_rules hs n meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`. `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`. `h_generalize! Hx : e == x` reverts `Hx`. when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) /-- `choose a b h using hyp` takes an hypothesis `hyp` of the form `∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating `∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions. Example: ```lean example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n, trivial end ``` -/ meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do tgt ← match tgt with | none := get_local `this | some e := tactic.i_to_expr_strict e end, tactic.choose tgt (first :: names), try (interactive.simp none tt [simp_arg_type.expr ``(exists_prop)] [] (loc.ns $ some <$> names)), try (tactic.clear tgt) meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := tactic.use l >> try triv /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) meta def convert_to_core (r : pexpr) : tactic unit := do tgt ← target, h ← to_expr ``(_ : %%tgt = %%r), rewrite_target h, swap /-- `convert_to g using n` attempts to change the current goal to `g`, using `congr' n` to resolve discrepancies. `convert_to g` defaults to using `congr' 1`. -/ meta def convert_to (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := match n with | none := convert_to_core r >> `[congr' 1] | (some 0) := convert_to_core r | (some o) := convert_to_core r >> congr' o end /-- `ac_change g using n` is `convert_to g using n; try {ac_refl}` -/ meta def ac_change (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := convert_to r n; try ac_refl private meta def opt_dir_with : parser (option (bool × name)) := (do tk "with", arrow ← (tk "<-")?, h ← ident, return (arrow.is_some, h)) <|> return none /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do let vt := match tp with | some t := t | none := pexpr.mk_placeholder end, let pv := ``(%%pv : %%vt), v ← to_expr pv, tp ← infer_type v, definev a tp v, when h_simp.is_none $ change' pv (some (expr.const a [])) loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, pf ← to_expr (cond flip ``(%%pv = %%nv) ``(%%nv = %%pv)) >>= assert id, reflexivity | none := skip end /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ meta def clear_except (xs : parse ident *) : tactic unit := do let ns := name_set.of_list xs, local_context >>= mmap' (λ h : expr, when (¬ ns.contains h.local_pp_name) $ try $ tactic.clear h) ∘ list.reverse meta def format_names (ns : list name) : format := format.join $ list.intersperse " " (ns.map to_fmt) private meta def format_binders : list name × binder_info × expr → tactic format | (ns, binder_info.default, t) := pformat!"({format_names ns} : {t})" | (ns, binder_info.implicit, t) := pformat!"{{{format_names ns} : {t}}" | (ns, binder_info.strict_implicit, t) := pformat!"⦃{format_names ns} : {t}⦄" | ([n], binder_info.inst_implicit, t) := if "_".is_prefix_of n.to_string then pformat!"[{t}]" else pformat!"[{format_names [n]} : {t}]" | (ns, binder_info.inst_implicit, t) := pformat!"[{format_names ns} : {t}]" | (ns, binder_info.aux_decl, t) := pformat!"({format_names ns} : {t})" meta def mk_paragraph_aux (right_margin : ℕ) : format → format → ℕ → list format → format | par ln len [] := par ++ format.line ++ ln | par ln len (x :: xs) := let len' := x.to_string.length in if len + len' ≤ right_margin then mk_paragraph_aux par (ln ++ x ++ " ") (len + len' + 1) xs else mk_paragraph_aux (par ++ format.line ++ ln) (" " ++ x ++ " ") len' xs /-- `mk_paragraph right_margin ls` packs `ls` into a paragraph where the lines have length at most `right_margin` -/ meta def mk_paragraph (right_margin : ℕ) : list format → format := mk_paragraph_aux right_margin "" "" 0 /-- Format the current goal as a stand-alone example. Useful for testing tactic. * `extract_goal`: formats the statement as an `example` declaration * `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration called `my_decl` * `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration Examples: ```lean example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := begin extract_goal, -- prints: -- example {i j k : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- end extract_goal my_lemma -- lemma my_lemma {i j k : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- end end example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := begin extract_goal my_lemma, -- prints: -- lemma my_lemma {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) -- (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := -- begin -- end extract_goal my_lemma with i j k -- prints: -- lemma my_lemma {i j k : ℕ} : i ≤ k := -- begin -- end end ``` -/ meta def extract_goal (n : parse ident?) (vs : parse with_ident_list) : tactic unit := do (cxt,_) ← solve_aux `(true) $ when (¬ vs.empty) (clear_except vs) >> local_context, tgt ← target, is_prop ← is_prop tgt, let title := match n, is_prop with | none, _ := to_fmt "example" | (some n), tt := format!"lemma {n}" | (some n), ff := format!"def {n}" end, cxt ← compact_decl cxt, cxt' ← cxt.init.mmap format_binders, cxt'' ← cxt.last'.traverse $ λ x, pformat!"{format_binders x} :", stmt ← pformat!"{tgt} :=", let fmt := mk_paragraph 80 $ title :: cxt' ++ [cxt''.get_or_else ":", stmt], trace fmt, trace!"begin\n \nend" end interactive end tactic
89ec3df50db40f9064028ecb157149f1d182786b
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/recInfo1.lean
97416fe367eb0eb7a054622d6d2755620aa1630b
[ "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
636
lean
import Lean.Meta open Lean open Lean.Meta def print (msg : MessageData) : MetaM Unit := trace! `Meta.debug msg def showRecInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM Unit := do let info ← mkRecursorInfo declName majorPos? print (toString info) theorem Iff.elim {a b c} (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c := h₁ h₂.1 h₂.2 set_option trace.Meta true set_option trace.Meta.isDefEq false #eval showRecInfo `Acc.recOn #eval showRecInfo `Prod.casesOn #eval showRecInfo `List.recOn #eval showRecInfo `List.casesOn #eval showRecInfo `List.brecOn #eval showRecInfo `Iff.elim (some 4)
c3676c4a5e0435eecbf49c39fde8c4de00d5ec12
b412a6d3e313459a241fcd7941e1ec91263762eb
/homotopy/pushout.hlean
eeacdf0f7125a3027d12903ef910587261b25707
[ "Apache-2.0" ]
permissive
avigad/Spectral
fb5b87f7d25746b2203fbe6fdc0c80f7035158c9
6e2d8807f467e9662bace347bdfcaed593cba147
refs/heads/master
1,607,307,431,821
1,503,349,559,000
1,503,349,559,000
47,590,774
0
0
null
null
null
null
UTF-8
Lean
false
false
32,850
hlean
import ..algebra.exactness homotopy.cofiber homotopy.wedge open eq function is_trunc sigma prod lift is_equiv equiv pointed sum unit bool cofiber namespace pushout section variables {TL BL TR : Type*} {f : TL →* BL} {g : TL →* TR} {TL' BL' TR' : Type*} {f' : TL' →* BL'} {g' : TL' →* TR'} (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) definition ppushout_functor [constructor] (tl : TL → TL') (bl : BL →* BL') (tr : TR → TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g →* ppushout f' g' := begin fconstructor, { exact pushout.functor tl bl tr fh gh }, { exact ap inl (respect_pt bl) }, end definition ppushout_pequiv (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g ≃* ppushout f' g' := pequiv_of_equiv (pushout.equiv _ _ _ _ tl bl tr fh gh) (ap inl (respect_pt bl)) end /- WIP: proving that satisfying the universal property of the pushout is equivalent to being equivalent to the pushout -/ universe variables u₁ u₂ u₃ u₄ variables {A : Type.{u₁}} {B : Type.{u₂}} {C : Type.{u₃}} {D D' : Type.{u₄}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) -- (f : A → B) (g : A → C) (h : B → D) (k : C → D) include p definition is_pushout : Type := Π⦃X : Type.{max u₁ u₂ u₃ u₄}⦄ (h' : B → X) (k' : C → X) (p' : h' ∘ f ~ k' ∘ g), is_contr (Σ(l : D → X) (v : l ∘ h ~ h' × l ∘ k ~ k'), Πa, square (prod.pr1 v (f a)) (prod.pr2 v (g a)) (ap l (p a)) (p' a)) definition cocone [reducible] (X : Type) : Type := Σ(v : (B → X) × (C → X)), prod.pr1 v ∘ f ~ prod.pr2 v ∘ g definition cocone_of_map [constructor] (X : Type) (l : D → X) : cocone p X := ⟨(l ∘ h, l ∘ k), λa, ap l (p a)⟩ -- definition cocone_of_map (X : Type) (l : D → X) : Σ(h' : B → X) (k' : C → X), -- h' ∘ f ~ k' ∘ g := -- ⟨l ∘ h, l ∘ k, λa, ap l (p a)⟩ omit p definition is_pushout2 [reducible] : Type := Π(X : Type.{max u₁ u₂ u₃ u₄}), is_equiv (cocone_of_map p X) section open sigma.ops protected definition inv_left (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ h ~ prod.pr1 v.1 := ap10 (ap prod.pr1 (right_inv (cocone_of_map p X) v)..1) protected definition inv_right (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ k ~ prod.pr2 v.1 := ap10 (ap prod.pr2 (right_inv (cocone_of_map p X) v)..1) end section local attribute is_pushout [reducible] definition is_prop_is_pushout : is_prop (is_pushout p) := _ local attribute is_pushout2 [reducible] definition is_prop_is_pushout2 : is_prop (is_pushout2 p) := _ end definition ap_eq_apd10_ap {A B : Type} {C : B → Type} (f : A → Πb, C b) {a a' : A} (p : a = a') (b : B) : ap (λa, f a b) p = apd10 (ap f p) b := by induction p; reflexivity variables (f g) definition is_pushout2_pushout : @is_pushout2 _ _ _ _ f g inl inr glue := λX, to_is_equiv (pushout_arrow_equiv f g X ⬝e assoc_equiv_prod _) definition is_equiv_of_is_pushout2_simple [constructor] {A B C D : Type.{u₁}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) (H : is_pushout2 p) : D ≃ pushout f g := begin fapply equiv.MK, { exact (cocone_of_map p _)⁻¹ᶠ ⟨(inl, inr), glue⟩ }, { exact pushout.elim h k p }, { intro x, exact sorry }, { apply ap10, apply eq_of_fn_eq_fn (equiv.mk _ (H D)), fapply sigma_eq, { esimp, fapply prod_eq, apply eq_of_homotopy, intro b, exact ap (pushout.elim h k p) (pushout.inv_left p H ⟨(inl, inr), glue⟩ b), apply eq_of_homotopy, intro c, exact ap (pushout.elim h k p) (pushout.inv_right p H ⟨(inl, inr), glue⟩ c) }, { apply pi.pi_pathover_constant, intro a, apply eq_pathover, refine !ap_eq_apd10_ap ⬝ph _ ⬝hp !ap_eq_apd10_ap⁻¹, refine ap (λx, apd10 x _) (ap_compose (λx, x ∘ f) pr1 _ ⬝ ap02 _ !prod_eq_pr1) ⬝ph _ ⬝hp ap (λx, apd10 x _) (ap_compose (λx, x ∘ g) pr2 _ ⬝ ap02 _ !prod_eq_pr2)⁻¹, refine apd10 !apd10_ap_precompose_dependent a ⬝ph _ ⬝hp apd10 !apd10_ap_precompose_dependent⁻¹ a, refine apd10 !apd10_eq_of_homotopy (f a) ⬝ph _ ⬝hp apd10 !apd10_eq_of_homotopy⁻¹ (g a), refine ap_compose (pushout.elim h k p) _ _ ⬝pv _, refine aps (pushout.elim h k p) _ ⬝vp (!elim_glue ⬝ !ap_id⁻¹), esimp, exact sorry }, } end -- definition is_equiv_of_is_pushout2 [constructor] (H : is_pushout2 p) : D ≃ pushout f g := -- begin -- fapply equiv.MK, -- { exact down.{_ u₄} ∘ (cocone_of_map p _)⁻¹ᶠ ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ }, -- { exact pushout.elim h k p }, -- { intro x, exact sorry -- }, -- { intro d, apply eq_of_fn_eq_fn (equiv_lift D), esimp, revert d, -- apply ap10, -- apply eq_of_fn_eq_fn (equiv.mk _ (H (lift.{_ (max u₁ u₂ u₃)} D))), -- fapply sigma_eq, -- { esimp, fapply prod_eq, -- apply eq_of_homotopy, intro b, apply ap up, esimp, -- exact ap (pushout.elim h k p ∘ down.{_ u₄}) -- (pushout.inv_left p H ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ b), -- exact sorry }, -- { exact sorry }, -- -- note q := @eq_of_is_contr _ H'' -- -- ⟨up ∘ pushout.elim h k p ∘ down ∘ (center' H').1, -- -- (λb, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr1 (center' H').2 b), -- -- λc, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr2 (center' H').2 c))⟩ -- -- ⟨up, (λx, idp, λx, idp)⟩, -- -- exact ap down (ap10 q..1 d) -- } -- end /- composing pushouts -/ definition pushout_vcompose_to [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout h (@inl _ _ _ f g)) : pushout (h ∘ f) g := begin induction x with d y b, { exact inl d }, { induction y with b c a, { exact inl (h b) }, { exact inr c }, { exact glue a }}, { reflexivity } end definition pushout_vcompose_from [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout (h ∘ f) g) : pushout h (@inl _ _ _ f g) := begin induction x with d c a, { exact inl d }, { exact inr (inr c) }, { exact glue (f a) ⬝ ap inr (glue a) } end definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := begin fapply equiv.MK, { exact pushout_vcompose_to }, { exact pushout_vcompose_from }, { intro x, induction x with d c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_vcompose_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ !ap_compose'⁻¹ ⬝ !idp_con ⬝ _, esimp, apply elim_glue }}, { intro x, induction x with d y b, { reflexivity }, { induction y with b c a, { exact glue b }, { reflexivity }, { apply eq_pathover, refine ap_compose pushout_vcompose_from _ _ ⬝ph _, esimp, refine ap02 _ !elim_glue ⬝ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }}, { apply eq_pathover_id_right, esimp, refine ap_compose pushout_vcompose_from _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }} end definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := calc pushout (@inr _ _ _ f g) h ≃ pushout h (@inr _ _ _ f g) : pushout.symm ... ≃ pushout h (@inl _ _ _ g f) : pushout.equiv _ _ _ _ erfl erfl (pushout.symm f g) (λa, idp) (λa, idp) ... ≃ pushout (h ∘ g) f : pushout_vcompose ... ≃ pushout f (h ∘ g) : pushout.symm definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : pushout h k ≃ pushout hf g := begin refine _ ⬝e pushout_vcompose f g h ⬝e _, { fapply pushout.equiv, reflexivity, reflexivity, exact e, reflexivity, exact homotopy_of_homotopy_inv_post e _ _ p }, { fapply pushout.equiv, reflexivity, reflexivity, reflexivity, exact q, reflexivity }, end definition pushout_hcompose_equiv {A B C D E : Type} {f : A → B} (g : A → C) {h : C → E} {hg : A → E} {k : C → D} (e : D ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inr) (q : h ∘ g ~ hg) : pushout k h ≃ pushout f hg := calc pushout k h ≃ pushout h k : pushout.symm ... ≃ pushout hg f : by exact pushout_vcompose_equiv _ (e ⬝e pushout.symm f g) p q ... ≃ pushout f hg : pushout.symm definition pushout_of_equiv_left_to [unfold 6] {A B C : Type} {f : A ≃ B} {g : A → C} (x : pushout f g) : C := begin induction x with b c a, { exact g (f⁻¹ b) }, { exact c }, { exact ap g (left_inv f a) } end definition pushout_of_equiv_left [constructor] {A B C : Type} (f : A ≃ B) (g : A → C) : pushout f g ≃ C := begin fapply equiv.MK, { exact pushout_of_equiv_left_to }, { exact inr }, { intro c, reflexivity }, { intro x, induction x with b c a, { exact (glue (f⁻¹ b))⁻¹ ⬝ ap inl (right_inv f b) }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose inr _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply move_top_of_left, apply move_left_of_bot, refine ap02 _ (adj f _) ⬝ !ap_compose⁻¹ ⬝pv _ ⬝vp !ap_compose, apply natural_square_tr }} end definition pushout_of_equiv_right [constructor] {A B C : Type} (f : A → B) (g : A ≃ C) : pushout f g ≃ B := calc pushout f g ≃ pushout g f : pushout.symm f g ... ≃ B : pushout_of_equiv_left g f -- todo: define pushout.equiv (renamed to pushout_equiv_pushout) using this variables {A₁ B₁ C₁ A₂ B₂ C₂ A₃ B₃ C₃ : Type} {f₁ : A₁ → B₁} {g₁ : A₁ → C₁} {f₂ : A₂ → B₂} {g₂ : A₂ → C₂} {f₃ : A₃ → B₃} {g₃ : A₃ → C₃} {h₂ : A₂ → A₃} {h₁ : A₁ → A₂} {i₂ : B₂ → B₃} {i₁ : B₁ → B₂} {j₂ : C₂ → C₃} {j₁ : C₁ → C₂} (p₂ : i₂ ∘ f₂ ~ f₃ ∘ h₂) (q₂ : j₂ ∘ g₂ ~ g₃ ∘ h₂) (p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁) (q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁) definition pushout_functor_compose : pushout.functor (h₂ ∘ h₁) (i₂ ∘ i₁) (j₂ ∘ j₁) (p₁ ⬝htyv p₂) (q₁ ⬝htyv q₂) ~ pushout.functor h₂ i₂ j₂ p₂ q₂ ∘ pushout.functor h₁ i₁ j₁ p₁ q₁ := begin exact sorry end variables {p₁ q₁} definition pushout_functor_homotopy_constant {p₁' : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁' : j₁ ∘ g₁ ~ g₂ ∘ h₁} (p : p₁ ~ p₁') (q : q₁ ~ q₁') : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₁ i₁ j₁ p₁' q₁' := begin induction p, induction q, reflexivity end definition pushout_functor_homotopy {h₁ h₂ : A₁ → A₂} {i₁ i₂ : B₁ → B₂} {j₁ j₂ : C₁ → C₂} {p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁} {p₂ : i₂ ∘ f₁ ~ f₂ ∘ h₂} {q₂ : j₂ ∘ g₁ ~ g₂ ∘ h₂} (r : h₁ ~ h₂) (s : i₁ ~ i₂) (t : j₁ ~ j₂) (u : r ⬝htyh p₁ ~ p₂ ⬝htyh s) (v : r ⬝htyh q₁ ~ q₂ ⬝htyh t) : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₂ i₂ j₂ p₂ q₂ := begin induction r, induction s, induction t, apply pushout_functor_homotopy_constant, { exact (rfl_hhconcat p₁)⁻¹ʰᵗʸ ⬝hty u ⬝hty hhconcat_rfl p₂ }, exact (rfl_hhconcat q₁)⁻¹ʰᵗʸ ⬝hty v ⬝hty hhconcat_rfl q₂ end /- pushout where one map is constant is a cofiber -/ definition pushout_const_equiv_to [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : pushout f (const A c₀)) : cofiber (sum_functor f (const unit c₀)) := begin induction x with b c a, { exact !cod (sum.inl b) }, { exact !cod (sum.inr c) }, { exact glue (sum.inl a) ⬝ (glue (sum.inr ⋆))⁻¹ } end definition pushout_const_equiv_from [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : cofiber (sum_functor f (const unit c₀))) : pushout f (const A c₀) := begin induction x with v v, { induction v with b c, exact inl b, exact inr c }, { exact inr c₀ }, { induction v with a u, exact glue a, reflexivity } end definition pushout_const_equiv [constructor] {A B C : Type} (f : A → B) (c₀ : C) : pushout f (const A c₀) ≃ cofiber (sum_functor f (const unit c₀)) := begin fapply equiv.MK, { exact pushout_const_equiv_to }, { exact pushout_const_equiv_from }, { intro x, induction x with v v, { induction v with b c, reflexivity, reflexivity }, { exact glue (sum.inr ⋆) }, { apply eq_pathover_id_right, refine ap_compose pushout_const_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction v with a u, { refine !elim_glue ⬝ph _, apply whisker_bl, exact hrfl }, { induction u, exact square_of_eq idp }}}, { intro x, induction x with c b a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_const_equiv_from _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) }} end /- wedge is the cofiber of the map 2 -> A + B -/ -- move to sum definition sum_of_bool [unfold 3] (A B : Type*) (b : bool) : A + B := by induction b; exact sum.inl pt; exact sum.inr pt definition psum_of_pbool [constructor] (A B : Type*) : pbool →* (A +* B) := pmap.mk (sum_of_bool A B) idp -- move to wedge definition wedge_equiv_pushout_sum [constructor] (A B : Type*) : wedge A B ≃ cofiber (sum_of_bool A B) := begin refine pushout_const_equiv _ _ ⬝e _, fapply pushout.equiv, exact bool_equiv_unit_sum_unit⁻¹ᵉ, reflexivity, reflexivity, intro x, induction x: reflexivity, intro x, induction x with u u: induction u; reflexivity end section open prod.ops /- products preserve pushouts -/ definition pushout_prod_equiv_to [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (xd : pushout f g × D) : pushout (prod_functor f (@id D)) (prod_functor g id) := begin induction xd with x d, induction x with b c a, { exact inl (b, d) }, { exact inr (c, d) }, { exact glue (a, d) } end definition pushout_prod_equiv_from [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (x : pushout (prod_functor f (@id D)) (prod_functor g id)) : pushout f g × D := begin induction x with bd cd ad, { exact (inl bd.1, bd.2) }, { exact (inr cd.1, cd.2) }, { exact prod_eq (glue ad.1) idp } end definition pushout_prod_equiv {A B C D : Type} (f : A → B) (g : A → C) : pushout f g × D ≃ pushout (prod_functor f (@id D)) (prod_functor g id) := begin fapply equiv.MK, { exact pushout_prod_equiv_to }, { exact pushout_prod_equiv_from }, { intro x, induction x with bd cd ad, { induction bd, reflexivity }, { induction cd, reflexivity }, { induction ad with a d, apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_prod_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, esimp, exact !ap_prod_elim ⬝ !idp_con ⬝ !elim_glue }}, { intro xd, induction xd with x d, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose (pushout_prod_equiv_from ∘ pushout_prod_equiv_to) _ _ ⬝ _, refine ap02 _ !ap_prod_mk_left ⬝ !ap_compose ⬝ _, refine ap02 _ (!ap_prod_elim ⬝ !idp_con ⬝ !elim_glue) ⬝ _, refine !elim_glue ⬝ !ap_prod_mk_left⁻¹ }} end end /- interaction of pushout and sums -/ definition pushout_to_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout f g) : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin induction x with b c a, { exact inl (sum.inl b) }, { exact inr c }, { exact glue (sum.inl a) } end definition pushout_from_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀))) : pushout f g := begin induction x with x c x, { induction x with b d, exact inl b, exact inr c₀ }, { exact inr c }, { induction x with a d, exact glue a, reflexivity } end /- The pushout of B <-- A --> C is the same as the pushout of B + D <-- A + D --> C -/ definition pushout_sum_cancel_equiv [constructor] {A B C : Type} (f : A → B) (g : A → C) (D : Type) (c₀ : C) : pushout f g ≃ pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin fapply equiv.MK, { exact pushout_to_sum D c₀ }, { exact pushout_from_sum D c₀ }, { intro x, induction x with x c x, { induction x with b d, reflexivity, esimp, exact (glue (sum.inr d))⁻¹ }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose (pushout_to_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with a d: esimp, { exact hdeg_square !elim_glue }, { exact square_of_eq !con.left_inv }}}, { intro x, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose (pushout_from_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ !elim_glue }} end end pushout namespace pushout variables {A A' B B' C C' : Type} {f : A → B} {g : A → C} {f' : A' → B'} {g' : A' → C'} definition sum_pushout_of_pushout_sum [unfold 11] (x : pushout (sum_functor f f') (sum_functor g g')) : pushout f g ⊎ pushout f' g' := begin induction x with b c a, { exact sum_functor inl inl b }, { exact sum_functor inr inr c }, { induction a with a a', exact ap sum.inl (glue a), exact ap sum.inr (glue a') } end definition pushout_sum_of_sum_pushout [unfold 11] (x : pushout f g ⊎ pushout f' g') : pushout (sum_functor f f') (sum_functor g g') := begin induction x with x x, { exact pushout.functor sum.inl sum.inl sum.inl homotopy.rfl homotopy.rfl x }, { exact pushout.functor sum.inr sum.inr sum.inr homotopy.rfl homotopy.rfl x } end variables (f g f' g') /- do we want to define this in terms of sigma_pushout? One possible disadvantage is that the computation on glue is less convenient -/ definition pushout_sum_equiv_sum_pushout [constructor] : pushout (sum_functor f f') (sum_functor g g') ≃ pushout f g ⊎ pushout f' g' := equiv.MK sum_pushout_of_pushout_sum pushout_sum_of_sum_pushout abstract begin intro x, induction x with x x, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, end end abstract begin intro x, induction x with b c a, { induction b: reflexivity }, { induction c: reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sum_of_sum_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': (apply hdeg_square; refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con) } end end variables {f g f' g'} variables {D E F D' E' F' : Type} {h : D → E} {i : D → F} {h' : D' → E'} {i' : D' → F'} {j : A → D} {k : B → E} {l : C → F} {j' : A' → D'} {k' : B' → E'} {l' : C' → F'} {j₂ : A' → D} {k₂ : B' → E} {l₂ : C' → F} (s : hsquare f h j k) (t : hsquare g i j l) (s' : hsquare f' h' j' k') (t' : hsquare g' i' j' l') (s₂ : hsquare f' h j₂ k₂) (t₂ : hsquare g' i j₂ l₂) definition sum_rec_pushout_sum_equiv_sum_pushout : sum.rec (pushout.functor j k l s t) (pushout.functor j₂ k₂ l₂ s₂ t₂) ∘ pushout_sum_equiv_sum_pushout f g f' g' ~ pushout.functor (sum.rec j j₂) (sum.rec k k₂) (sum.rec l l₂) (sum_rec_hsquare s s₂) (sum_rec_hsquare t t₂) := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': exact hdeg_square (!ap_compose'⁻¹ ⬝ !elim_glue ⬝ !elim_glue⁻¹) end end } end definition pushout_sum_equiv_sum_pushout_natural : hsquare (pushout.functor (j +→ j') (k +→ k') (l +→ l') (sum_functor_hsquare s s') (sum_functor_hsquare t t')) (pushout.functor j k l s t +→ pushout.functor j' k' l' s' t') (pushout_sum_equiv_sum_pushout f g f' g') (pushout_sum_equiv_sum_pushout h i h' i') := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _ ⬝hp (!ap_compose ⬝ ap02 _ !elim_glue)⁻¹, refine !ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ !elim_glue) ◾ (!ap_compose'⁻¹ ⬝ !ap_inv) ⬝ph _, induction a with a a', { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inl _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inl _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inl _ _) ⬝ !ap_con⁻¹ }, { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inr _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inr _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inr _ _) ⬝ !ap_con⁻¹ } end end } end end pushout namespace pushout open sigma sigma.ops variables {X : Type} {A B C : X → Type} {f : Πx, A x → B x} {g : Πx, A x → C x} definition sigma_pushout_of_pushout_sigma [unfold 7] (x : pushout (total f) (total g)) : Σx, pushout (f x) (g x) := begin induction x with b c a, { exact total (λx, inl) b }, { exact total (λx, inr) c }, { exact sigma_eq_right (glue a.2) } end definition pushout_sigma_of_sigma_pushout [unfold 7] (x : Σx, pushout (f x) (g x)) : pushout (total f) (total g) := pushout.functor (dpair x.1) (dpair x.1) (dpair x.1) homotopy.rfl homotopy.rfl x.2 variables (f g) definition pushout_sigma_equiv_sigma_pushout [constructor] : pushout (total f) (total g) ≃ Σx, pushout (f x) (g x) := equiv.MK sigma_pushout_of_pushout_sigma pushout_sigma_of_sigma_pushout abstract begin intro x, induction x with x y, induction y with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sigma_pushout_of_pushout_sigma _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue } end end abstract begin intro x, induction x with b c a, { induction b, reflexivity }, { induction c, reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sigma_of_sigma_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a', apply hdeg_square, refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con } end end -- apply eq_pathover_id_right, refine ap_compose sigma_pushout_of_pushout_sigma _ _ ⬝ ap02 _ !elim_glue ⬝ph _ -- apply eq_pathover_id_right, refine ap_compose pushout_sigma_of_sigma_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _ /- an induction principle for the cofiber of f : A → B if A is a pushout where the second map has a section. The Pgluer is modified to get the right coherence See https://github.com/HoTT/HoTT-Agda/blob/master/theorems/homotopy/elims/CofPushoutSection.agda -/ open sigma.ops definition cofiber_pushout_helper' {A : Type} {B : A → Type} {a₀₀ a₀₂ a₂₀ a₂₂ : A} {p₀₁ : a₀₀ = a₀₂} {p₁₀ : a₀₀ = a₂₀} {p₂₁ : a₂₀ = a₂₂} {p₁₂ : a₀₂ = a₂₂} {s : square p₀₁ p₂₁ p₁₀ p₁₂} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ b₂₂' : B a₂₂} {q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂'} {q₁₂ : b₀₂ =[p₁₂] b₂₂} : Σ(r : b₂₂' = b₂₂), squareover B s q₀₁ (r ▸ q₂₁) q₁₀ q₁₂ := begin induction s, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on, induction q₁₀ using idp_rec_on, induction q₁₂ using idp_rec_on, exact ⟨idp, idso⟩ end definition cofiber_pushout_helper {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} {Pcod : Πd, P (cofiber.cod h d)} {Pbase : P (cofiber.base h)} (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (a : A) : Σ(p : Pbase = Pbase), squareover P (natural_square cofiber.glue (glue a)) (Pgluel (f a)) (p ▸ Pgluer (g a)) (pathover_ap P (λa, cofiber.cod h (h a)) (apd (λa, Pcod (h a)) (glue a))) (pathover_ap P (λa, cofiber.base h) (apd (λa, Pbase) (glue a))) := !cofiber_pushout_helper' definition cofiber_pushout_rec {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} (Pcod : Πd, P (cofiber.cod h d)) (Pbase : P (cofiber.base h)) (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (r : C → A) (p : Πa, r (g a) = a) (x : cofiber h) : P x := begin induction x with d x, { exact Pcod d }, { exact Pbase }, { induction x with b c a, { exact Pgluel b }, { exact (cofiber_pushout_helper Pgluel Pgluer (r c)).1 ▸ Pgluer c }, { apply pathover_pathover, rewrite [p a], exact (cofiber_pushout_helper Pgluel Pgluer a).2 }} end /- universal property of cofiber -/ definition cofiber_exact_1 {X Y Z : Type*} (f : X →* Y) (g : pcofiber f →* Z) : (g ∘* pcod f) ∘* f ~* pconst X Z := !passoc ⬝* pwhisker_left _ !pcod_pcompose ⬝* !pcompose_pconst protected definition pcofiber.elim [constructor] {X Y Z : Type*} {f : X →* Y} (g : Y →* Z) (p : g ∘* f ~* pconst X Z) : pcofiber f →* Z := begin fapply pmap.mk, { intro w, induction w with y x, exact g y, exact pt, exact p x }, { reflexivity } end protected definition pcofiber.elim_pcod {X Y Z : Type*} {f : X →* Y} {g : Y →* Z} (p : g ∘* f ~* pconst X Z) : pcofiber.elim g p ∘* pcod f ~* g := begin fapply phomotopy.mk, { intro y, reflexivity }, { esimp, refine !idp_con ⬝ _, refine _ ⬝ (!ap_con ⬝ (!ap_compose'⁻¹ ⬝ !ap_inv) ◾ !elim_glue)⁻¹, apply eq_inv_con_of_con_eq, exact (to_homotopy_pt p)⁻¹ } end /- The maps Z^{C_f} --> Z^Y --> Z^X are exact at Z^Y. Here Y^X means pointed maps from X to Y and C_f is the cofiber of f. The maps are given by precomposing with (pcod f) and f. -/ definition cofiber_exact {X Y Z : Type*} (f : X →* Y) : is_exact_t (@ppcompose_right _ _ Z (pcod f)) (ppcompose_right f) := begin constructor, { intro g, apply eq_of_phomotopy, apply cofiber_exact_1 }, { intro g p, note q := phomotopy_of_eq p, exact fiber.mk (pcofiber.elim g q) (eq_of_phomotopy (pcofiber.elim_pcod q)) } end /- cofiber of pcod is suspension -/ definition pcofiber_pcod {A B : Type*} (f : A →* B) : pcofiber (pcod f) ≃* susp A := begin fapply pequiv_of_equiv, { refine !pushout.symm ⬝e _, exact pushout_vcompose_equiv f equiv.rfl homotopy.rfl homotopy.rfl }, reflexivity end -- definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : -- pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := -- definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : -- pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := -- definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} -- {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : -- pushout h k ≃ pushout hf g := end pushout namespace pushout /- define the quotient using pushout -/ section open quotient sigma.ops variables {A B : Type} (R : A → A → Type) {Q : B → B → Type} (f : A → B) (k : Πa a' : A, R a a' → Q (f a) (f a')) definition pushout_quotient {A : Type} (R : A → A → Type) : Type := @pushout ((Σa a', R a a') ⊎ (Σa a', R a a')) A (Σa a', R a a') (sum.rec pr1 (λx, x.2.1)) (sum.rec id id) variable {R} definition pushout_quotient_of_quotient [unfold 3] (x : quotient R) : pushout_quotient R := begin induction x with a a a' r, { exact inl a }, { exact glue (sum.inl ⟨a, a', r⟩) ⬝ (glue (sum.inr ⟨a, a', r⟩))⁻¹ } end definition quotient_of_pushout_quotient [unfold 3] (x : pushout_quotient R) : quotient R := begin induction x with a x x, { exact class_of R a }, { exact class_of R x.2.1 }, { induction x with x x, exact eq_of_rel R x.2.2, reflexivity } end variable (R) definition quotient_equiv_pushout [constructor] : quotient R ≃ pushout_quotient R := equiv.MK pushout_quotient_of_quotient quotient_of_pushout_quotient abstract begin intro x, induction x with a x x, { reflexivity }, { exact glue (sum.inr x) }, { apply eq_pathover_id_right, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with x x, { refine !elim_eq_of_rel ⬝ph _, induction x with a x, induction x with a' r, exact whisker_bl _ hrfl }, { exact square_of_eq idp }} end end abstract begin intro x, induction x, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose quotient_of_pushout_quotient _ _ ⬝ ap02 _ !elim_eq_of_rel ⬝ _, exact !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) } end end variable {R} definition sigma_functor2 [unfold 7] : (Σ a a', R a a') → (Σ b b', Q b b') := sigma_functor f (λa, sigma_functor f (k a)) definition pushout_quotient_functor [unfold 7] : pushout_quotient R → pushout_quotient Q := let tf := sigma_functor2 f k in pushout.functor (sum_functor tf tf) f tf begin intro x, induction x: reflexivity end begin intro x, induction x: reflexivity end definition quotient_equiv_pushout_natural : hsquare (quotient.functor _ _ f k) (pushout_quotient_functor f k) (quotient_equiv_pushout R) (quotient_equiv_pushout Q) := begin intro x, induction x with a a a' r, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ _ ⬝ (ap_compose (pushout.functor _ _ _ _ _) _ _)⁻¹, refine ap02 _ !elim_eq_of_rel ⬝ _ ⬝ (ap02 _ !elim_eq_of_rel)⁻¹, refine !elim_eq_of_rel ⬝ _, exact (!ap_con ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con) ◾ (!ap_inv ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con)⁻²))⁻¹ } end end end pushout
fe2c6c9897c5a1044f74b5b8827110d94b431354
a51edd9a1700339fa6dc7dc428eb5dfa3994b8bc
/src/misc/experiments.lean
c805c5f76f6339b4c87bd4d91d240d904dc1a756
[]
no_license
avigad/formal_logic
83f5c0534b3e9e7da53eff01bb82289daad65555
59d7fe7cb7a7927fb72d89d4fd40965bcd769349
refs/heads/master
1,585,302,642,116
1,541,000,469,000
1,541,000,469,000
146,376,915
1
1
null
null
null
null
UTF-8
Lean
false
false
5,661
lean
import .vm_check ..syntax /- foo is an rbmap with ("A", 0) to ("Z", 25) -/ def foo := let l := (list.range 26).map (λ i, (char.to_string $ char.of_nat (i + 65), i)) in rbmap.from_list l #eval foo.find "Z" /- check time -/ -- set_option profiler true -- too slow -- theorem bar : foo.find "Z" = some 25 := rfl #eval foo.find "Z" -- curiously, fails; VM doesn't have code associated with bool.tt -- example : tt = tt := by vm_check_tt example : id tt = tt := by vm_check_tt example : tt && tt = tt := by vm_check_tt example : 2 < 5 := vm_check -- fails -- example : 5 < 2 := vm_check -- fails -- example : ∀ x, 2 < x := vm_check example : 1000 * 1000 = 1000000 := vm_check -- set_option profiler true theorem bar : foo.find "Z" = some 25 := vm_check -- fails -- example : ∀ x : nat, x = x := -- assume x, vm_check namespace testeq def foo (s t : string) : nat := if s = t then 0 else 1 def foo' (s t : nat) : nat := if s = t then 0 else 1 def bar (s t : string) : nat → nat | 0 := 0 | (n+1):= foo s t + bar n def bar' (s t : nat) : nat → nat | 0 := 0 | (n+1):= foo' s t + bar' n def baz := "hello" def bla (s : string) : nat → nat | 0 := 0 | (n+1):= foo s s + bla n def bla' := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" def bla'' := "oxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" set_option profiler true /- #eval bar bla' bla' 1000000 #eval bar bla' bla'' 1000000 #eval bar ("o"++ bla') bla'' 1000000 #eval bar "hello" "goodbye" 1000000 #eval bar "hello" "hello" 1000000 #eval bar "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 1000000 --#eval bar baz baz 1000000 --#eval bla "hello" 1000000 --#eval bar' 25 67 1000000 --#eval bar' 43 43 1000000 -/ end testeq /-do tgt ← target, apply `(@of_to_bool_eq_tt %%tgt), skip -/ section open hol open hol.type -- these seem slow set_option profiler true theorem arities_ok_mk_prop : arities_ok mk_prop := by { dsimp [mk_prop, arities_ok, arities_ok_aux, list.empty, coe_sort], reflexivity } theorem arities_ok_mk_list_type (t : type) (h : arities_ok t) : arities_ok (mk_list_type t) = tt := by { dsimp [mk_list_type, arities_ok, coe_sort] at *, dsimp [arities_ok_aux], rw h, reflexivity } theorem arities_ok_mk_list_type' (t : type) (h : arities_ok t) : arities_ok (mk_list_type t) = tt := by { simp [mk_list_type, arities_ok, coe_sort] at *, simp [arities_ok_aux], split, assumption, reflexivity } @[simp] theorem arity_list : constructor.list.arity = 1 := rfl theorem arities_ok_mk_list_type'' (t : type) (h : arities_ok t = tt) : arities_ok (mk_list_type t) = tt := by { simp [arities_ok] at *, simp [mk_list_type, arities_ok_aux, h] } theorem arities_ok_mk_list_type''' (t : type) (h : arities_ok t = tt) : arities_ok (mk_list_type t) = tt := by { dsimp [arities_ok] at *, dsimp [mk_list_type, arities_ok_aux, constructor.list], rw h, reflexivity } -- much faster #eval arities_ok mk_prop #eval arities_ok (mk_list_type mk_prop) end
273381e1dd05e2812b9521975860ae259ff0d26b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finset/pairwise.lean
846fd4d0ac2df7d9d42c82a3e721c14bdf9dc1e9
[ "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
3,374
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.lattice /-! # Relations holding pairwise on finite sets In this file we prove a few results about the interaction of `set.pairwise_disjoint` and `finset`, as well as the interaction of `list.pairwise disjoint` and the condition of `disjoint` on `list.to_finset`, in `set` form. -/ open finset variables {α ι ι' : Type*} instance [decidable_eq α] {r : α → α → Prop} [decidable_rel r] {s : finset α} : decidable ((s : set α).pairwise r) := decidable_of_iff' (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) iff.rfl lemma finset.pairwise_disjoint_range_singleton : (set.range (singleton : α → finset α)).pairwise_disjoint id := begin rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h, exact disjoint_singleton.2 (ne_of_apply_ne _ h), end namespace set lemma pairwise_disjoint.elim_finset {s : set ι} {f : ι → finset α} (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj (finset.not_disjoint_iff.2 ⟨a, hai, haj⟩) lemma pairwise_disjoint.image_finset_of_le [decidable_eq ι] [semilattice_inf α] [order_bot α] {s : finset ι} {f : ι → α} (hs : (s : set ι).pairwise_disjoint f) {g : ι → ι} (hf : ∀ a, f (g a) ≤ f a) : (s.image g : set ι).pairwise_disjoint f := begin rw coe_image, exact hs.image_of_le hf, end variables [lattice α] [order_bot α] /-- Bind operation for `set.pairwise_disjoint`. In a complete lattice, you can use `set.pairwise_disjoint.bUnion`. -/ lemma pairwise_disjoint.bUnion_finset {s : set ι'} {g : ι' → finset ι} {f : ι → α} (hs : s.pairwise_disjoint (λ i' : ι', (g i').sup f)) (hg : ∀ i ∈ s, (g i : set ι).pairwise_disjoint f) : (⋃ i ∈ s, ↑(g i)).pairwise_disjoint f := begin rintro a ha b hb hab, simp_rw set.mem_Union at ha hb, obtain ⟨c, hc, ha⟩ := ha, obtain ⟨d, hd, hb⟩ := hb, obtain hcd | hcd := eq_or_ne (g c) (g d), { exact hg d hd (by rwa hcd at ha) hb hab }, { exact (hs hc hd (ne_of_apply_ne _ hcd)).mono (finset.le_sup ha) (finset.le_sup hb) } end end set namespace list variables {β : Type*} [decidable_eq α] {r : α → α → Prop} {l : list α} lemma pairwise_of_coe_to_finset_pairwise (hl : (l.to_finset : set α).pairwise r) (hn : l.nodup) : l.pairwise r := by { rw coe_to_finset at hl, exact hn.pairwise_of_set_pairwise hl } lemma pairwise_iff_coe_to_finset_pairwise (hn : l.nodup) (hs : symmetric r) : (l.to_finset : set α).pairwise r ↔ l.pairwise r := by { rw [coe_to_finset, hn.pairwise_coe], exact ⟨hs⟩ } lemma pairwise_disjoint_of_coe_to_finset_pairwise_disjoint {α ι} [semilattice_inf α] [order_bot α] [decidable_eq ι] {l : list ι} {f : ι → α} (hl : (l.to_finset : set ι).pairwise_disjoint f) (hn : l.nodup) : l.pairwise (_root_.disjoint on f) := pairwise_of_coe_to_finset_pairwise hl hn lemma pairwise_disjoint_iff_coe_to_finset_pairwise_disjoint {α ι} [semilattice_inf α] [order_bot α] [decidable_eq ι] {l : list ι} {f : ι → α} (hn : l.nodup) : (l.to_finset : set ι).pairwise_disjoint f ↔ l.pairwise (_root_.disjoint on f) := pairwise_iff_coe_to_finset_pairwise hn (symmetric_disjoint.comap f) end list
12d0ecd8c23275294ba10bcd0df7a0ee7e5d40b9
2fbe653e4bc441efde5e5d250566e65538709888
/src/data/set/function.lean
4f7dee85676bb0d47cce4c869ff06395d2e6cafb
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
13,817
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu Functions over sets. -/ import data.set.basic logic.function open function universes u v w x namespace set variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} /- maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (a : set α) (b : set β) : Prop := a ⊆ f ⁻¹' b theorem maps_to' (f : α → β) (a : set α) (b : set β) : maps_to f a b ↔ f '' a ⊆ b := image_subset_iff.symm theorem maps_to_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : maps_to f1 a b) : maps_to f2 a b := λ x h, by rw [mem_preimage, ← h₁ _ h]; exact h₂ h theorem maps_to_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : maps_to g b c) (h₂ : maps_to f a b) : maps_to (g ∘ f) a c := λ x h, h₁ (h₂ h) theorem maps_to_univ (f : α → β) (a) : maps_to f a univ := λ x h, trivial theorem maps_to_image (f : α → β) (a : set α) : maps_to f a (f '' a) := by rw maps_to' theorem maps_to_range (f : α → β) (a : set α) : maps_to f a (range f) := by rw [← image_univ, maps_to']; exact image_subset _ (subset_univ _) theorem image_subset_of_maps_to_of_subset {f : α → β} {a c : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : c ⊆ a) : f '' c ⊆ b := λ y hy, let ⟨x, hx, heq⟩ := hy in by rw [←heq]; apply h₁; apply h₂; assumption theorem image_subset_of_maps_to {f : α → β} {a : set α} {b : set β} (h : maps_to f a b) : f '' a ⊆ b := image_subset_of_maps_to_of_subset h (subset.refl _) /- injectivity -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (a : set α) : Prop := ∀⦃x1 x2 : α⦄, x1 ∈ a → x2 ∈ a → f x1 = f x2 → x1 = x2 theorem inj_on_empty (f : α → β) : inj_on f ∅ := λ _ _ h₁ _ _, false.elim h₁ theorem inj_on_of_eq_on {f1 f2 : α → β} {a : set α} (h₁ : eq_on f1 f2 a) (h₂ : inj_on f1 a) : inj_on f2 a := λ _ _ h₁' h₂' heq, by apply h₂ h₁' h₂'; rw [h₁, heq, ←h₁]; repeat {assumption} theorem inj_on_of_inj_on_of_subset {f : α → β} {a b : set α} (h₁ : inj_on f b) (h₂ : a ⊆ b) : inj_on f a := λ _ _ h₁' h₂' heq, h₁ (h₂ h₁') (h₂ h₂') heq lemma injective_iff_inj_on_univ {f : α → β} : injective f ↔ inj_on f univ := iff.intro (λ h _ _ _ _ heq, h heq) (λ h _ _ heq, h trivial trivial heq) lemma inj_on_of_injective {α β : Type*} {f : α → β} (s : set α) (h : injective f) : inj_on f s := inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 h) (subset_univ s) theorem inj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : inj_on g b) (h₃: inj_on f a) : inj_on (g ∘ f) a := λ _ _ h₁' h₂' heq, by apply h₃ h₁' h₂'; apply h₂; repeat {apply h₁, assumption}; assumption lemma inj_on_comp_of_injective_left {g : β → γ} {f : α → β} {a : set α} (hg : injective g) (hf : inj_on f a) : inj_on (g ∘ f) a := inj_on_comp (maps_to_univ _ _) (injective_iff_inj_on_univ.mp hg) hf lemma inj_on_iff_injective {f : α → β} {s : set α} : inj_on f s ↔ injective (λ x:s, f x.1) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a b as bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ lemma inv_fun_on_image [inhabited α] {β : Type v} {s t : set α} {f : α → β} (h : inj_on f s) (ht : t ⊆ s) : (inv_fun_on f s) '' (f '' t) = t := begin have A : ∀z, z ∈ t → ((inv_fun_on f s) ∘ f) z = z := λz hz, inv_fun_on_eq' h (ht hz), rw ← image_comp, ext, simp [A] {contextual := tt} end lemma inj_on_preimage {f : α → β} {B : set (set β)} (hB : B ⊆ powerset (range f)) : inj_on (preimage f) B := begin intros s t hs ht hst, rw [←image_preimage_eq_of_subset (hB hs), ←image_preimage_eq_of_subset (hB ht), hst] end lemma subset_image_iff {s : set α} {t : set β} (f : α → β) : t ⊆ f '' s ↔ ∃u⊆s, t = f '' u ∧ inj_on f u := begin split, { assume h, choose g hg using h, refine ⟨ {a | ∃ b (h : b ∈ t), g h = a }, _, set.ext $ assume b, ⟨_, _⟩, _⟩, { rintros a ⟨b, hb, rfl⟩, exact (hg hb).1 }, { rintros hb, exact ⟨g hb, ⟨b, hb, rfl⟩, (hg hb).2⟩ }, { rintros ⟨c, ⟨b, hb, rfl⟩, rfl⟩, rwa (hg hb).2 }, { rintros a₁ a₂ ⟨b₁, h₁, rfl⟩ ⟨b₂, h₂, rfl⟩ eq, rw [(hg h₁).2, (hg h₂).2] at eq, subst eq } }, { rintros ⟨u, hu, rfl, _⟩, exact image_subset _ hu } end lemma subset_range_iff {s : set β} (f : α → β) : s ⊆ set.range f ↔ ∃u, s = f '' u ∧ inj_on f u := by rw [← image_univ, subset_image_iff]; simp /- surjectivity -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (a : set α) (b : set β) : Prop := b ⊆ f '' a theorem surj_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : surj_on f1 a b) : surj_on f2 a b := λ _ h, let ⟨x, hx⟩ := h₂ h in ⟨x, hx.left, by rw [←h₁ _ hx.left]; exact hx.right⟩ theorem surj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : surj_on g b c) (h₂ : surj_on f a b) : surj_on (g ∘ f) a c := λ z h, let ⟨y, hy⟩ := h₁ h, ⟨x, hx⟩ := h₂ hy.left in ⟨x, hx.left, calc g (f x) = g y : by rw [hx.right] ... = z : hy.right⟩ lemma surjective_iff_surj_on_univ {f : α → β} : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective {f : α → β} {s : set α} : surj_on f s univ ↔ surjective (λ x:s, f x.1) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma image_eq_of_maps_to_of_surj_on {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : surj_on f a b) : f '' a = b := eq_of_subset_of_subset (image_subset_of_maps_to h₁) h₂ /- bijectivity -/ /-- `f` is bijective from `a` to `b` if `f` is injective on `a` and `f '' a = b`. -/ @[reducible] def bij_on (f : α → β) (a : set α) (b : set β) : Prop := maps_to f a b ∧ inj_on f a ∧ surj_on f a b lemma maps_to_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : maps_to f a b := h.left lemma inj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : inj_on f a := h.right.left lemma surj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : surj_on f a b := h.right.right lemma bij_on.mk {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : inj_on f a) (h₃ : surj_on f a b) : bij_on f a b := ⟨h₁, h₂, h₃⟩ lemma inj_on.to_bij_on {f : α → β} {a : set α} (h : inj_on f a) : bij_on f a (f '' a) := bij_on.mk (maps_to_image f a) h (subset.refl _) theorem bij_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : bij_on f1 a b) : bij_on f2 a b := let ⟨map, inj, surj⟩ := h₂ in ⟨maps_to_of_eq_on h₁ map, inj_on_of_eq_on h₁ inj, surj_on_of_eq_on h₁ surj⟩ lemma image_eq_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : f '' a = b := image_eq_of_maps_to_of_surj_on h.left h.right.right theorem bij_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : bij_on g b c) (h₂: bij_on f a b) : bij_on (g ∘ f) a c := let ⟨gmap, ginj, gsurj⟩ := h₁, ⟨fmap, finj, fsurj⟩ := h₂ in ⟨maps_to_comp gmap fmap, inj_on_comp fmap ginj finj, surj_on_comp gsurj fsurj⟩ lemma bijective_iff_bij_on_univ {f : α → β} : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) /- left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (g : β → α) (f : α → β) (a : set α) : Prop := ∀ x ∈ a, g (f x) = x theorem left_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : eq_on g1 g2 b) (h₃ : left_inv_on g1 f a) : left_inv_on g2 f a := λ x h, calc g2 (f x) = g1 (f x) : eq.symm $ h₂ _ (h₁ h) ... = x : h₃ _ h theorem left_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α} (h₁ : eq_on f1 f2 a) (h₂ : left_inv_on g f1 a) : left_inv_on g f2 a := λ x h, calc g (f2 x) = g (f1 x) : congr_arg g (h₁ _ h).symm ... = x : h₂ _ h theorem inj_on_of_left_inv_on {g : β → α} {f : α → β} {a : set α} (h : left_inv_on g f a) : inj_on f a := λ x₁ x₂ h₁ h₂ heq, calc x₁ = g (f x₁) : eq.symm $ h _ h₁ ... = g (f x₂) : congr_arg g heq ... = x₂ : h _ h₂ theorem left_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : left_inv_on f' f a) (h₃ : left_inv_on g' g b) : left_inv_on (f' ∘ g') (g ∘ f) a := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (h₃ _ (h₁ h)) ... = x : h₂ _ h /- right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (g : β → α) (f : α → β) (b : set β) : Prop := left_inv_on f g b theorem right_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {b : set β} (h₁ : eq_on g1 g2 b) (h₂ : right_inv_on g1 f b) : right_inv_on g2 f b := left_inv_on_of_eq_on_right h₁ h₂ theorem right_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : maps_to g b a) (h₂ : eq_on f1 f2 a) (h₃ : right_inv_on g f1 b) : right_inv_on g f2 b := left_inv_on_of_eq_on_left h₁ h₂ h₃ theorem surj_on_of_right_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to g b a) (h₂ : right_inv_on g f b) : surj_on f a b := λ y h, ⟨g y, h₁ h, h₂ _ h⟩ theorem right_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β} {c : set γ} {b : set β} (g'cb : maps_to g' c b) (h₁ : right_inv_on f' f b) (h₂ : right_inv_on g' g c) : right_inv_on (f' ∘ g') (g ∘ f) c := left_inv_on_comp g'cb h₂ h₁ theorem right_inv_on_of_inj_on_of_left_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : maps_to g b a) (h₃ : inj_on f a) (h₄ : left_inv_on f g b) : right_inv_on f g a := λ x h, h₃ (h₂ $ h₁ h) h (h₄ _ (h₁ h)) theorem eq_on_of_left_inv_of_right_inv {g₁ g₂ : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to g₂ b a) (h₂ : left_inv_on g₁ f a) (h₃ : right_inv_on g₂ f b) : eq_on g₁ g₂ b := λ y h, calc g₁ y = (g₁ ∘ f ∘ g₂) y : congr_arg g₁ (h₃ _ h).symm ... = g₂ y : h₂ _ (h₁ h) theorem left_inv_on_of_surj_on_right_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β} (h₁ : surj_on f a b) (h₂ : right_inv_on f g a) : left_inv_on f g b := λ y h, let ⟨x, hx, heq⟩ := h₁ h in calc (f ∘ g) y = (f ∘ g ∘ f) x : congr_arg (f ∘ g) heq.symm ... = f x : congr_arg f (h₂ _ hx) ... = y : heq /- inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (a : set α) (b : set β) : Prop := left_inv_on g f a ∧ right_inv_on g f b theorem bij_on_of_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : maps_to g b a) (h₃ : inv_on g f a b) : bij_on f a b := ⟨h₁, inj_on_of_left_inv_on h₃.left, surj_on_of_right_inv_on h₂ h₃.right⟩ lemma range_restrict {α : Type*} {β : Type*} (f : α → β) (p : set α) : range (restrict f p) = f '' (p : set α) := by { ext x, simp [restrict], refl } section piecewise variables {δ : α → Sort v} (s : set α) (f g : Πi, δ i) @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] : piecewise set.univ f g = f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀j, decidable (j ∈ s)] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin simp [piecewise], ext i, by_cases h : i = j, { rw h, simp }, { by_cases h' : i ∈ s; simp [h, h'] } end @[simp] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] @[simp] lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by { simp [piecewise, h], congr } end piecewise end set
efbeed48a619784f91f7c910d1cb30accb00f776
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/measure_theory/function/ae_measurable_sequence.lean
431b0ff47d3e699e12d7373cce5050191a48981e
[ "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
6,378
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.measure.measure_space /-! # Sequence of measurable functions associated to a sequence of a.e.-measurable functions We define here tools to prove statements about limits (infi, supr...) of sequences of `ae_measurable` functions. Given a sequence of a.e.-measurable functions `f : ι → α → β` with hypothesis `hf : ∀ i, ae_measurable (f i) μ`, and a pointwise property `p : α → (ι → β) → Prop` such that we have `hp : ∀ᵐ x ∂μ, p x (λ n, f n x)`, we define a sequence of measurable functions `ae_seq hf p` and a measurable set `ae_seq_set hf p`, such that * `μ (ae_seq_set hf p)ᶜ = 0` * `x ∈ ae_seq_set hf p → ∀ i : ι, ae_seq hf hp i x = f i x` * `x ∈ ae_seq_set hf p → p x (λ n, f n x)` -/ open measure_theory open_locale classical variables {α β γ ι : Type*} [measurable_space α] [measurable_space β] {f : ι → α → β} {μ : measure α} {p : α → (ι → β) → Prop} /-- If we have the additional hypothesis `∀ᵐ x ∂μ, p x (λ n, f n x)`, this is a measurable set whose complement has measure 0 such that for all `x ∈ ae_seq_set`, `f i x` is equal to `(hf i).mk (f i) x` for all `i` and we have the pointwise property `p x (λ n, f n x)`. -/ def ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : set α := (to_measurable μ {x | (∀ i, f i x = (hf i).mk (f i) x) ∧ p x (λ n, f n x)}ᶜ)ᶜ /-- A sequence of measurable functions that are equal to `f` and verify property `p` on the measurable set `ae_seq_set hf p`. -/ noncomputable def ae_seq (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : ι → α → β := λ i x, ite (x ∈ ae_seq_set hf p) ((hf i).mk (f i) x) (⟨f i x⟩ : nonempty β).some namespace ae_seq section mem_ae_seq_set lemma mk_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : (hf i).mk (f i) x = f i x := begin have h_ss : ae_seq_set hf p ⊆ {x | ∀ i, f i x = (hf i).mk (f i) x}, { rw [ae_seq_set, ←compl_compl {x | ∀ i, f i x = (hf i).mk (f i) x}, set.compl_subset_compl], refine set.subset.trans (set.compl_subset_compl.mpr (λ x h, _)) (subset_to_measurable _ _), exact h.1, }, exact (h_ss hx i).symm, end lemma ae_seq_eq_mk_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : ae_seq hf p i x = (hf i).mk (f i) x := by simp only [ae_seq, hx, if_true] lemma ae_seq_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : ae_seq hf p i x = f i x := by simp only [ae_seq_eq_mk_of_mem_ae_seq_set hf hx i, mk_eq_fun_of_mem_ae_seq_set hf hx i] lemma prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) : p x (λ n, ae_seq hf p n x) := begin simp only [ae_seq, hx, if_true], rw funext (λ n, mk_eq_fun_of_mem_ae_seq_set hf hx n), have h_ss : ae_seq_set hf p ⊆ {x | p x (λ n, f n x)}, { rw [←compl_compl {x | p x (λ n, f n x)}, ae_seq_set, set.compl_subset_compl], refine set.subset.trans (set.compl_subset_compl.mpr _) (subset_to_measurable _ _), exact λ x hx, hx.2, }, have hx' := set.mem_of_subset_of_mem h_ss hx, exact hx', end lemma fun_prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) : p x (λ n, f n x) := begin have h_eq : (λ n, f n x) = λ n, ae_seq hf p n x, from funext (λ n, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx n).symm), rw h_eq, exact prop_of_mem_ae_seq_set hf hx, end end mem_ae_seq_set lemma ae_seq_set_measurable_set {hf : ∀ i, ae_measurable (f i) μ} : measurable_set (ae_seq_set hf p) := (measurable_set_to_measurable _ _).compl lemma measurable (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) (i : ι) : measurable (ae_seq hf p i) := begin refine measurable.ite ae_seq_set_measurable_set (hf i).measurable_mk _, by_cases hα : nonempty α, { exact @measurable_const _ _ _ _ (⟨f i hα.some⟩ : nonempty β).some }, { exact measurable_of_not_nonempty hα _ } end lemma measure_compl_ae_seq_set_eq_zero [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : μ (ae_seq_set hf p)ᶜ = 0 := begin rw [ae_seq_set, compl_compl, measure_to_measurable], have hf_eq := λ i, (hf i).ae_eq_mk, simp_rw [filter.eventually_eq, ←ae_all_iff] at hf_eq, exact filter.eventually.and hf_eq hp, end lemma ae_seq_eq_mk_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : ∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = (hf i).mk (f i) a := begin have h_ss : ae_seq_set hf p ⊆ {a : α | ∀ i, ae_seq hf p i a = (hf i).mk (f i) a}, from λ x hx i, by simp only [ae_seq, hx, if_true], exact le_antisymm (le_trans (measure_mono (set.compl_subset_compl.mpr h_ss)) (le_of_eq (measure_compl_ae_seq_set_eq_zero hf hp))) (zero_le _), end lemma ae_seq_eq_fun_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : ∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = f i a := begin have h_ss : {a : α | ¬∀ (i : ι), ae_seq hf p i a = f i a} ⊆ (ae_seq_set hf p)ᶜ, from λ x, mt (λ hx i, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx i)), exact measure_mono_null h_ss (measure_compl_ae_seq_set_eq_zero hf hp), end lemma ae_seq_n_eq_fun_n_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) (n : ι) : ae_seq hf p n =ᵐ[μ] f n:= ae_all_iff.mp (ae_seq_eq_fun_ae hf hp) n lemma supr [complete_lattice β] [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : (⨆ n, ae_seq hf p n) =ᵐ[μ] ⨆ n, f n := begin simp_rw [filter.eventually_eq, ae_iff, supr_apply], have h_ss : ae_seq_set hf p ⊆ {a : α | (⨆ (i : ι), ae_seq hf p i a) = ⨆ (i : ι), f i a}, { intros x hx, congr, exact funext (λ i, ae_seq_eq_fun_of_mem_ae_seq_set hf hx i), }, exact measure_mono_null (set.compl_subset_compl.mpr h_ss) (measure_compl_ae_seq_set_eq_zero hf hp), end end ae_seq
0668b21fef1a2e054353c21aea5990a7abed2a85
690889011852559ee5ac4dfea77092de8c832e7e
/src/topology/sheaves/stalks.lean
fc0073c15b566b7b8636997e221988218b98a247
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
3,576
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 topology.category.Top.open_nhds import topology.sheaves.presheaf import category_theory.limits.limits universes v u v' u' open category_theory open Top open category_theory.limits open topological_space variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit (nbhds_inclusion x ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl variables (C) def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ), end -- Here are two other potential solutions, suggested by @fpvandoorn at -- https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240 -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', cases j, cases j_val, rw [colim.ι_map_assoc, colim.ι_map, colimit.ι_pre, whisker_left.app, whisker_right.app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, rw [category_theory.functor.map_id] end @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor, pushforward], ext U, op_induction U, cases U, cases U_val, simp only [colim.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_right.app, category.assoc], dsimp, simp only [category.id_comp, category_theory.functor.map_id], -- FIXME A simp lemma which unfortunately doesn't fire: rw [category_theory.functor.map_id], dsimp, simp, end end stalk_pushforward end Top.presheaf
ec667e9536334e3911ca14450a0b83d2a2832aa4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/sigma/default.lean
f08d0226bfc22a03bb05e01625f136e79ead9658
[]
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
299
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.sigma.basic import Mathlib.Lean3Lib.init.data.sigma.lex namespace Mathlib
784275c6d6ab3bee6810f579072c8224782290c2
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/monotone.lean
0939b142af10ef08e1720529bf8fdf608a421c6b
[ "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
1,642
lean
class Preorder (α : Type u) extends LE α where le_refl (a : α) : a ≤ a le_trans {a b c : α} : a ≤ b → b ≤ c → a ≤ c instance {α : Type u} {β : α → Type v} [(a : α) → Preorder (β a)] : Preorder ((a : α) → β a) where le f g := ∀ a, f a ≤ g a le_refl f := fun a => Preorder.le_refl (f a) le_trans := fun h₁ h₂ a => Preorder.le_trans (h₁ a) (h₂ a) -- In Lean 3, we defined `monotone` using the strict implicit notation `{{ ... }}`. -- Implicit lambdas in Lean 4 allow us to use the regular `{...}` def Monotone [Preorder α] [Preorder β] (f : α → β) := ∀ {a b}, a ≤ b → f a ≤ f b theorem monotone_id [Preorder α] : Monotone (α := α) id := fun h => h theorem monotone_id' [Preorder α] : Monotone (α := α) id := @fun a b h => h -- `@` disables implicit lambdas theorem monotone_id'' [Preorder α] : Monotone (α := α) id := fun {a b} (h : a ≤ b) => h -- `{a b}` disables implicit lambdas theorem monotone_const [Preorder α] [Preorder β] (b : β) : Monotone (fun a : α => b) := fun _ => Preorder.le_refl b theorem monotone_comp [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} (m_g : Monotone g) (m_f : Monotone f) : Monotone (g ∘ f) := fun h => m_g (m_f h) theorem monotone_fun [Preorder α] [Preorder γ] {f : α → β → γ} (m : (b : β) → Monotone (fun a => f a b)) : Monotone f := fun h b => m b h theorem ex [Preorder α] {f g h : α → α} (m_h : Monotone h) (m_g : Monotone g) (m_f : Monotone f) : Monotone (h ∘ g ∘ f) := monotone_comp m_h (monotone_comp m_g m_f) -- implicit lambdas in action here
1aba0e338476aae0ec33ef470c7ead8cf9f91236
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/polynomial/derivative.lean
a9d936d220f6a88a431879a3915a00b072784e60
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
10,108
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.eval /-! # Theory of univariate polynomials -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ} section derivative section semiring variables [semiring R] /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative (p : polynomial R) : polynomial R := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial R) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1)], simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast, swap, { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one, mem_support_iff], intro h, push_neg at h, simp [h], }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul], }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } } end @[simp] lemma derivative_zero : derivative (0 : polynomial R) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : R) (n : ℕ) : derivative (monomial n a) = monomial (n - 1) (a * n) := (sum_single_index $ by simp).trans (C_mul_X_pow_eq_monomial _ _) lemma derivative_C_mul_X_pow (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [C_mul_X_pow_eq_monomial, C_mul_X_pow_eq_monomial, derivative_monomial] @[simp] lemma derivative_C {a : R} : derivative (C a) = 0 := (derivative_monomial a 0).trans $ by simp @[simp] lemma derivative_X : derivative (X : polynomial R) = 1 := (derivative_monomial _ _).trans $ by simp @[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial R} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] /-- The formal derivative of polynomials, as additive homomorphism. -/ def derivative_hom (R : Type*) [semiring R] : polynomial R →+ polynomial R := { to_fun := derivative, map_zero' := derivative_zero, map_add' := λ p q, derivative_add } @[simp] lemma derivative_neg {R : Type*} [ring R] (f : polynomial R) : derivative (-f) = -derivative f := (derivative_hom R).map_neg f @[simp] lemma derivative_sub {R : Type*} [ring R] (f g : polynomial R) : derivative (f - g) = derivative f - derivative g := (derivative_hom R).map_sub f g instance : is_add_monoid_hom (derivative : polynomial R → polynomial R) := (derivative_hom R).is_add_monoid_hom @[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} : derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) := (derivative_hom R).map_sum f s @[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p := by { ext, simp only [coeff_derivative, mul_assoc, coeff_smul], } end semiring section comm_semiring variables [comm_semiring R] @[simp] lemma derivative_mul {f g : polynomial R} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_C_mul_X_pow _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end theorem derivative_pow_succ (p : polynomial R) (n : ℕ) : (p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative := nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih, by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul, add_mul (n.succ : polynomial R), one_mul, pow_succ', mul_assoc, n.cast_succ] theorem derivative_pow (p : polynomial R) (n : ℕ) : (p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative := nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n, by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ] theorem derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) : (p.map f).derivative = p.derivative.map f := polynomial.induction_on p (λ r, by rw [map_C, derivative_C, derivative_C, map_zero]) (λ p q ihp ihq, by rw [map_add, derivative_add, ihp, ihq, derivative_add, map_add]) (λ n r ih, by rw [map_mul, map_C, map_pow, map_X, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, map_mul, map_C, map_mul, map_pow, map_add, map_nat_cast, map_one, map_X]) /-- Chain rule for formal derivative of polynomials. -/ theorem derivative_eval₂_C (p q : polynomial R) : (p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative := polynomial.induction_on p (λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul]) (λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul]) (λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih, @derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X, add_mul, mul_right_comm]) theorem of_mem_support_derivative {p : polynomial R} {n : ℕ} (h : n ∈ p.derivative.support) : n + 1 ∈ p.support := finsupp.mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), finsupp.mem_support_iff.1 h $ show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul] theorem degree_derivative_lt {p : polynomial R} (hp : p ≠ 0) : p.derivative.degree < p.degree := (finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le (with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp theorem nat_degree_derivative_lt {p : polynomial R} (hp : p.derivative ≠ 0) : p.derivative.nat_degree < p.nat_degree := have hp1 : p ≠ 0, from λ h, hp $ by rw [h, derivative_zero], with_bot.some_lt_some.1 $ by { rw [nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp, nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp1], exact degree_derivative_lt hp1 } theorem degree_derivative_le {p : polynomial R} : p.derivative.degree ≤ p.degree := if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else le_of_lt $ degree_derivative_lt H /-- The formal derivative of polynomials, as linear homomorphism. -/ def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R := { to_fun := derivative, map_add' := λ p q, derivative_add, map_smul' := λ r p, derivative_smul r p } end comm_semiring section domain variables [integral_domain R] lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [mem_support_iff_coeff_ne_zero, coeff_derivative, ne.def, mul_eq_zero], by { rw [nat.cast_eq_zero], simp only [nat.succ_ne_zero, or_false] } @[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_C_mul_X_pow_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end theorem nat_degree_eq_zero_of_derivative_eq_zero [char_zero R] {f : polynomial R} (h : f.derivative = 0) : f.nat_degree = 0 := begin by_cases hf : f = 0, { exact (congr_arg polynomial.nat_degree hf).trans rfl }, { rw nat_degree_eq_zero_iff_degree_le_zero, by_contra absurd, have f_nat_degree_pos : 0 < f.nat_degree, { rwa [not_le, ←nat_degree_pos_iff_degree_pos] at absurd }, let m := f.nat_degree - 1, have hm : m + 1 = f.nat_degree := nat.sub_add_cancel f_nat_degree_pos, have h2 := coeff_derivative f m, rw polynomial.ext_iff at h, rw [h m, coeff_zero, zero_eq_mul] at h2, cases h2, { rw [hm, ←leading_coeff, leading_coeff_eq_zero] at h2, exact hf h2, }, { norm_cast at h2 } } end end domain end derivative end polynomial
4207f4448ba78d4455edad86161b1fbf1db64719
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_geometry/presheafed_space/has_colimits.lean
3fde6da6ad2691384deb228e354b2262afb6dce1
[ "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
14,170
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 algebraic_geometry.presheafed_space import topology.category.Top.limits import topology.sheaves.limits import category_theory.limits.concrete_category /-! # `PresheafedSpace C` has colimits. If `C` has limits, then the category `PresheafedSpace C` has colimits, and the forgetful functor to `Top` preserves these colimits. When restricted to a diagram where the underlying continuous maps are open embeddings, this says that we can glue presheaved spaces. Given a diagram `F : J ⥤ PresheafedSpace C`, we first build the colimit of the underlying topological spaces, as `colimit (F ⋙ PresheafedSpace.forget C)`. Call that colimit space `X`. Our strategy is to push each of the presheaves `F.obj j` forward along the continuous map `colimit.ι (F ⋙ PresheafedSpace.forget C) j` to `X`. Since pushforward is functorial, we obtain a diagram `J ⥤ (presheaf C X)ᵒᵖ` of presheaves on a single space `X`. (Note that the arrows now point the other direction, because this is the way `PresheafedSpace C` is set up.) The limit of this diagram then constitutes the colimit presheaf. -/ noncomputable theory universes v u open category_theory open Top open Top.presheaf open topological_space open opposite open category_theory.category open category_theory.limits open category_theory.functor variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] namespace algebraic_geometry namespace PresheafedSpace @[simp] lemma map_id_c_app (F : J ⥤ PresheafedSpace C) (j) (U) : (F.map (𝟙 j)).c.app (op U) = (pushforward.id (F.obj j).presheaf).inv.app (op U) ≫ (pushforward_eq (by { simp, refl }) (F.obj j).presheaf).hom.app (op U) := begin cases U, dsimp, simp [PresheafedSpace.congr_app (F.map_id j)], refl, end @[simp] lemma map_comp_c_app (F : J ⥤ PresheafedSpace C) {j₁ j₂ j₃} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃) (U) : (F.map (f ≫ g)).c.app (op U) = (F.map g).c.app (op U) ≫ (pushforward_map (F.map g).base (F.map f).c).app (op U) ≫ (pushforward.comp (F.obj j₁).presheaf (F.map f).base (F.map g).base).inv.app (op U) ≫ (pushforward_eq (by { rw F.map_comp, refl }) _).hom.app _ := begin cases U, dsimp, simp only [PresheafedSpace.congr_app (F.map_comp f g)], dsimp, simp, dsimp, simp, -- See note [dsimp, simp] end /-- Given a diagram of presheafed spaces, we can push all the presheaves forward to the colimit `X` of the underlying topological spaces, obtaining a diagram in `(presheaf C X)ᵒᵖ`. -/ @[simps] def pushforward_diagram_to_colimit (F : J ⥤ PresheafedSpace C) : J ⥤ (presheaf C (colimit (F ⋙ PresheafedSpace.forget C)))ᵒᵖ := { obj := λ j, op ((colimit.ι (F ⋙ PresheafedSpace.forget C) j) _* (F.obj j).presheaf), map := λ j j' f, (pushforward_map (colimit.ι (F ⋙ PresheafedSpace.forget C) j') (F.map f).c ≫ (pushforward.comp (F.obj j).presheaf ((F ⋙ PresheafedSpace.forget C).map f) (colimit.ι (F ⋙ PresheafedSpace.forget C) j')).inv ≫ (pushforward_eq (colimit.w (F ⋙ PresheafedSpace.forget C) f) (F.obj j).presheaf).hom).op, map_id' := λ j, begin apply (op_equiv _ _).injective, ext U, induction U using opposite.rec, cases U, dsimp, simp, dsimp, simp, end, map_comp' := λ j₁ j₂ j₃ f g, begin apply (op_equiv _ _).injective, ext U, dsimp, simp only [map_comp_c_app, id.def, eq_to_hom_op, pushforward_map_app, eq_to_hom_map, assoc, id_comp, pushforward.comp_inv_app, pushforward_eq_hom_app], dsimp, simp only [eq_to_hom_trans, id_comp], congr' 1, -- The key fact is `(F.map f).c.congr`, -- which allows us in rewrite in the argument of `(F.map f).c.app`. rw (F.map f).c.congr, -- Now we pick up the pieces. First, we say what we want to replace that open set by: swap 3, refine op ((opens.map (colimit.ι (F ⋙ PresheafedSpace.forget C) j₂)).obj (unop U)), -- Now we show the open sets are equal. swap 2, { apply unop_injective, rw ←opens.map_comp_obj, congr, exact colimit.w (F ⋙ PresheafedSpace.forget C) g, }, -- Finally, the original goal is now easy: swap 2, { simp, refl, }, end, } variables [has_limits C] /-- Auxiliary definition for `PresheafedSpace.has_colimits`. -/ def colimit (F : J ⥤ PresheafedSpace C) : PresheafedSpace C := { carrier := colimit (F ⋙ PresheafedSpace.forget C), presheaf := limit (pushforward_diagram_to_colimit F).left_op, } @[simp] lemma colimit_carrier (F : J ⥤ PresheafedSpace C) : (colimit F).carrier = limits.colimit (F ⋙ PresheafedSpace.forget C) := rfl @[simp] lemma colimit_presheaf (F : J ⥤ PresheafedSpace C) : (colimit F).presheaf = limit (pushforward_diagram_to_colimit F).left_op := rfl /-- Auxiliary definition for `PresheafedSpace.has_colimits`. -/ @[simps] def colimit_cocone (F : J ⥤ PresheafedSpace C) : cocone F := { X := colimit F, ι := { app := λ j, { base := colimit.ι (F ⋙ PresheafedSpace.forget C) j, c := limit.π _ (op j), }, naturality' := λ j j' f, begin fapply PresheafedSpace.ext, { ext x, exact colimit.w_apply (F ⋙ PresheafedSpace.forget C) f x, }, { ext U, induction U using opposite.rec, cases U, dsimp, simp only [PresheafedSpace.id_c_app, eq_to_hom_op, eq_to_hom_map, assoc, pushforward.comp_inv_app], rw ← congr_arg nat_trans.app (limit.w (pushforward_diagram_to_colimit F).left_op f.op), dsimp, simp only [eq_to_hom_op, eq_to_hom_map, assoc, id_comp, pushforward.comp_inv_app], congr, dsimp, simp only [id_comp], simpa, } end, }, } namespace colimit_cocone_is_colimit /-- Auxiliary definition for `PresheafedSpace.colimit_cocone_is_colimit`. -/ def desc_c_app (F : J ⥤ PresheafedSpace C) (s : cocone F) (U : (opens ↥(s.X.carrier))ᵒᵖ) : s.X.presheaf.obj U ⟶ (colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s) _* limit (pushforward_diagram_to_colimit F).left_op).obj U := begin refine limit.lift _ { X := s.X.presheaf.obj U, π := { app := λ j, _, naturality' := λ j j' f, _, }} ≫ (limit_obj_iso_limit_comp_evaluation _ _).inv, -- We still need to construct the `app` and `naturality'` fields omitted above. { refine (s.ι.app (unop j)).c.app U ≫ (F.obj (unop j)).presheaf.map (eq_to_hom _), dsimp, rw ←opens.map_comp_obj, simp, }, { rw (PresheafedSpace.congr_app (s.w f.unop).symm U), dsimp, have w := functor.congr_obj (congr_arg opens.map (colimit.ι_desc ((PresheafedSpace.forget C).map_cocone s) (unop j))) (unop U), simp only [opens.map_comp_obj_unop] at w, replace w := congr_arg op w, have w' := nat_trans.congr (F.map f.unop).c w, rw w', dsimp, simp, dsimp, simp, }, end lemma desc_c_naturality (F : J ⥤ PresheafedSpace C) (s : cocone F) {U V : (opens ↥(s.X.carrier))ᵒᵖ} (i : U ⟶ V) : s.X.presheaf.map i ≫ desc_c_app F s V = desc_c_app F s U ≫ (colimit.desc (F ⋙ forget C) ((forget C).map_cocone s) _* (colimit_cocone F).X.presheaf).map i := begin dsimp [desc_c_app], ext, simp only [limit.lift_π, nat_trans.naturality, limit.lift_π_assoc, eq_to_hom_map, assoc, pushforward_obj_map, nat_trans.naturality_assoc, op_map, limit_obj_iso_limit_comp_evaluation_inv_π_app_assoc, limit_obj_iso_limit_comp_evaluation_inv_π_app], dsimp, have w := functor.congr_hom (congr_arg opens.map (colimit.ι_desc ((PresheafedSpace.forget C).map_cocone s) (unop j))) (i.unop), simp only [opens.map_comp_map] at w, replace w := congr_arg quiver.hom.op w, rw w, dsimp, simp, end /-- Auxiliary definition for `PresheafedSpace.colimit_cocone_is_colimit`. -/ def desc (F : J ⥤ PresheafedSpace C) (s : cocone F) : colimit F ⟶ s.X := { base := colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s), c := { app := λ U, desc_c_app F s U, naturality' := λ U V i, desc_c_naturality F s i } } lemma desc_fac (F : J ⥤ PresheafedSpace C) (s : cocone F) (j : J) : (colimit_cocone F).ι.app j ≫ desc F s = s.ι.app j := begin fapply PresheafedSpace.ext, { simp [desc] }, { ext, dsimp [desc, desc_c_app], simpa } end end colimit_cocone_is_colimit open colimit_cocone_is_colimit /-- Auxiliary definition for `PresheafedSpace.has_colimits`. -/ def colimit_cocone_is_colimit (F : J ⥤ PresheafedSpace C) : is_colimit (colimit_cocone F) := { desc := λ s, desc F s, fac' := λ s, desc_fac F s, uniq' := λ s m w, begin -- We need to use the identity on the continuous maps twice, so we prepare that first: have t : m.base = colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s), { apply category_theory.limits.colimit.hom_ext, intros j, apply continuous_map.ext, intros x, dsimp, simp only [colimit.ι_desc_apply, map_cocone_ι_app], rw ← w j, simp, }, fapply PresheafedSpace.ext, -- could `ext` please not reorder goals? { exact t, }, { ext U j, dsimp [desc, desc_c_app], simp only [limit.lift_π, eq_to_hom_op, eq_to_hom_map, assoc, limit_obj_iso_limit_comp_evaluation_inv_π_app], rw PresheafedSpace.congr_app (w (unop j)).symm U, dsimp, have w := congr_arg op (functor.congr_obj (congr_arg opens.map t) (unop U)), rw nat_trans.congr (limit.π (pushforward_diagram_to_colimit F).left_op j) w, simp } end, } /-- When `C` has limits, the category of presheaved spaces with values in `C` itself has colimits. -/ instance : has_colimits (PresheafedSpace C) := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } /-- The underlying topological space of a colimit of presheaved spaces is the colimit of the underlying topological spaces. -/ instance forget_preserves_colimits : preserves_colimits (PresheafedSpace.forget C) := { preserves_colimits_of_shape := λ J 𝒥, by exactI { preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone (colimit_cocone_is_colimit F) begin apply is_colimit.of_iso_colimit (colimit.is_colimit _), fapply cocones.ext, { refl, }, { intro j, dsimp, simp, } end } } /-- Given a diagram of `PresheafedSpace C`s, its colimit is computed by pushing the sheaves onto the colimit of the underlying spaces, and taking componentwise limit. This is the componentwise diagram for an open set `U` of the colimit of the underlying spaces. -/ @[simps] def componentwise_diagram (F : J ⥤ PresheafedSpace C) (U : opens (limits.colimit F).carrier) : Jᵒᵖ ⥤ C := { obj := λ j, (F.obj (unop j)).presheaf.obj (op ((opens.map (colimit.ι F (unop j)).base).obj U)), map := λ j k f, (F.map f.unop).c.app _ ≫ (F.obj (unop k)).presheaf.map (eq_to_hom (by { rw [← colimit.w F f.unop, comp_base], refl })), map_comp' := λ i j k f g, begin cases U, dsimp, simp_rw [map_comp_c_app, category.assoc], congr' 1, rw [Top.presheaf.pushforward.comp_inv_app, Top.presheaf.pushforward_eq_hom_app, category_theory.nat_trans.naturality_assoc, Top.presheaf.pushforward_map_app], congr' 1, rw [category.id_comp, ← (F.obj (unop k)).presheaf.map_comp], erw ← (F.obj (unop k)).presheaf.map_comp, congr end } /-- The components of the colimit of a diagram of `PresheafedSpace C` is obtained via taking componentwise limits. -/ def colimit_presheaf_obj_iso_componentwise_limit (F : J ⥤ PresheafedSpace C) (U : opens (limits.colimit F).carrier) : (limits.colimit F).presheaf.obj (op U) ≅ limit (componentwise_diagram F U) := begin refine ((sheaf_iso_of_iso (colimit.iso_colimit_cocone ⟨_, colimit_cocone_is_colimit F⟩).symm).app (op U)).trans _, refine (limit_obj_iso_limit_comp_evaluation _ _).trans (limits.lim.map_iso _), fapply nat_iso.of_components, { intro X, refine ((F.obj (unop X)).presheaf.map_iso (eq_to_iso _)), dsimp only [functor.op, unop_op, opens.map], congr' 2, rw set.preimage_preimage, simp_rw ← comp_app, congr' 2, exact ι_preserves_colimits_iso_inv (forget C) F (unop X) }, { intros X Y f, change ((F.map f.unop).c.app _ ≫ _ ≫ _) ≫ (F.obj (unop Y)).presheaf.map _ = _ ≫ _, rw Top.presheaf.pushforward.comp_inv_app, erw category.id_comp, rw category.assoc, erw [← (F.obj (unop Y)).presheaf.map_comp, (F.map f.unop).c.naturality_assoc, ← (F.obj (unop Y)).presheaf.map_comp], congr } end @[simp] lemma colimit_presheaf_obj_iso_componentwise_limit_inv_ι_app (F : J ⥤ PresheafedSpace C) (U : opens (limits.colimit F).carrier) (j : J) : (colimit_presheaf_obj_iso_componentwise_limit F U).inv ≫ (colimit.ι F j).c.app (op U) = limit.π _ (op j) := begin delta colimit_presheaf_obj_iso_componentwise_limit, rw [iso.trans_inv, iso.trans_inv, iso.app_inv, sheaf_iso_of_iso_inv, pushforward_to_of_iso_app, congr_app (iso.symm_inv _)], simp_rw category.assoc, rw [← functor.map_comp_assoc, nat_trans.naturality], erw ← comp_c_app_assoc, rw congr_app (colimit.iso_colimit_cocone_ι_hom _ _), simp_rw category.assoc, erw [limit_obj_iso_limit_comp_evaluation_inv_π_app_assoc, lim_map_π_assoc], convert category.comp_id _, erw ← (F.obj j).presheaf.map_id, iterate 2 { erw ← (F.obj j).presheaf.map_comp }, congr end @[simp] lemma colimit_presheaf_obj_iso_componentwise_limit_hom_π (F : J ⥤ PresheafedSpace C) (U : opens (limits.colimit F).carrier) (j : J) : (colimit_presheaf_obj_iso_componentwise_limit F U).hom ≫ limit.π _ (op j) = (colimit.ι F j).c.app (op U) := by rw [← iso.eq_inv_comp, colimit_presheaf_obj_iso_componentwise_limit_inv_ι_app] end PresheafedSpace end algebraic_geometry
c29c7975ed7a2b36270b3e7f23a12542b792a142
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/data/string/basic.lean
379758e7b10d0806e5f2292fbb32e02e8b3f949a
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,448
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.basic import init.data.char.basic def string := list char namespace string @[pattern] def empty : string := list.nil instance : inhabited string := ⟨empty⟩ @[pattern] def str : char → string → string := list.cons def concat (a b : string) : string := list.append b a instance : has_append string := ⟨string.concat⟩ end string open list private def utf8_length_aux : nat → nat → string → nat | 0 r (c::s) := let n := char.to_nat c in if n < 0x80 then utf8_length_aux 0 (r+1) s else if 0xC0 ≤ n ∧ n < 0xE0 then utf8_length_aux 1 (r+1) s else if 0xE0 ≤ n ∧ n < 0xF0 then utf8_length_aux 2 (r+1) s else if 0xF0 ≤ n ∧ n < 0xF8 then utf8_length_aux 3 (r+1) s else if 0xF8 ≤ n ∧ n < 0xFC then utf8_length_aux 4 (r+1) s else if 0xFC ≤ n ∧ n < 0xFE then utf8_length_aux 5 (r+1) s else utf8_length_aux 0 (r+1) s | (n+1) r (c::s) := utf8_length_aux n r s | n r [] := r def utf8_length : string → nat | s := utf8_length_aux 0 0 (reverse s) private def to_nat_core : list char → nat → nat | [] r := r | (c::cs) r := to_nat_core cs (char.to_nat c - char.to_nat #"0" + r*10) def string.to_nat (s : string) : nat := to_nat_core s^.reverse 0
d529c01cb945320856f771da5fe9b0237b438467
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/field/defs.lean
b65b95b79824c910c90f5e56f0ae492cf7518c10
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,830
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.field.defs import algebra.order.ring.defs /-! # Linear ordered (semi)fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A linear ordered (semi)field is a (semi)field equipped with a linear order such that * addition respects the order: `a ≤ b → c + a ≤ c + b`; * multiplication of positives is positive: `0 < a → 0 < b → 0 < a * b`; * `0 < 1`. ## Main Definitions * `linear_ordered_semifield`: Typeclass for linear order semifields. * `linear_ordered_field`: Typeclass for linear ordered fields. ## Implementation details For olean caching reasons, this file is separate to the main file, `algebra.order.field.basic`. The lemmata are instead located there. -/ set_option old_structure_cmd true variables {α : Type*} /-- A linear ordered semifield is a field with a linear order respecting the operations. -/ @[protect_proj, ancestor linear_ordered_comm_semiring semifield] class linear_ordered_semifield (α : Type*) extends linear_ordered_comm_semiring α, semifield α /-- A linear ordered field is a field with a linear order respecting the operations. -/ @[protect_proj, ancestor linear_ordered_comm_ring field] class linear_ordered_field (α : Type*) extends linear_ordered_comm_ring α, field α @[priority 100] -- See note [lower instance priority] instance linear_ordered_field.to_linear_ordered_semifield [linear_ordered_field α] : linear_ordered_semifield α := { ..linear_ordered_ring.to_linear_ordered_semiring, ..‹linear_ordered_field α› } -- Guard against import creep. assert_not_exists monoid_hom
342f1e6091fc8ea9741134638e5ff64e2d1444d4
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/semidirect_product.lean
720c550b02df63d91af0be6aa244d8c7c06cd13c
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
9,074
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.equiv.mul_add_aut import logic.function.basic import group_theory.subgroup.basic /-! # Semidirect product This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} private def one_aux : N ⋊[φ] G := ⟨1, 1⟩ private def mul_aux (a b : N ⋊[φ] G) : N ⋊[φ] G := ⟨a.1 * φ a.2 b.1, a.right * b.right⟩ private def inv_aux (a : N ⋊[φ] G) : N ⋊[φ] G := let i := a.2⁻¹ in ⟨φ i a.1⁻¹, i⟩ private lemma mul_assoc_aux (a b c : N ⋊[φ] G) : mul_aux (mul_aux a b) c = mul_aux a (mul_aux b c) := by simp [mul_aux, mul_assoc, mul_equiv.map_mul] private lemma mul_one_aux (a : N ⋊[φ] G) : mul_aux a one_aux = a := by cases a; simp [mul_aux, one_aux] private lemma one_mul_aux (a : N ⋊[φ] G) : mul_aux one_aux a = a := by cases a; simp [mul_aux, one_aux] private lemma mul_left_inv_aux (a : N ⋊[φ] G) : mul_aux (inv_aux a) a = one_aux := by simp only [mul_aux, inv_aux, one_aux, ← mul_equiv.map_mul, mul_left_inv]; simp instance : group (N ⋊[φ] G) := { one := one_aux, inv := inv_aux, mul := mul_aux, mul_assoc := mul_assoc_aux, one_mul := one_mul_aux, mul_one := mul_one_aux, mul_left_inv := mul_left_inv_aux } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g := by rw [← monoid_hom.map_inv, inl_aut, inv_inv] @[simp] lemma mk_eq_inl_mul_inr (g : G) (n : N) : (⟨n, g⟩ : N ⋊[φ] G) = inl n * inr g := by ext; simp @[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end /-- Two maps out of the semidirect product are equal if they're equal after composition with both `inl` and `inr` -/ lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl) (hr : f.comp inr = g.comp inr) : f = g := by { rw [lift_unique f, lift_unique g], simp only * } end lift section map variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁} /-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/ def map (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ := { to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩, map_one' := by simp, map_mul' := λ x y, begin replace h := monoid_hom.ext_iff.1 (h x.right) y.left, ext; simp * at *, end } variables (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) @[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl @[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl @[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl @[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) := by simp [map] @[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ := by ext; simp @[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) := by simp [map] @[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ := by ext; simp [map] end map end semidirect_product
b0ad2aac630dcc35f7615185e3108befcecda004
17d3c61bf162bf88be633867ed4cb201378a8769
/library/init/meta/interactive.lean
6575650cf1b3b25d6e42e2933b36bad3961e5d66
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,594
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.category.combinators namespace interactive namespace types /- The parser treats constants in the tactic.interactive namespace specially. The following argument types have special parser support when interactive tactics are used inside `begin ... end` blocks. - ident : make sure the next token is an identifier, and produce the quoted name `t, where t is the next identifier. - opt_ident : parse (identifier)? - using_ident - raw_ident_list : parse identifier* and produce a list of quoted identifiers. Example: a b c produces [`a, `b, `c] - with_ident_list : parse (`with` identifier+)? and produce a list of quoted identifiers - assign_tk : parse the token `:=` and produce the unit () - colon_tk : parse the token `:` and produce the unit () - comma_tk : parse the token `,` and produce the unit () - location : parse (`at` identifier+)? and produce a list of quoted identifiers - qexpr : parse an expression e and produce the quoted expression `e - qexpr_list : parse `[` (expr (`,` expr)*)? `]` and produce a list of quoted expressions. - opt_qexpr_list : parse (`[` (expr (`,` expr)*)? `]`)? and produce a list of quoted expressions. - qexpr0 : parse an expression e using 0 as the right-binding-power, and produce the quoted expression `e - qexpr_list_or_qexpr0 : parse `[` (expr (`,` expr)*)? `]` or expr and produce a list of quoted expressions - qexpr_list_with_pos - qexpr_list_or_qexpr0_with_pos : parse `[` (expr (`,` expr)*)? `]` or expr and produce a list of quoted expressions with position information -/ def pos : Type := nat × nat def ident : Type := name def opt_ident : Type := option ident def using_ident : Type := option ident def raw_ident_list : Type := list ident def with_ident_list : Type := list ident def without_ident_list : Type := list ident def location : Type := list ident @[reducible] meta def qexpr : Type := pexpr @[reducible] meta def qexpr0 : Type := pexpr meta def qexpr_list : Type := list qexpr meta def qexpr_list_with_pos : Type := list (qexpr × pos) meta def opt_qexpr_list : Type := list qexpr meta def qexpr_list_or_qexpr0 : Type := list qexpr meta def qexpr_list_or_qexpr0_with_pos : Type := list (qexpr × pos) meta def assign_tk : Type := unit meta def colon_tk : Type := unit end types end interactive namespace tactic meta def report_resolve_name_failure {α : Type} (e : expr) (n : name) : tactic α := if e^.is_choice_macro then fail ("failed to resolve name '" ++ to_string n ++ "', it is overloaded") else fail ("failed to resolve name '" ++ to_string n ++ "', unexpected result") namespace interactive open interactive.types expr /- itactic: parse a nested "interactive" tactic. That is, parse `(` tactic `)` -/ meta def itactic : Type := tactic unit /-- This tactic applies to a goal that is either a Pi/forall or starts with a let binder. If the current goal is a Pi/forall `∀ x:T, U` (resp `let x:=t in U`) then intro puts `x:T` (resp `x:=t`) in the local context. The new subgoal target is `U`. If the goal is an arrow `T → U`, then it puts in the local context either `h:T`, and the new goal target is `U`. If the goal is neither a Pi/forall nor starting with a let definition, the tactic `intro` applies the tactic `whnf` until the tactic `intro` can be applied or the goal is not `head-reducible`. -/ meta def intro : opt_ident → tactic unit | none := intro1 >> skip | (some h) := tactic.intro h >> skip /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h_1 ... h_n` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : raw_ident_list → tactic unit | [] := tactic.intros >> skip | hs := intro_lst hs >> skip /-- The tactic `rename h₁ h₂` renames hypothesis `h₁` into `h₂` in the current local context. -/ meta def rename : ident → ident → tactic unit := tactic.rename /-- This tactic applies to any goal. The argument term is a term well-formed in the local context of the main goal. The tactic apply tries to match the current goal against the conclusion of the type of term. If it succeeds, then the tactic returns as many subgoals as the number of non-dependent premises that have not been fixed by type inference or type class resolution. The tactic `apply` uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : qexpr0) : tactic unit := to_expr q >>= tactic.apply /-- Similar to the `apply` tactic, but it also creates subgoals for dependent premises that have not been fixed by type inference or type class resolution. -/ meta def fapply (q : qexpr0) : tactic unit := to_expr q >>= tactic.fapply /-- This tactic tries to close the main goal `... |- U` using type class resolution. It succeeds if it generates a term of type `U` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic applies to any goal. It behaves like `exact` with a big difference: the user can leave some holes `_` in the term. `refine` will generate as many subgoals as there are holes in the term. Note that some holes may be implicit. The type of holes must be either synthesized by the system or declared by an explicit type ascription like (e.g., `(_ : nat → Prop)`). -/ meta def refine : qexpr0 → tactic unit := tactic.refine /-- This tactic looks in the local context for an hypothesis which type is equal to the goal target. If it is the case, the subgoal is proved. Otherwise, it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- This tactic applies to any goal. `change U` replaces the main goal target `T` with `U` providing that `U` is well-formed with respect to the main goal local context, and `T` and `U` are definitionally equal. -/ meta def change (q : qexpr0) : tactic unit := to_expr q >>= tactic.change /-- This tactic applies to any goal. It gives directly the exact proof term of the goal. Let `T` be our goal, let `p` be a term of type `U` then `exact p` succeeds iff `T` and `U` are definitionally equal. -/ meta def exact (q : qexpr0) : tactic unit := do tgt : expr ← target, to_expr_strict `((%%q : %%tgt)) >>= tactic.exact private meta def get_locals : list name → tactic (list expr) | [] := return [] | (n::ns) := do h ← get_local n, hs ← get_locals ns, return (h::hs) /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and its dependencies to the goal target. This tactic is the inverse of `intro`. -/ meta def revert (ids : raw_ident_list) : tactic unit := do hs ← get_locals ids, revert_lst hs, skip /- Return (some a) iff p is of the form (- a) -/ private meta def is_neg (p : pexpr) : option pexpr := /- Remark: we use the low-level to_raw_expr and of_raw_expr to be able to pattern match pre-terms. This is a low-level trick (aka hack). -/ match pexpr.to_raw_expr p with | (app (const c []) arg) := if c = `neg then some (pexpr.of_raw_expr arg) else none | _ := none end private meta def resolve_name' (n : name) : tactic expr := do { e ← resolve_name n, match e with | expr.const n _ := mk_const n -- create metavars for universe levels | expr.local_const _ _ _ _ := return e | _ := report_resolve_name_failure e n end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ private meta def to_expr' (p : pexpr) : tactic expr := let e := pexpr.to_raw_expr p in match e with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | _ := to_expr p end private meta def to_symm_expr_list : list (pexpr × pos) → tactic (list (bool × expr × pos)) | [] := return [] | ((p, pos)::ps) := match is_neg p with | some a := do r ← to_expr' a, rs ← to_symm_expr_list ps, return ((tt, r, pos) :: rs) | none := do r ← to_expr' p, rs ← to_symm_expr_list ps, return ((ff, r, pos) :: rs) end private meta def rw_goal : transparency → list (bool × expr × pos) → tactic unit | m [] := return () | m ((symm, e, pos)::es) := save_info pos.1 pos.2 >> rewrite_core m tt tt occurrences.all symm e >> rw_goal m es private meta def rw_hyp : transparency → list (bool × expr × pos) → name → tactic unit | m [] hname := return () | m ((symm, e, pos)::es) hname := do h ← get_local hname, save_info pos.1 pos.2, rewrite_at_core m tt tt occurrences.all symm e h, rw_hyp m es hname private meta def rw_hyps : transparency → list (bool × expr × pos) → list name → tactic unit | m es [] := return () | m es (h::hs) := rw_hyp m es h >> rw_hyps m es hs private meta def rw_core (m : transparency) (hs : qexpr_list_or_qexpr0_with_pos) (loc : location) : tactic unit := do hlist ← to_symm_expr_list hs, match loc with | [] := rw_goal m hlist >> try (reflexivity_core reducible) | hs := rw_hyps m hlist hs >> try (reflexivity_core reducible) end meta def rewrite : qexpr_list_or_qexpr0_with_pos → location → tactic unit := rw_core reducible meta def rw : qexpr_list_or_qexpr0_with_pos → location → tactic unit := rewrite /- rewrite followed by assumption -/ meta def rwa (q : qexpr_list_or_qexpr0_with_pos) (l : location) : tactic unit := rewrite q l >> try assumption meta def erewrite : qexpr_list_or_qexpr0_with_pos → location → tactic unit := rw_core semireducible meta def erw : qexpr_list_or_qexpr0_with_pos → location → tactic unit := erewrite private meta def get_type_name (e : expr) : tactic name := do e_type ← infer_type e >>= whnf, (const I ls) ← return $ get_app_fn e_type | failed, return I meta def induction (p : qexpr0) (rec_name : using_ident) (ids : with_ident_list) : tactic unit := do e ← to_expr p, match rec_name with | some n := induction_core semireducible e n ids | none := do I ← get_type_name e, induction_core semireducible e (I <.> "rec") ids end meta def cases (p : qexpr0) (ids : with_ident_list) : tactic unit := do e ← to_expr p, if e^.is_local_constant then cases_core semireducible e ids else do x ← mk_fresh_name, tactic.generalize e x <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, cases_core semireducible h ids meta def destruct (p : qexpr0) : tactic unit := to_expr p >>= tactic.destruct meta def generalize (p : qexpr) (x : ident) : tactic unit := do e ← to_expr p, tactic.generalize e x meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- This tactic applies to any goal. The contradiction tactic attempts to find in the current local context an hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction meta def repeat : itactic → tactic unit := tactic.repeat meta def try : itactic → tactic unit := tactic.try meta def solve1 : itactic → tactic unit := tactic.solve1 /-- This tactic applies to any goal. `assert h : T` adds a new hypothesis of name `h` and type `T` to the current goal and opens a new subgoal with target `T`. The new subgoal becomes the main goal. -/ meta def assert (h : ident) (c : colon_tk) (q : qexpr0) : tactic unit := do e ← to_expr_strict q, tactic.assert h e meta def define (h : ident) (c : colon_tk) (q : qexpr0) : tactic unit := do e ← to_expr_strict q, tactic.define h e /-- This tactic applies to any goal. `assertv h : T := p` adds a new hypothesis of name `h` and type `T` to the current goal if `p` a term of type `T`. -/ meta def assertv (h : ident) (c : colon_tk) (q₁ : qexpr0) (a : assign_tk) (q₂ : qexpr0) : tactic unit := do t ← to_expr_strict q₁, v ← to_expr_strict `((%%q₂ : %%t)), tactic.assertv h t v meta def definev (h : ident) (c : colon_tk) (q₁ : qexpr0) (a : assign_tk) (q₂ : qexpr0) : tactic unit := do t ← to_expr_strict q₁, v ← to_expr_strict `((%%q₂ : %%t)), tactic.definev h t v meta def note (h : ident) (a : assign_tk) (q : qexpr0) : tactic unit := do p ← to_expr_strict q, tactic.note h p meta def pose (h : ident) (a : assign_tk) (q : qexpr0) : tactic unit := do p ← to_expr_strict q, tactic.pose h p /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a meta def existsi (e : qexpr0) : tactic unit := to_expr e >>= tactic.existsi /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := tactic.constructor meta def left : tactic unit := tactic.left meta def right : tactic unit := tactic.right meta def split : tactic unit := tactic.split meta def exfalso : tactic unit := tactic.exfalso /-- The injection tactic is based on the fact that constructors of inductive datatypes are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds to new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` an `h₂` to name the new hypotheses. -/ meta def injection (q : qexpr0) (hs : with_ident_list) : tactic unit := do e ← to_expr q, tactic.injection_with e hs private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s^.add_simp n, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail ("invalid simplification lemma '" ++ to_string n ++ "' (use command 'set_option trace.simp_lemmas true' for more details)") private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (n : name) (ref : expr) : tactic simp_lemmas := do e ← resolve_name n, match e with | expr.const n _ := (do b ← is_valid_simp_lemma_cnst reducible n, guard b, save_const_type_info n ref, s^.add_simp n) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns^.length > 0), save_const_type_info n ref, add_simps s eqns) <|> report_invalid_simp_lemma n | expr.local_const _ _ _ _ := (do b ← is_valid_simp_lemma reducible e, guard b, try (save_type_info e ref), s^.add e) <|> report_invalid_simp_lemma n | _ := report_resolve_name_failure e n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (p : pexpr) : tactic simp_lemmas := let e := pexpr.to_raw_expr p in match e with | (const c []) := simp_lemmas.resolve_and_add s c e | (local_const c _ _ _) := simp_lemmas.resolve_and_add s c e | _ := do new_e ← to_expr p, s^.add new_e end private meta def simp_lemmas.append_pexprs : simp_lemmas → list pexpr → tactic simp_lemmas | s [] := return s | s (l::ls) := do new_s ← simp_lemmas.add_pexpr s l, simp_lemmas.append_pexprs new_s ls private meta def mk_simp_set (attr_names : list name) (hs : list qexpr) (ex : list name) : tactic simp_lemmas := do s₀ ← join_user_simp_lemmas attr_names, s₁ ← simp_lemmas.append_pexprs s₀ hs, return $ simp_lemmas.erase s₁ ex private meta def simp_goal (cfg : simplify_config) : simp_lemmas → tactic unit | s := do (new_target, Heq) ← target >>= simplify_core cfg s `eq, tactic.assert `Htarget new_target, swap, Ht ← get_local `Htarget, mk_eq_mpr Heq Ht >>= tactic.exact private meta def simp_hyp (cfg : simplify_config) (s : simp_lemmas) (h_name : name) : tactic unit := do h ← get_local h_name, htype ← infer_type h, (new_htype, eqpr) ← simplify_core cfg s `eq htype, tactic.assert (expr.local_pp_name h) new_htype, mk_eq_mp eqpr h >>= tactic.exact, try $ tactic.clear h private meta def simp_hyps (cfg : simplify_config) : simp_lemmas → location → tactic unit | s [] := skip | s (h::hs) := simp_hyp cfg s h >> simp_hyps s hs private meta def simp_core (cfg : simplify_config) (ctx : list expr) (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) (loc : location) : tactic unit := do s ← mk_simp_set attr_names hs ids, s ← s^.append ctx, match loc : _ → tactic unit with | [] := simp_goal cfg s | _ := simp_hyps cfg s loc end, try tactic.triv, try (tactic.reflexivity_core reducible) /-- This tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. - `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. - `simp [h_1, ..., h_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h_i`s. The `h_i`'s are terms. If a `h_i` is a definition `f`, then the equational lemmas associated with `f` are used. This is a convenient way to "unfold" `f`. - `simp without id_1 ... id_n` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id_i`s. - `simp at h` simplifies the non dependent hypothesis `h : T`. The tactic fails if the target or another hypothesis depends on `h`. - `simp with attr` simplifies the main goal target using the lemmas tagged with the attribute `[attr]`. -/ meta def simp (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) (loc : location) : tactic unit := simp_core {} [] hs attr_names ids loc /-- Similar to the `simp` tactic, but uses contextual simplification. For example, when simplifying `t = s → p`, the equation `t = s` is automatically added to the set of simplification rules when simplifying `p`. -/ meta def ctx_simp (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) (loc : location) : tactic unit := simp_core {contextual := tt} [] hs attr_names ids loc /-- Similar to the `simp` tactic, but adds all applicable hypotheses as simplification rules. -/ meta def simp_using_hs (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) : tactic unit := do ctx ← collect_ctx_simps, simp_core {} ctx hs attr_names ids [] private meta def dsimp_hyps (s : simp_lemmas) : location → tactic unit | [] := skip | (h::hs) := get_local h >>= dsimp_at_core s meta def dsimp (es : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) : location → tactic unit | [] := do s ← mk_simp_set attr_names es ids, tactic.dsimp_core s | hs := do s ← mk_simp_set attr_names es ids, dsimp_hyps s hs /-- This tactic applies to a goal that has the form `t ~ u` where `~` is a reflexive relation. That is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity meta def symmetry : tactic unit := tactic.symmetry meta def transitivity : tactic unit := tactic.transitivity meta def ac_reflexivity : tactic unit := tactic.ac_refl meta def ac_refl : tactic unit := tactic.ac_refl meta def cc : tactic unit := tactic.cc meta def subst (q : qexpr0) : tactic unit := to_expr q >>= tactic.subst >> try (reflexivity_core reducible) meta def clear : raw_ident_list → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env^.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env^.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) private meta def dunfold_hyps : list name → location → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= dunfold_at cs >> dunfold_hyps cs hs meta def dunfold : raw_ident_list → location → tactic unit | cs [] := do new_cs ← to_qualified_names cs, tactic.dunfold new_cs | cs hs := do new_cs ← to_qualified_names cs, dunfold_hyps new_cs hs /- TODO(Leo): add support for non-refl lemmas -/ meta def unfold : raw_ident_list → location → tactic unit := dunfold private meta def dunfold_hyps_occs : name → occurrences → location → tactic unit | c occs [] := skip | c occs (h::hs) := get_local h >>= dunfold_core_at occs [c] >> dunfold_hyps_occs c occs hs meta def dunfold_occs : ident → list nat → location → tactic unit | c ps [] := do new_c ← to_qualified_name c, tactic.dunfold_occs_of ps new_c | c ps hs := do new_c ← to_qualified_name c, dunfold_hyps_occs new_c (occurrences.pos ps) hs /- TODO(Leo): add support for non-refl lemmas -/ meta def unfold_occs : ident → list nat → location → tactic unit := dunfold_occs private meta def delta_hyps : list name → location → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_at cs >> dunfold_hyps cs hs meta def delta : raw_ident_list → location → tactic unit | cs [] := do new_cs ← to_qualified_names cs, tactic.delta new_cs | cs hs := do new_cs ← to_qualified_names cs, delta_hyps new_cs hs end interactive end tactic
aa26d2adfa8ced78e9adfef0864d729729e8bd26
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/homotopy/cylinder.hlean
ee71c918ff1734cf8a4a10e0526a3b4e92493b6a
[ "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
4,775
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 Declaration of mapping cylinders -/ import hit.quotient open quotient eq sum equiv fiber namespace cylinder section parameters {A B : Type} (f : A → B) local abbreviation C := B + A inductive cylinder_rel : C → C → Type := | Rmk : Π(a : A), cylinder_rel (inl (f a)) (inr a) open cylinder_rel local abbreviation R := cylinder_rel definition cylinder := quotient cylinder_rel -- TODO: define this in root namespace parameter {f} definition base (b : B) : cylinder := class_of R (inl b) definition top (a : A) : cylinder := class_of R (inr a) definition seg (a : A) : base (f a) = top a := eq_of_rel cylinder_rel (Rmk f a) protected definition rec {P : cylinder → Type} (Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a)) (Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) (x : cylinder) : P x := begin induction x, { cases a, apply Pbase, apply Ptop}, { cases H, apply Pseg} end protected definition rec_on [reducible] {P : cylinder → Type} (x : cylinder) (Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a)) (Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) : P x := rec Pbase Ptop Pseg x theorem rec_seg {P : cylinder → Type} (Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a)) (Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) (a : A) : apd (rec Pbase Ptop Pseg) (seg a) = Pseg a := !rec_eq_of_rel protected definition elim {P : Type} (Pbase : B → P) (Ptop : A → P) (Pseg : Π(a : A), Pbase (f a) = Ptop a) (x : cylinder) : P := rec Pbase Ptop (λa, pathover_of_eq _ (Pseg a)) x protected definition elim_on [reducible] {P : Type} (x : cylinder) (Pbase : B → P) (Ptop : A → P) (Pseg : Π(a : A), Pbase (f a) = Ptop a) : P := elim Pbase Ptop Pseg x theorem elim_seg {P : Type} (Pbase : B → P) (Ptop : A → P) (Pseg : Π(a : A), Pbase (f a) = Ptop a) (a : A) : ap (elim Pbase Ptop Pseg) (seg a) = Pseg a := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (seg a)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_seg], end protected definition elim_type (Pbase : B → Type) (Ptop : A → Type) (Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) (x : cylinder) : Type := elim Pbase Ptop (λa, ua (Pseg a)) x protected definition elim_type_on [reducible] (x : cylinder) (Pbase : B → Type) (Ptop : A → Type) (Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) : Type := elim_type Pbase Ptop Pseg x theorem elim_type_seg (Pbase : B → Type) (Ptop : A → Type) (Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) (a : A) : transport (elim_type Pbase Ptop Pseg) (seg a) = Pseg a := by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_seg];apply cast_ua_fn end end cylinder attribute cylinder.base cylinder.top [constructor] attribute cylinder.rec cylinder.elim [unfold 8] [recursor 8] attribute cylinder.elim_type [unfold 7] attribute cylinder.rec_on cylinder.elim_on [unfold 5] attribute cylinder.elim_type_on [unfold 4] namespace cylinder open sigma sigma.ops variables {A B : Type} (f : A → B) /- cylinder as a dependent family -/ definition pr1 [unfold 4] : cylinder f → B := cylinder.elim id f (λa, idp) definition fcylinder : B → Type := fiber (pr1 f) definition cylinder_equiv_sigma_fcylinder [constructor] : cylinder f ≃ Σb, fcylinder f b := !sigma_fiber_equiv⁻¹ᵉ variable {f} definition fbase (b : B) : fcylinder f b := fiber.mk (base b) idp definition ftop (a : A) : fcylinder f (f a) := fiber.mk (top a) idp definition fseg (a : A) : fbase (f a) = ftop a := fiber_eq (seg a) !elim_seg⁻¹ -- TODO: define the induction principle for "fcylinder" -- set_option pp.notation false -- -- The induction principle for the dependent mapping cylinder (TODO) -- protected definition frec {P : Π(b), fcylinder f b → Type} -- (Pbase : Π(b : B), P _ (fbase b)) (Ptop : Π(a : A), P _ (ftop a)) -- (Pseg : Π(a : A), Pbase (f a) =[fseg a] Ptop a) {b : B} (x : fcylinder f b) : P _ x := -- begin -- cases x with x p, induction p, -- induction x: esimp, -- { apply Pbase}, -- { apply Ptop}, -- { esimp, --fapply fiber_pathover, -- --refine pathover_of_pathover_ap P (λx, fiber.mk x idp), -- exact sorry} -- end -- theorem frec_fseg {P : Π(b), fcylinder f b → Type} -- (Pbase : Π(b : B), P _ (fbase b)) (Ptop : Π(a : A), P _ (ftop a)) -- (Pseg : Π(a : A), Pbase (f a) =[fseg a] Ptop a) (a : A) -- : apd (cylinder.frec Pbase Ptop Pseg) (fseg a) = Pseg a := -- sorry end cylinder
d7e619a949ad9c67352cba264257c8e49cc58e3b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/field_simp.lean
2e40657346d59a90c6de39e89fc064366848c4ec
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,400
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.interactive import Mathlib.tactic.norm_num import Mathlib.PostPort namespace Mathlib /-! # `field_simp` tactic Tactic to clear denominators in algebraic expressions, based on `simp` with a specific simpset. -/ namespace tactic /-- Try to prove a goal of the form `x ≠ 0` by calling `assumption`, or `norm_num1` if `x` is a numeral. -/ namespace interactive /-- The goal of `field_simp` is to reduce an expression in a field to an expression of the form `n / d` where neither `n` nor `d` contains any division symbol, just using the simplifier (with a carefully crafted simpset named `field_simps`) to reduce the number of division symbols whenever possible by iterating the following steps: - write an inverse as a division - in any product, move the division to the right - if there are several divisions in a product, group them together at the end and write them as a single division - reduce a sum to a common denominator If the goal is an equality, this simpset will also clear the denominators, so that the proof can normally be concluded by an application of `ring` or `ring_exp`. `field_simp [hx, hy]` is a short form for `simp [-one_div, -mul_eq_zero, hx, hy] with field_simps {discharger := [field_simp.ne_zero]}` Note that this naive algorithm will not try to detect common factors in denominators to reduce the complexity of the resulting expression. Instead, it relies on the ability of `ring` to handle complicated expressions in the next step. As always with the simplifier, reduction steps will only be applied if the preconditions of the lemmas can be checked. This means that proofs that denominators are nonzero should be included. The fact that a product is nonzero when all factors are, and that a power of a nonzero number is nonzero, are included in the simpset, but more complicated assertions (especially dealing with sums) should be given explicitly. If your expression is not completely reduced by the simplifier invocation, check the denominators of the resulting expression and provide proofs that they are nonzero to enable further progress. To check that denominators are nonzero, `field_simp` will look for facts in the context, and will try to apply `norm_num` to close numerical goals. The invocation of `field_simp` removes the lemma `one_div` from the simpset, as this lemma works against the algorithm explained above. It also removes `mul_eq_zero : x * y = 0 ↔ x = 0 ∨ y = 0`, as `norm_num` can not work on disjunctions to close goals of the form `24 ≠ 0`, and replaces it with `mul_ne_zero : x ≠ 0 → y ≠ 0 → x * y ≠ 0` creating two goals instead of a disjunction. For example, ```lean example (a b c d x y : ℂ) (hx : x ≠ 0) (hy : y ≠ 0) : a + b / x + c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x + c) / x) := begin field_simp, ring end ``` See also the `cancel_denoms` tactic, which tries to do a similar simplification for expressions that have numerals in denominators. The tactics are not related: `cancel_denoms` will only handle numeric denominators, and will try to entirely remove (numeric) division from the expression by multiplying by a factor. -/
c083059f12e4e55fbf7ad6c6ed9e0e431e779b79
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/algebra/module/locally_convex.lean
3f2133b60152f778dc0231aae717d4ddac5953ba
[ "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
6,909
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.convex.topology /-! # Locally convex topological modules A `locally_convex_space` is a topological semimodule over an ordered semiring in which any point admits a neighborhood basis made of convex sets, or equivalently, in which convex neighborhoods of a point form a neighborhood basis at that point. In a module, this is equivalent to `0` satisfying such properties. ## Main results - `locally_convex_space_iff_zero` : in a module, local convexity at zero gives local convexity everywhere - `seminorm.locally_convex_space` : a topology generated by a family of seminorms is locally convex - `normed_space.locally_convex_space` : a normed space is locally convex ## TODO - define a structure `locally_convex_filter_basis`, extending `module_filter_basis`, for filter bases generating a locally convex topology - show that any locally convex topology is generated by a family of seminorms -/ open topological_space filter set open_locale topological_space section semimodule /-- A `locally_convex_space` is a topological semimodule over an ordered semiring in which convex neighborhoods of a point form a neighborhood basis at that point. -/ class locally_convex_space (𝕜 E : Type*) [ordered_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] [topological_space E] : Prop := (convex_basis : ∀ x : E, (𝓝 x).has_basis (λ (s : set E), s ∈ 𝓝 x ∧ convex 𝕜 s) id) variables (𝕜 E : Type*) [ordered_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] [topological_space E] lemma locally_convex_space_iff : locally_convex_space 𝕜 E ↔ ∀ x : E, (𝓝 x).has_basis (λ (s : set E), s ∈ 𝓝 x ∧ convex 𝕜 s) id := ⟨@locally_convex_space.convex_basis _ _ _ _ _ _, locally_convex_space.mk⟩ lemma locally_convex_space.of_bases {ι : Type*} (b : E → ι → set E) (p : E → ι → Prop) (hbasis : ∀ x : E, (𝓝 x).has_basis (p x) (b x)) (hconvex : ∀ x i, p x i → convex 𝕜 (b x i)) : locally_convex_space 𝕜 E := ⟨λ x, (hbasis x).to_has_basis (λ i hi, ⟨b x i, ⟨⟨(hbasis x).mem_of_mem hi, hconvex x i hi⟩, le_refl (b x i)⟩⟩) (λ s hs, ⟨(hbasis x).index s hs.1, ⟨(hbasis x).property_index hs.1, (hbasis x).set_index_subset hs.1⟩⟩)⟩ lemma locally_convex_space.convex_basis_zero [locally_convex_space 𝕜 E] : (𝓝 0 : filter E).has_basis (λ s, s ∈ (𝓝 0 : filter E) ∧ convex 𝕜 s) id := locally_convex_space.convex_basis 0 lemma locally_convex_space_iff_exists_convex_subset : locally_convex_space 𝕜 E ↔ ∀ x : E, ∀ U ∈ 𝓝 x, ∃ S ∈ 𝓝 x, convex 𝕜 S ∧ S ⊆ U := (locally_convex_space_iff 𝕜 E).trans (forall_congr $ λ x, has_basis_self) end semimodule section module variables (𝕜 E : Type*) [ordered_semiring 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] lemma locally_convex_space.of_basis_zero {ι : Type*} (b : ι → set E) (p : ι → Prop) (hbasis : (𝓝 0).has_basis p b) (hconvex : ∀ i, p i → convex 𝕜 (b i)) : locally_convex_space 𝕜 E := begin refine locally_convex_space.of_bases 𝕜 E (λ (x : E) (i : ι), ((+) x) '' b i) (λ _, p) (λ x, _) (λ x i hi, (hconvex i hi).translate x), rw ← map_add_left_nhds_zero, exact hbasis.map _ end lemma locally_convex_space_iff_zero : locally_convex_space 𝕜 E ↔ (𝓝 0 : filter E).has_basis (λ (s : set E), s ∈ (𝓝 0 : filter E) ∧ convex 𝕜 s) id := ⟨λ h, @locally_convex_space.convex_basis _ _ _ _ _ _ h 0, λ h, locally_convex_space.of_basis_zero 𝕜 E _ _ h (λ s, and.right)⟩ lemma locally_convex_space_iff_exists_convex_subset_zero : locally_convex_space 𝕜 E ↔ ∀ U ∈ (𝓝 0 : filter E), ∃ S ∈ (𝓝 0 : filter E), convex 𝕜 S ∧ S ⊆ U := (locally_convex_space_iff_zero 𝕜 E).trans has_basis_self -- see Note [lower instance priority] @[priority 100] instance locally_convex_space.to_locally_connected_space [module ℝ E] [has_continuous_smul ℝ E] [locally_convex_space ℝ E] : locally_connected_space E := locally_connected_space_of_connected_bases _ _ (λ x, @locally_convex_space.convex_basis ℝ _ _ _ _ _ _ x) (λ x s hs, hs.2.is_preconnected) end module section lattice_ops variables {ι : Sort*} {𝕜 E F : Type*} [ordered_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] [add_comm_monoid F] [module 𝕜 F] lemma locally_convex_space_Inf {ts : set (topological_space E)} (h : ∀ t ∈ ts, @locally_convex_space 𝕜 E _ _ _ t) : @locally_convex_space 𝕜 E _ _ _ (Inf ts) := begin letI : topological_space E := Inf ts, refine locally_convex_space.of_bases 𝕜 E (λ x, λ If : set ts × (ts → set E), ⋂ i ∈ If.1, If.2 i) (λ x, λ If : set ts × (ts → set E), If.1.finite ∧ ∀ i ∈ If.1, ((If.2 i) ∈ @nhds _ ↑i x ∧ convex 𝕜 (If.2 i))) (λ x, _) (λ x If hif, convex_Inter $ λ i, convex_Inter $ λ hi, (hif.2 i hi).2), rw [nhds_Inf, ← infi_subtype''], exact has_basis_infi' (λ i : ts, (@locally_convex_space_iff 𝕜 E _ _ _ ↑i).mp (h ↑i i.2) x), end lemma locally_convex_space_infi {ts' : ι → topological_space E} (h' : ∀ i, @locally_convex_space 𝕜 E _ _ _ (ts' i)) : @locally_convex_space 𝕜 E _ _ _ (⨅ i, ts' i) := begin refine locally_convex_space_Inf _, rwa forall_range_iff end lemma locally_convex_space_inf {t₁ t₂ : topological_space E} (h₁ : @locally_convex_space 𝕜 E _ _ _ t₁) (h₂ : @locally_convex_space 𝕜 E _ _ _ t₂) : @locally_convex_space 𝕜 E _ _ _ (t₁ ⊓ t₂) := by {rw inf_eq_infi, refine locally_convex_space_infi (λ b, _), cases b; assumption} lemma locally_convex_space_induced {t : topological_space F} [locally_convex_space 𝕜 F] (f : E →ₗ[𝕜] F) : @locally_convex_space 𝕜 E _ _ _ (t.induced f) := begin letI : topological_space E := t.induced f, refine locally_convex_space.of_bases 𝕜 E (λ x, preimage f) (λ x, λ (s : set F), s ∈ 𝓝 (f x) ∧ convex 𝕜 s) (λ x, _) (λ x s ⟨_, hs⟩, hs.linear_preimage f), rw nhds_induced, exact (locally_convex_space.convex_basis $ f x).comap f end instance {ι : Type*} {X : ι → Type*} [Π i, add_comm_monoid (X i)] [Π i, topological_space (X i)] [Π i, module 𝕜 (X i)] [Π i, locally_convex_space 𝕜 (X i)] : locally_convex_space 𝕜 (Π i, X i) := locally_convex_space_infi (λ i, locally_convex_space_induced (linear_map.proj i)) instance [topological_space E] [topological_space F] [locally_convex_space 𝕜 E] [locally_convex_space 𝕜 F] : locally_convex_space 𝕜 (E × F) := locally_convex_space_inf (locally_convex_space_induced (linear_map.fst _ _ _)) (locally_convex_space_induced (linear_map.snd _ _ _)) end lattice_ops
622913f57832ffc6fbb7576fd5e074f6526724b6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/calculus/fderiv_symmetric.lean
41b99929f84cc926b4d4dd6d342b2a86235fca95
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
19,022
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv import analysis.calculus.mean_value import analysis.convex.topology /-! # Symmetry of the second derivative We show that, over the reals, the second derivative is symmetric. The most precise result is `convex.second_derivative_within_at_symmetric`. It asserts that, if a function is differentiable inside a convex set `s` with nonempty interior, and has a second derivative within `s` at a point `x`, then this second derivative at `x` is symmetric. Note that this result does not require continuity of the first derivative. The following particular cases of this statement are especially relevant: `second_derivative_symmetric_of_eventually` asserts that, if a function is differentiable on a neighborhood of `x`, and has a second derivative at `x`, then this second derivative is symmetric. `second_derivative_symmetric` asserts that, if a function is differentiable, and has a second derivative at `x`, then this second derivative is symmetric. ## Implementation note For the proof, we obtain an asymptotic expansion to order two of `f (x + v + w) - f (x + v)`, by using the mean value inequality applied to a suitable function along the segment `[x + v, x + v + w]`. This expansion involves `f'' ⬝ w` as we move along a segment directed by `w` (see `convex.taylor_approx_two_segment`). Consider the alternate sum `f (x + v + w) + f x - f (x + v) - f (x + w)`, corresponding to the values of `f` along a rectangle based at `x` with sides `v` and `w`. One can write it using the two sides directed by `w`, as `(f (x + v + w) - f (x + v)) - (f (x + w) - f x)`. Together with the previous asymptotic expansion, one deduces that it equals `f'' v w + o(1)` when `v, w` tends to `0`. Exchanging the roles of `v` and `w`, one instead gets an asymptotic expansion `f'' w v`, from which the equality `f'' v w = f'' w v` follows. In our most general statement, we only assume that `f` is differentiable inside a convex set `s`, so a few modifications have to be made. Since we don't assume continuity of `f` at `x`, we consider instead the rectangle based at `x + v + w` with sides `v` and `w`, in `convex.is_o_alternate_sum_square`, but the argument is essentially the same. It only works when `v` and `w` both point towards the interior of `s`, to make sure that all the sides of the rectangle are contained in `s` by convexity. The general case follows by linearity, though. -/ open asymptotics set open_locale topological_space variables {E F : Type*} [normed_add_comm_group E] [normed_space ℝ E] [normed_add_comm_group F] [normed_space ℝ F] {s : set E} (s_conv : convex ℝ s) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) include s_conv xs hx hf /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one can Taylor-expand to order two the function `f` on the segment `[x + h v, x + h (v + w)]`, giving a bilinear estimate for `f (x + hv + hw) - f (x + hv)` in terms of `f' w` and of `f'' ⬝ w`, up to `o(h^2)`. This is a technical statement used to show that the second derivative is symmetric. -/ lemma convex.taylor_approx_two_segment {v w : E} (hv : x + v ∈ interior s) (hw : x + v + w ∈ interior s) : (λ h : ℝ, f (x + h • v + h • w) - f (x + h • v) - h • f' x w - h^2 • f'' v w - (h^2/2) • f'' w w) =o[𝓝[>] 0] (λ h, h^2) := begin -- it suffices to check that the expression is bounded by `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2` for -- small enough `h`, for any positive `ε`. apply is_o.trans_is_O (is_o_iff.2 (λ ε εpos, _)) (is_O_const_mul_self ((∥v∥ + ∥w∥) * ∥w∥) _ _), -- consider a ball of radius `δ` around `x` in which the Taylor approximation for `f''` is -- good up to `δ`. rw [has_fderiv_within_at, has_fderiv_at_filter, is_o_iff] at hx, rcases metric.mem_nhds_within_iff.1 (hx εpos) with ⟨δ, δpos, sδ⟩, have E1 : ∀ᶠ h in 𝓝[>] (0:ℝ), h * (∥v∥ + ∥w∥) < δ, { have : filter.tendsto (λ h, h * (∥v∥ + ∥w∥)) (𝓝[>] (0:ℝ)) (𝓝 (0 * (∥v∥ + ∥w∥))) := (continuous_id.mul continuous_const).continuous_within_at, apply (tendsto_order.1 this).2 δ, simpa only [zero_mul] using δpos }, have E2 : ∀ᶠ h in 𝓝[>] (0:ℝ), (h : ℝ) < 1 := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(1 : ℝ), by simp only [mem_Ioi, zero_lt_one], λ x hx, hx.2⟩, filter_upwards [E1, E2, self_mem_nhds_within] with h hδ h_lt_1 hpos, -- we consider `h` small enough that all points under consideration belong to this ball, -- and also with `0 < h < 1`. replace hpos : 0 < h := hpos, have xt_mem : ∀ t ∈ Icc (0 : ℝ) 1, x + h • v + (t * h) • w ∈ interior s, { assume t ht, have : x + h • v ∈ interior s := s_conv.add_smul_mem_interior xs hv ⟨hpos, h_lt_1.le⟩, rw [← smul_smul], apply s_conv.interior.add_smul_mem this _ ht, rw add_assoc at hw, rw [add_assoc, ← smul_add], exact s_conv.add_smul_mem_interior xs hw ⟨hpos, h_lt_1.le⟩ }, -- define a function `g` on `[0,1]` (identified with `[v, v + w]`) such that `g 1 - g 0` is the -- quantity to be estimated. We will check that its derivative is given by an explicit -- expression `g'`, that we can bound. Then the desired bound for `g 1 - g 0` follows from the -- mean value inequality. let g := λ t, f (x + h • v + (t * h) • w) - (t * h) • f' x w - (t * h^2) • f'' v w - ((t * h)^2/2) • f'' w w, set g' := λ t, f' (x + h • v + (t * h) • w) (h • w) - h • f' x w - h^2 • f'' v w - (t * h^2) • f'' w w with hg', -- check that `g'` is the derivative of `g`, by a straightforward computation have g_deriv : ∀ t ∈ Icc (0 : ℝ) 1, has_deriv_within_at g (g' t) (Icc 0 1) t, { assume t ht, apply_rules [has_deriv_within_at.sub, has_deriv_within_at.add], { refine (hf _ _).comp_has_deriv_within_at _ _, { exact xt_mem t ht }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.const_add, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { suffices H : has_deriv_within_at (λ u, ((u * h) ^ 2 / 2) • f'' w w) (((((2 : ℕ) : ℝ) * (t * h) ^ (2 - 1) * (1 * h))/2) • f'' w w) (Icc 0 1) t, { convert H using 2, simp only [one_mul, nat.cast_bit0, pow_one, nat.cast_one], ring }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_id', has_deriv_at.pow, has_deriv_at.mul_const] } }, -- check that `g'` is uniformly bounded, with a suitable bound `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2`. have g'_bound : ∀ t ∈ Ico (0 : ℝ) 1, ∥g' t∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2, { assume t ht, have I : ∥h • v + (t * h) • w∥ ≤ h * (∥v∥ + ∥w∥) := calc ∥h • v + (t * h) • w∥ ≤ ∥h • v∥ + ∥(t * h) • w∥ : norm_add_le _ _ ... = h * ∥v∥ + t * (h * ∥w∥) : by simp only [norm_smul, real.norm_eq_abs, hpos.le, abs_of_nonneg, abs_mul, ht.left, mul_assoc] ... ≤ h * ∥v∥ + 1 * (h * ∥w∥) : add_le_add le_rfl (mul_le_mul_of_nonneg_right ht.2.le (mul_nonneg hpos.le (norm_nonneg _))) ... = h * (∥v∥ + ∥w∥) : by ring, calc ∥g' t∥ = ∥(f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)) (h • w)∥ : begin rw hg', have : h * (t * h) = t * (h * h), by ring, simp only [continuous_linear_map.coe_sub', continuous_linear_map.map_add, pow_two, continuous_linear_map.add_apply, pi.smul_apply, smul_sub, smul_add, smul_smul, ← sub_sub, continuous_linear_map.coe_smul', pi.sub_apply, continuous_linear_map.map_smul, this] end ... ≤ ∥f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)∥ * ∥h • w∥ : continuous_linear_map.le_op_norm _ _ ... ≤ (ε * ∥h • v + (t * h) • w∥) * (∥h • w∥) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), have H : x + h • v + (t * h) • w ∈ metric.ball x δ ∩ interior s, { refine ⟨_, xt_mem t ⟨ht.1, ht.2.le⟩⟩, rw [add_assoc, add_mem_ball_iff_norm], exact I.trans_lt hδ }, simpa only [mem_set_of_eq, add_assoc x, add_sub_cancel'] using sδ H, end ... ≤ (ε * (∥h • v∥ + ∥h • w∥)) * (∥h • w∥) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), apply mul_le_mul_of_nonneg_left _ (εpos.le), apply (norm_add_le _ _).trans, refine add_le_add le_rfl _, simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, ht.1, hpos.le, mul_assoc], exact mul_le_of_le_one_left (mul_nonneg hpos.le (norm_nonneg _)) ht.2.le, end ... = ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2 : by { simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, hpos.le], ring } }, -- conclude using the mean value inequality have I : ∥g 1 - g 0∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2, by simpa only [mul_one, sub_zero] using norm_image_sub_le_of_norm_deriv_le_segment' g_deriv g'_bound 1 (right_mem_Icc.2 zero_le_one), convert I using 1, { congr' 1, dsimp only [g], simp only [nat.one_ne_zero, add_zero, one_mul, zero_div, zero_mul, sub_zero, zero_smul, ne.def, not_false_iff, bit0_eq_zero, zero_pow'], abel }, { simp only [real.norm_eq_abs, abs_mul, add_nonneg (norm_nonneg v) (norm_nonneg w), abs_of_nonneg, mul_assoc, pow_bit0_abs, norm_nonneg, abs_pow] } end /-- One can get `f'' v w` as the limit of `h ^ (-2)` times the alternate sum of the values of `f` along the vertices of a quadrilateral with sides `h v` and `h w` based at `x`. In a setting where `f` is not guaranteed to be continuous at `f`, we can still get this if we use a quadrilateral based at `h v + h w`. -/ lemma convex.is_o_alternate_sum_square {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : (λ h : ℝ, f (x + h • (2 • v + 2 • w)) + f (x + h • (v + w)) - f (x + h • (2 • v + w)) - f (x + h • (v + 2 • w)) - h^2 • f'' v w) =o[𝓝[>] 0] (λ h, h^2) := begin have A : (1 : ℝ)/2 ∈ Ioc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have B : (1 : ℝ)/2 ∈ Icc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have C : ∀ (w : E), (2 : ℝ) • w = 2 • w := λ w, by simp only [two_smul], have h2v2w : x + (2 : ℝ) • v + (2 : ℝ) • w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h4v h4w B using 1, simp only [smul_sub, smul_smul, one_div, add_sub_add_left_eq_sub, mul_add, add_smul], norm_num, simp only [show (4 : ℝ) = (2 : ℝ) + (2 : ℝ), by norm_num, add_smul], abel }, have h2vww : x + (2 • v + w) + w ∈ interior s, { convert h2v2w using 1, simp only [two_smul], abel }, have h2v : x + (2 : ℝ) • v ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4v A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have h2w : x + (2 : ℝ) • w ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have hvw : x + (v + w) ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h2v2w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj, smul_add, smul_sub], norm_num, abel }, have h2vw : x + (2 • v + w) ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2v h2v2w B using 1, simp only [smul_add, smul_sub, smul_smul, ← C], norm_num, abel }, have hvww : x + (v + w) + w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2w h2v2w B using 1, simp only [one_div, add_sub_cancel', inv_smul_smul₀, add_sub_add_right_eq_sub, ne.def, not_false_iff, bit0_eq_zero, one_ne_zero], rw two_smul, abel }, have TA1 := s_conv.taylor_approx_two_segment hf xs hx h2vw h2vww, have TA2 := s_conv.taylor_approx_two_segment hf xs hx hvw hvww, convert TA1.sub TA2, ext h, simp only [two_smul, smul_add, ← add_assoc, continuous_linear_map.map_add, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', continuous_linear_map.map_smul], abel, end /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one has `f'' v w = f'' w v`. Superseded by `convex.second_derivative_within_at_symmetric`, which removes the assumption that `v` and `w` point inside `s`. -/ lemma convex.second_derivative_within_at_symmetric_of_mem_interior {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : f'' w v = f'' v w := begin have A : (λ h : ℝ, h^2 • (f'' w v- f'' v w)) =o[𝓝[>] 0] (λ h, h^2), { convert (s_conv.is_o_alternate_sum_square hf xs hx h4v h4w).sub (s_conv.is_o_alternate_sum_square hf xs hx h4w h4v), ext h, simp only [add_comm, smul_add, smul_sub], abel }, have B : (λ h : ℝ, f'' w v - f'' v w) =o[𝓝[>] 0] (λ h, (1 : ℝ)), { have : (λ h : ℝ, 1/h^2) =O[𝓝[>] 0] (λ h, 1/h^2) := is_O_refl _ _, have C := this.smul_is_o A, apply C.congr' _ _, { filter_upwards [self_mem_nhds_within], assume h hpos, rw [← one_smul ℝ (f'' w v - f'' v w), smul_smul, smul_smul], congr' 1, field_simp [has_lt.lt.ne' hpos] }, { filter_upwards [self_mem_nhds_within] with _ hpos, field_simp [has_lt.lt.ne' hpos, has_smul.smul], }, }, simpa only [sub_eq_zero] using is_o_const_const_iff.1 B, end omit s_conv xs hx hf /-- If a function is differentiable inside a convex set with nonempty interior, and has a second derivative at a point of this convex set, then this second derivative is symmetric. -/ theorem convex.second_derivative_within_at_symmetric {s : set E} (s_conv : convex ℝ s) (hne : (interior s).nonempty) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) (v w : E) : f'' v w = f'' w v := begin /- we work around a point `x + 4 z` in the interior of `s`. For any vector `m`, then `x + 4 (z + t m)` also belongs to the interior of `s` for small enough `t`. This means that we will be able to apply `second_derivative_within_at_symmetric_of_mem_interior` to show that `f''` is symmetric, after cancelling all the contributions due to `z`. -/ rcases hne with ⟨y, hy⟩, obtain ⟨z, hz⟩ : ∃ z, z = ((1:ℝ) / 4) • (y - x) := ⟨((1:ℝ) / 4) • (y - x), rfl⟩, have A : ∀ (m : E), filter.tendsto (λ (t : ℝ), x + (4 : ℝ) • (z + t • m)) (𝓝 0) (𝓝 y), { assume m, have : x + (4 : ℝ) • (z + (0 : ℝ) • m) = y, by simp [hz], rw ← this, refine tendsto_const_nhds.add _, refine tendsto_const_nhds.smul _, refine tendsto_const_nhds.add _, exact continuous_at_id.smul continuous_at_const }, have B : ∀ (m : E), ∀ᶠ t in 𝓝[>] (0 : ℝ), x + (4 : ℝ) • (z + t • m) ∈ interior s, { assume m, apply nhds_within_le_nhds, apply A m, rw [mem_interior_iff_mem_nhds] at hy, exact interior_mem_nhds.2 hy }, -- we choose `t m > 0` such that `x + 4 (z + (t m) m)` belongs to the interior of `s`, for any -- vector `m`. choose t ts tpos using λ m, ((B m).and self_mem_nhds_within).exists, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z` -- and `z + (t m) m`, we deduce that `f'' m z = f'' z m` for all `m`. have C : ∀ (m : E), f'' m z = f'' z m, { assume m, have : f'' (z + t m • m) (z + t 0 • 0) = f'' (z + t 0 • 0) (z + t m • m) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts 0) (ts m), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, add_right_inj, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', add_zero, continuous_linear_map.zero_apply, smul_zero, continuous_linear_map.map_zero] at this, exact smul_right_injective F (tpos m).ne' this }, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z + (t v) v` -- and `z + (t w) w`, we deduce that `f'' v w = f'' w v`. Cross terms involving `z` can be -- eliminated thanks to the fact proved above that `f'' m z = f'' z m`. have : f'' (z + t v • v) (z + t w • w) = f'' (z + t w • w) (z + t v • v) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts w) (ts v), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, smul_add, smul_smul, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', C] at this, rw ← sub_eq_zero at this, abel at this, simp only [one_zsmul, neg_smul, sub_eq_zero, mul_comm, ← sub_eq_add_neg] at this, apply smul_right_injective F _ this, simp [(tpos v).ne', (tpos w).ne'] end /-- If a function is differentiable around `x`, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric_of_eventually {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := begin rcases metric.mem_nhds_iff.1 hf with ⟨ε, εpos, hε⟩, have A : (interior (metric.ball x ε)).nonempty, by rwa [metric.is_open_ball.interior_eq, metric.nonempty_ball], exact convex.second_derivative_within_at_symmetric (convex_ball x ε) A (λ y hy, hε (interior_subset hy)) (metric.mem_ball_self εpos) hx.has_fderiv_within_at v w, end /-- If a function is differentiable, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ y, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := second_derivative_symmetric_of_eventually (filter.eventually_of_forall hf) hx v w
abbfe2775c7f375d41b2ece7909f4925ed94b954
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/hom_functor.lean
f2ebc0b66a4cfb66cd3f3b21acd707b2d1bb7d7f
[]
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,184
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.products.basic import Mathlib.PostPort universes u v namespace Mathlib /-! The hom functor, sending `(X, Y)` to the type `X ⟶ Y`. -/ namespace category_theory.functor /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ def hom (C : Type u) [category C] : Cᵒᵖ × C ⥤ Type v := mk (fun (p : Cᵒᵖ × C) => opposite.unop (prod.fst p) ⟶ prod.snd p) fun (X Y : Cᵒᵖ × C) (f : X ⟶ Y) (h : opposite.unop (prod.fst X) ⟶ prod.snd X) => has_hom.hom.unop (prod.fst f) ≫ h ≫ prod.snd f @[simp] theorem hom_obj (C : Type u) [category C] (X : Cᵒᵖ × C) : obj (hom C) X = (opposite.unop (prod.fst X) ⟶ prod.snd X) := rfl @[simp] theorem hom_pairing_map (C : Type u) [category C] {X : Cᵒᵖ × C} {Y : Cᵒᵖ × C} (f : X ⟶ Y) : map (hom C) f = fun (h : obj (hom C) X) => has_hom.hom.unop (prod.fst f) ≫ h ≫ prod.snd f := rfl
c82873732611addf402775619a20383ebe80dd8b
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/linear_algebra/basic.lean
fd32a2dc6ad01e7919d82b34e01eb2a514f9c029
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
70,355
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard -/ import algebra.pi_instances data.finsupp data.equiv.algebra order.order_iso /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module.lean`. ## Main definitions * Many constructors for linear maps, including `pair` and `copair` * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * `linear_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that extends `linear_map` and `equiv`. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `sup_quotient_equiv_quotient_inf`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`pair`, `copair`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function lattice reserve infix ` ≃ₗ `:25 universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finset lemma smul_sum {α : Type u} {M : Type v} {R : Type w} [ring R] [add_comm_group M] [module R M] {s : finset α} {a : R} {f : α → M} : a • (s.sum f) = s.sum (λc, a • f c) := (finset.sum_hom ((•) a)).symm end finset namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [ring R] [add_comm_group M] [module R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp namespace linear_map section variables [ring R] [add_comm_group M] [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 (f g : M →ₗ[R] M₂) include R @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂], λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩ /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp, by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp instance linear_map.is_add_group_hom : is_add_group_hom f := { map_add := f.add } instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : t.sum f b = t.sum (λd, f d b) := (@finset.sum_hom _ _ _ t f _ _ (λ g : M →ₗ[R] M₂, g b) _).symm @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl /-- `λb, f b • x` is a linear map. -/ def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_right f x : M₂ → M) c = f c • x := rfl instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ @[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl section variables (R M) include M instance endomorphism_ring : ring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..}; { intros, apply linear_map.ext, simp } end section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩ end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The pair of two linear maps is a linear map. -/ def pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ := ⟨λ x, (f x, g x), λ x y, by simp, λ x y, by simp⟩ @[simp] theorem pair_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) : pair f g x = (f x, g x) := rfl @[simp] theorem fst_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (pair f g) = f := by ext; refl @[simp] theorem snd_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (pair f g) = g := by ext; refl @[simp] theorem pair_fst_snd : pair (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl] /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr] end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl /-- The copair function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def copair (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := ⟨λ x, f x.1 + g x.2, λ x y, by simp, λ x y, by simp [smul_add]⟩ @[simp] theorem copair_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) : copair f g (x, y) = f x + g y := rfl @[simp] theorem copair_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (copair f g).comp (inl R M M₂) = f := by ext; simp @[simp] theorem copair_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (copair f g).comp (inr R M M₂) = g := by ext; simp @[simp] theorem copair_inl_inr : copair (inl R M M₂) (inr R M M₂) = linear_map.id := by ext ⟨x, y⟩; simp theorem fst_eq_copair : fst R M M₂ = copair linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_copair : snd R M M₂ = copair 0 linear_map.id := by ext ⟨x, y⟩; simp theorem inl_eq_pair : inl R M M₂ = pair linear_map.id 0 := rfl theorem inr_eq_pair : inr R M M₂ = pair 0 linear_map.id := rfl end section comm_ring variables [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₃] variables (f g : M →ₗ[R] M₂) include R instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl instance : module R (M →ₗ[R] M₂) := module.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def congr_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨linear_map.comp f, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl end comm_ring end linear_map namespace submodule variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set lattice instance : partial_order (submodule R M) := partial_order.lift (coe : submodule R M → set M) (λ a b, ext') (by apply_instance) lemma le_def {p p' : submodule R M} : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl lemma le_def' {p p' : submodule R M} : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl /-- If two submodules p and p' satisfy p ⊆ p', then `of_le p p'` is the linear map version of this inclusion. -/ def of_le {p p' : submodule R M} (h : p ≤ p') : p →ₗ[R] p' := linear_map.cod_restrict _ p.subtype $ λ ⟨x, hx⟩, h hx @[simp] theorem of_le_apply {p p' : submodule R M} (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : (submodule.subtype q).comp (of_le h) = submodule.subtype p := by ext ⟨b, hb⟩; simp /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨by split; try {exact {0}}; simp {contextual := tt}⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨by split; try {exact set.univ}; simp⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ := by ext x; simp [semimodule.eq_zero_of_zero_eq_one _ x zero_eq_one] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, ↑s, zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.lattice.order_top, ..submodule.lattice.order_bot } instance : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] theorem mem_infi {ι} (p : ι → submodule R M) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, zero := ⟨0, p.zero_mem, f.map_zero⟩, add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩; exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩, smul := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ } lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.ext' $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, zero := by simp, add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂], smul := λ a x h, by simp [p.smul_mem _ h] } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.ext' rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr @[simp] theorem Union_coe_of_directed {ι} (hι : nonempty ι) (S : ι → submodule R M) (H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), rw [show supr S = ⨆ i, span R (S i), by simp, ← span_Union], unfreezeI, refine λ x hx, span_induction hx (λ _, id) _ _ _, { cases hι with i, exact mem_Union.2 ⟨i, by simp⟩ }, { simp, intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { simp [-mem_coe]; exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_supr_of_mem {ι : Sort*} {b : M} (p : ι → submodule R M) (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h @[simp] theorem mem_supr_of_directed {ι} (hι : nonempty ι) (S : ι → submodule R M) (H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by rw [← mem_coe, Union_coe_of_directed hι S H, mem_Union]; refl theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hzs : z ∈ Sup s) (x ∈ s) (hdir : ∀ i ∈ s, ∀ j ∈ s, ∃ k ∈ s, i ≤ k ∧ j ≤ k) : ∃ y ∈ s, z ∈ y := begin haveI := classical.dec, rw Sup_eq_supr at hzs, have : ∃ (i : submodule R M), z ∈ ⨆ (H : i ∈ s), i, { refine (mem_supr_of_directed ⟨⊥⟩ _ (λ i j, _)).1 hzs, by_cases his : i ∈ s; by_cases hjs : j ∈ s, { rcases hdir i his j hjs with ⟨k, hks, hik, hjk⟩, exact ⟨k, le_supr_of_le hks (supr_le $ λ _, hik), le_supr_of_le hks (supr_le $ λ _, hjk)⟩ }, { exact ⟨i, le_refl _, supr_le $ hjs.elim⟩ }, { exact ⟨j, supr_le $ his.elim, le_refl _⟩ }, { exact ⟨⊥, supr_le $ his.elim, supr_le $ hjs.elim⟩ } }, cases this with N hzn, by_cases hns : N ∈ s, { have : (⨆ (H : N ∈ s), N) ≤ N := supr_le (λ _, le_refl _), exact ⟨N, hns, this hzn⟩ }, { have : (⨆ (H : N ∈ s), N) ≤ ⊥ := supr_le hns.elim, cases (mem_bot R).1 (this hzn), exact ⟨x, H, x.zero_mem⟩ } end section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ end lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin rw [← union_singleton, span_union, mem_sup], simp [mem_span_singleton], split, { rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ }, { rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ } end lemma mem_span_insert' {y} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp⟩ } end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, zero := ⟨zero_mem _, zero_mem _⟩, add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩; exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩, smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := ext' set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [le_def'], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm] instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_add] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : module R (quotient p) := module.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] instance {K M} {R:discrete_field K} [add_comm_group M] [vector_space K M] (p : submodule K M) : vector_space K (quotient p) := {} end quotient end submodule namespace submodule variables [discrete_field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end set_option class.instance_max_depth 40 lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by by_cases a = 0; simp [h, map_smul] end submodule namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule @[simp] lemma finsupp_sum {R M M₂ γ} [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂] [has_zero γ] (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := (set.ext_iff _ _).1 (range_coe f). @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := begin refine eq_top_iff'.2 (λ x, mem_sup.2 _), rcases x with ⟨x₁, x₂⟩ , have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range, by simp, have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range, by simp, use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂], simp end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0), from ⟨λ h m, h m mem_top, λ h m _, h m⟩, by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rw [map_comap_eq, inf_of_le_right h] lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem map_le_map_iff {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := ⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩ theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff hf).1 (le_of_eq h)) ((map_le_map_iff hf).1 (ge_of_eq h)) theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem map_copair_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (copair f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_pair_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (pair f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_copair_prod, copair_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (prod.inl '' s ∪ prod.inr '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl lemma ker_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (pair f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_pair_prod]; refl end linear_map namespace linear_map variables [discrete_field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end linear_map namespace is_linear_map lemma is_linear_map_add {R M : Type*} [ring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [ring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp }, { intros x y, simp [smul_add] } end end is_linear_map namespace submodule variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot.2 $ λ x y, subtype.eq' @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] lemma disjoint_iff_comap_eq_bot (p q : submodule R M) : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff p.ker_subtype, map_bot, map_comap_subtype]; refl /-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/ def map_subtype.order_iso : ((≤) : submodule R p → submodule R p → Prop) ≃o ((≤) : {p' : submodule R M // p' ≤ p} → {p' : submodule R M // p' ≤ p} → Prop) := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq], ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of M. -/ def map_subtype.le_order_embedding : ((≤) : submodule R p → submodule R p → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.le_order_embedding p p' = map p.subtype p' := rfl /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of M. -/ def map_subtype.lt_order_embedding : ((<) : submodule R p → submodule R p → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (map_subtype.le_order_embedding p).lt_embedding_of_le_embedding @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] /-- The map from a module `M` to the quotient of `M` by a submodule `p` is a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` along `f : M → M₂` is linear. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.order_iso : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≃o ((≤) : {p' : submodule R M // p ≤ p'} → {p' : submodule R M // p ≤ p'} → Prop) := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq], ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.le_order_embedding : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.lt_order_embedding : ((<) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding end submodule section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] extends M →ₗ[R] M₂, M ≃ M₂ end infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ @[simp] theorem coe_apply (e : M ≃ₗ[R] M₂) (b : M) : (e : M →ₗ[R] M₂) b = e b := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[ext] lemma ext {f g : M ≃ₗ[R] M₂} (h : (f : M → M₂) = g) : f = g := to_equiv_injective (equiv.eq_of_to_fun_eq h) section variable (M) /-- The identity map is a linear equivalence. -/ def refl : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end /-- Linear equivalences are symmetric. -/ def symm (e : M ≃ₗ[R] M₂) : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- Linear equivalences are transitive. -/ def trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] theorem apply_symm_apply (e : M ≃ₗ[R] M₂) (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (e : M ≃ₗ[R] M₂) (b : M) : e.symm (e b) = b := e.5 b /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (f : M →ₗ[R] M₂) (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := { ..f, ..@equiv.of_bijective _ _ f ⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ } @[simp] theorem of_bijective_apply (f : M →ₗ[R] M₂) {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem ker (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot.2 f.to_equiv.injective @[simp] protected theorem range (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 f.to_equiv.surjective /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (p : submodule R M) (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply (p : submodule R M) {h} (x : p) : of_top p h x = x := rfl @[simp] theorem of_top_symm_apply (p : submodule R M) {h} (x : M) : ↑((of_top p h).symm x) = x := rfl lemma eq_bot_of_equiv (p : submodule R M) (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), have := e.symm_apply_apply ⟨b, hb⟩, rw [← e.coe_apply, submodule.eq_zero_of_bot_submodule ((e : p →ₗ[R] (⊥ : submodule R M₂)) ⟨b, hb⟩), ← e.symm.coe_apply, linear_map.map_zero] at this, exact congr_arg (coe : p → M) this.symm end end ring section comm_ring variables [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₃] include R open linear_map set_option class.instance_max_depth 39 /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, e₂.to_linear_map.comp $ f.comp e₁.symm.to_linear_map, inv_fun := λ f, e₂.symm.to_linear_map.comp $ f.comp e₁.to_linear_map, left_inv := λ f, by { ext x, unfold_coes, change e₂.inv_fun (e₂.to_fun $ f.to_fun $ e₁.inv_fun $ e₁.to_fun x) = _, rw [e₁.left_inv, e₂.left_inv] }, right_inv := λ f, by { ext x, unfold_coes, change e₂.to_fun (e₂.inv_fun $ f.to_fun $ e₁.to_fun $ e₁.inv_fun x) = _, rw [e₁.right_inv, e₂.right_inv] }, add := λ f g, by { ext x, change e₂.to_fun ((f + g) (e₁.inv_fun x)) = _, rw [linear_map.add_apply, e₂.add], refl }, smul := λ c f, by { ext x, change e₂.to_fun ((c • f) (e₁.inv_fun x)) = _, rw [linear_map.smul_apply, e₂.smul], refl } } /-- If M₂ and M₃ are linearly isomorphic then the two spaces of linear maps from M into M₂ and M into M₃ are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl M) f /-- If M and M₂ are linearly isomorphic then the two spaces of linear maps from M and M₂ to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (M →ₗ[R] M) ≃ₗ[R] (M₂ →ₗ[R] M₂) := arrow_congr e e end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variable (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha end field end linear_equiv namespace equiv variables [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { add := h.add, smul := h.smul, .. e} end equiv namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right, let F : f.ker.quotient →ₗ[R] f.range := f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩) (λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in { inv_fun := λx, submodule.quotient.mk (classical.some (hr x)), left_inv := by rintro ⟨x⟩; exact (submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $ classical.some_spec $ hr $ F $ submodule.quotient.mk x), right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x), .. F } open submodule /-- Canonical linear map from the quotient p/(p ∩ p') to (p+p')/p', mapping x + (p ∩ p') to x + p', where p and p' are submodules of an ambient module. -/ def sup_quotient_to_quotient_inf (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf le_sup_left (le_refl _)) end set_option class.instance_max_depth 41 /-- Second Isomorphism Law : the canonical map from p/(p ∩ p') to (p+p')/p' as a linear isomorphism. -/ noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := { .. sup_quotient_to_quotient_inf p p', .. show (comap p.subtype (p ⊓ p')).quotient ≃ (comap (p ⊔ p').subtype p').quotient, from @equiv.of_bijective _ _ (sup_quotient_to_quotient_inf p p') begin constructor, { rw [← ker_eq_bot, sup_quotient_to_quotient_inf, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], rintros ⟨x, hx1⟩ hx2, exact ⟨hx1, hx2⟩ }, rw [← range_eq_top, sup_quotient_to_quotient_inf, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end } section prod /-- The cartesian product of two linear maps as a linear map. -/ def prod {R M M₂ M₃ : Type*} [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] (f₁ : M →ₗ[R] M₂) (f₂ : M →ₗ[R] M₃) : M →ₗ[R] (M₂ × M₃) := { to_fun := λx, (f₁ x, f₂ x), add := λx y, begin change (f₁ (x + y), f₂ (x+y)) = (f₁ x, f₂ x) + (f₁ y, f₂ y), simp only [linear_map.map_add], refl end, smul := λc x, by simp only [linear_map.map_smul] } lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] : is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) := ⟨λu v, rfl, λc u, rfl⟩ end prod section pi universe i variables {φ : ι → Type i} variables [∀i, add_comm_group (φ i)] [∀i, module R (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := ⟨λc i, f i c, assume c d, funext $ assume i, (f i).add _ _, assume c d, funext $ assume i, (f i).smul _ _⟩ @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := bot_unique $ submodule.le_def'.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end section variables (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'], ext b ⟨j, hj⟩, refl }, { ext ⟨b, hb⟩, apply subtype.coe_ext.2, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { rw [dif_pos h], refl }, { rw [dif_neg h], exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end section variable [decidable_eq ι] variables (R φ) /-- The standard basis of the product of `φ`. -/ def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot.2 $ assume f g hfg, have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := by ext b; simp [std_basis_ne R φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) := begin refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb j hj, have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩, rw [proj_std_basis_ne R φ j i this.symm, zero_apply] end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show I.sum (λi, std_basis R φ i (b i)) = b, { ext i, rw [pi.finset_sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $ linear_map.mem_range.2 ⟨_, rfl⟩) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [finset.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _), rw [← finset.mem_coe, finset.coe_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ := have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty], begin apply top_unique, convert (infi_ker_proj_le_supr_range_std_basis R φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm) end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint_mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _, simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := begin ext i j, rw [std_basis_apply, finsupp.single_apply], split_ifs, { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h)], refl }, end end end pi variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : group (general_linear_group R M) := by delta general_linear_group; apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, begin delta to_linear_equiv of_linear_equiv, cases f with f f_inv, cases f, cases f_inv, congr end, right_inv := λ f, begin delta to_linear_equiv of_linear_equiv, cases f, congr end, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : ((general_linear_equiv R M).to_equiv f).to_linear_map = f.val := by {ext, refl} end general_linear_group end linear_map
7190d3238485949a2a0c0aa3f7c452d098050543
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/functor.lean
2cfcda936721194116df81450a49125920aa1157
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,971
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Johannes Hölzl, Simon Hudon, Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.basic import Mathlib.control.traversable.lemmas import Mathlib.control.traversable.instances import Mathlib.PostPort universes u_1 u u_2 namespace Mathlib /-! # Functoriality of `multiset`. -/ namespace multiset protected instance functor : Functor multiset := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β } @[simp] theorem fmap_def {α' : Type u_1} {β' : Type u_1} {s : multiset α'} (f : α' → β') : f <$> s = map f s := rfl protected instance is_lawful_functor : is_lawful_functor multiset := sorry def traverse {F : Type u → Type u} [Applicative F] [is_comm_applicative F] {α' : Type u} {β' : Type u} (f : α' → F β') : multiset α' → F (multiset β') := quotient.lift (Functor.map coe ∘ traverse f) sorry protected instance monad : Monad multiset := { toApplicative := { toFunctor := { map := Functor.map, mapConst := Functor.mapConst }, toPure := { pure := fun (α : Type u_1) (x : α) => x ::ₘ 0 }, toSeq := { seq := fun (α β : Type u_1) (f : multiset (α → β)) (x : multiset α) => bind f fun (_x : α → β) => map _x x }, toSeqLeft := { seqLeft := fun (α β : Type u_1) (a : multiset α) (b : multiset β) => (fun (α β : Type u_1) (f : multiset (α → β)) (x : multiset α) => bind f fun (_x : α → β) => map _x x) β α (map (function.const β) a) b }, toSeqRight := { seqRight := fun (α β : Type u_1) (a : multiset α) (b : multiset β) => (fun (α β : Type u_1) (f : multiset (α → β)) (x : multiset α) => bind f fun (_x : α → β) => map _x x) β β (map (function.const α id) a) b } }, toBind := { bind := bind } } @[simp] theorem pure_def {α : Type u_1} : pure = fun (x : α) => x ::ₘ 0 := rfl @[simp] theorem bind_def {α : Type u_1} {β : Type u_1} : bind = bind := rfl protected instance is_lawful_monad : is_lawful_monad multiset := sorry @[simp] theorem lift_beta {α : Type u_1} {β : Type u_2} (x : List α) (f : List α → β) (h : ∀ (a b : List α), a ≈ b → f a = f b) : quotient.lift f h ↑x = f x := quotient.lift_beta f h x @[simp] theorem map_comp_coe {α : Type u_1} {β : Type u_1} (h : α → β) : Functor.map h ∘ coe = coe ∘ Functor.map h := sorry theorem id_traverse {α : Type u_1} (x : multiset α) : traverse id.mk x = x := sorry theorem comp_traverse {G : Type u_1 → Type u_1} {H : Type u_1 → Type u_1} [Applicative G] [Applicative H] [is_comm_applicative G] [is_comm_applicative H] {α : Type u_1} {β : Type u_1} {γ : Type u_1} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (functor.comp.mk ∘ Functor.map h ∘ g) x = functor.comp.mk (traverse h <$> traverse g x) := sorry theorem map_traverse {G : Type u_1 → Type u_1} [Applicative G] [is_comm_applicative G] {α : Type u_1} {β : Type u_1} {γ : Type u_1} (g : α → G β) (h : β → γ) (x : multiset α) : Functor.map h <$> traverse g x = traverse (Functor.map h ∘ g) x := sorry theorem traverse_map {G : Type u_1 → Type u_1} [Applicative G] [is_comm_applicative G] {α : Type u_1} {β : Type u_1} {γ : Type u_1} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := sorry theorem naturality {G : Type u_1 → Type u_1} {H : Type u_1 → Type u_1} [Applicative G] [Applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α : Type u_1} {β : Type u_1} (f : α → G β) (x : multiset α) : coe_fn eta (multiset β) (traverse f x) = traverse (coe_fn eta β ∘ f) x := sorry
b672390c65923fa0316c38406bd8609f035ed257
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/choose/dvd.lean
3adae6d9f24aa1cc561e150fd21748754bd6da07
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,263
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import data.nat.choose.basic import data.nat.prime /-! # Divisibility properties of binomial coefficients > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace nat open_locale nat namespace prime lemma dvd_choose_add {p a b : ℕ} (hp : prime p) (hap : a < p) (hbp : b < p) (h : p ≤ a + b) : p ∣ choose (a + b) a := begin have h₁ : p ∣ (a + b)!, from hp.dvd_factorial.2 h, rw [← add_choose_mul_factorial_mul_factorial, ← choose_symm_add, hp.dvd_mul, hp.dvd_mul, hp.dvd_factorial, hp.dvd_factorial] at h₁, exact (h₁.resolve_right hbp.not_le).resolve_right hap.not_le end lemma dvd_choose {p a b : ℕ} (hp : prime p) (ha : a < p) (hab : b - a < p) (h : p ≤ b) : p ∣ choose b a := have a + (b - a) = b := nat.add_sub_of_le (ha.le.trans h), this ▸ hp.dvd_choose_add ha hab (this.symm ▸ h) lemma dvd_choose_self {p k : ℕ} (hp : prime p) (hk : k ≠ 0) (hkp : k < p) : p ∣ choose p k := hp.dvd_choose hkp (nat.sub_lt ((zero_le _).trans_lt hkp) hk.bot_lt) le_rfl end prime end nat
fed617276b6d016e0d22d145e720254250a7a6a5
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/filter/partial.lean
06ae9315015aa57c4e91a1f0603793e53ef41842
[ "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
8,445
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Extends `tendsto` to relations and partial functions. -/ import order.filter.basic universes u v w namespace filter variables {α : Type u} {β : Type v} {γ : Type w} open_locale filter /- Relations. -/ def rmap (r : rel α β) (f : filter α) : filter β := { sets := r.core ⁻¹' f.sets, univ_sets := by { simp [rel.core], apply univ_mem_sets }, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ rel.core_mono _ st, inter_sets := by { simp [set.preimage, rel.core_inter], exact λ s t, inter_mem_sets } } theorem rmap_sets (r : rel α β) (f : filter α) : (rmap r f).sets = r.core ⁻¹' f.sets := rfl @[simp] theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) : s ∈ l.rmap r ↔ r.core s ∈ l := iff.rfl @[simp] theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) : rmap s (rmap r l) = rmap (r.comp s) l := filter_eq $ by simp [rmap_sets, set.preimage, rel.core_comp] @[simp] lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) := funext $ rmap_rmap _ _ def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂ theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂, r.core s ∈ l₁ := iff.rfl def rcomap (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.core s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (by rw rel.core_inter) (set.inter_subset_inter ha₂ hb₂)⟩ } theorem rcomap_sets (r : rel α β) (f : filter β) : (rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl @[simp] theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap r (rcomap s l) = rcomap (r.comp s) l := filter_eq $ begin ext t, simp [rcomap_sets, rel.image, rel.core_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.core s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) := funext $ rcomap_rcomap _ _ theorem rtendsto_iff_le_comap (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r := begin rw rtendsto_def, change (∀ (s : set β), s ∈ l₂.sets → rel.core r s ∈ l₁) ↔ l₁ ≤ rcomap r l₂, simp [filter.le_def, rcomap, rel.mem_image], split, intros h s t tl₂ h', { exact mem_sets_of_superset (h t tl₂) h' }, intros h t tl₂, apply h _ t tl₂ (set.subset.refl _), end -- Interestingly, there does not seem to be a way to express this relation using a forward map. -- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if -- and only if `s ∈ f'`. But the intersection of two sets satsifying the lhs may be empty. def rcomap' (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (@rel.preimage_inter _ _ r _ _) (set.inter_subset_inter ha₂ hb₂)⟩ } @[simp] lemma mem_rcomap' (r : rel α β) (l : filter β) (s : set α) : s ∈ l.rcomap' r ↔ ∃ t ∈ l, rel.preimage r t ⊆ s := iff.rfl theorem rcomap'_sets (r : rel α β) (f : filter β) : (rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl @[simp] theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap' r (rcomap' s l) = rcomap' (r.comp s) l := filter_eq $ begin ext t, simp [rcomap'_sets, rel.image, rel.preimage_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.preimage_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.preimage s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) := funext $ rcomap'_rcomap' _ _ def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂, r.preimage s ∈ l₁ := begin unfold rtendsto', unfold rcomap', simp [le_def, rel.mem_image], split, { intros h s hs, apply (h _ _ hs (set.subset.refl _)) }, intros h s t ht h', apply mem_sets_of_superset (h t ht) h' end theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] } theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] } /- Partial functions. -/ def pmap (f : α →. β) (l : filter α) : filter β := filter.rmap f.graph' l @[simp] lemma mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ l.pmap f ↔ f.core s ∈ l := iff.rfl def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂ theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f.core s ∈ l₁ := iff.rfl theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) : ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ := iff.rfl theorem pmap_res (l : filter α) (s : set α) (f : α → β) : pmap (pfun.res f s) l = map f (l ⊓ 𝓟 s) := filter_eq $ begin apply set.ext, intro t, simp [pfun.core_res], split, { intro h, constructor, split, { exact h }, constructor, split, { reflexivity }, simp [set.inter_distrib_right], apply set.inter_subset_left }, rintro ⟨t₁, h₁, t₂, h₂, h₃⟩, apply mem_sets_of_superset h₁, rw ← set.inter_subset, exact set.subset.trans (set.inter_subset_inter_right _ h₂) h₃ end theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) : tendsto f (l₁ ⊓ 𝓟 s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ := by simp only [tendsto, ptendsto, pmap_res] theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ := by { rw ← tendsto_iff_ptendsto, simp [principal_univ] } def pcomap' (f : α →. β) (l : filter β) : filter α := filter.rcomap' f.graph' l def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph' theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂, f.preimage s ∈ l₁ := rtendsto'_def _ _ _ theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} : ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h s sl₂, exacts mem_sets_of_superset (h s sl₂) (pfun.preimage_subset_core _ _), end theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁) : ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h' s sl₂, rw pfun.preimage_eq, show pfun.core f s ∩ pfun.dom f ∈ l₁, exact inter_mem_sets (h' s sl₂) h end end filter
81d82a5da9458dfd7be669d8e9799929702cca9b
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/AuxRecursor.lean
3419c43042915473a386f7fe06b1300a6697833f
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,844
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Environment namespace Lean def casesOnSuffix := "casesOn" def recOnSuffix := "recOn" def brecOnSuffix := "brecOn" def binductionOnSuffix := "binductionOn" def mkCasesOnName (indDeclName : Name) : Name := Name.mkStr indDeclName casesOnSuffix def mkRecOnName (indDeclName : Name) : Name := Name.mkStr indDeclName recOnSuffix def mkBRecOnName (indDeclName : Name) : Name := Name.mkStr indDeclName brecOnSuffix def mkBInductionOnName (indDeclName : Name) : Name := Name.mkStr indDeclName binductionOnSuffix builtin_initialize auxRecExt : TagDeclarationExtension ← mkTagDeclarationExtension `auxRec @[export lean_mark_aux_recursor] def markAuxRecursor (env : Environment) (declName : Name) : Environment := auxRecExt.tag env declName @[export lean_is_aux_recursor] def isAuxRecursor (env : Environment) (declName : Name) : Bool := auxRecExt.isTagged env declName -- TODO: use `markAuxRecursor` when they are defined -- An attribute is not a good solution since we don't want users to control what is tagged as an auxiliary recursor. || declName == ``Eq.ndrec || declName == ``Eq.ndrecOn def isCasesOnRecursor (env : Environment) (declName : Name) : Bool := match declName with | Name.str _ s _ => s == casesOnSuffix && isAuxRecursor env declName | _ => false builtin_initialize noConfusionExt : TagDeclarationExtension ← mkTagDeclarationExtension `noConf @[export lean_mark_no_confusion] def markNoConfusion (env : Environment) (n : Name) : Environment := noConfusionExt.tag env n @[export lean_is_no_confusion] def isNoConfusion (env : Environment) (n : Name) : Bool := noConfusionExt.isTagged env n end Lean
8290cf0f3a88f15a3e9c512159a8a3af012aa6eb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/default.lean
2cfb609541c12eb7577c2ef68e551b7716fd0790
[]
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,010
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.core import Mathlib.Lean3Lib.init.logic import Mathlib.Lean3Lib.init.control.default import Mathlib.Lean3Lib.init.data.basic import Mathlib.Lean3Lib.init.version import Mathlib.Lean3Lib.init.propext import Mathlib.Lean3Lib.init.cc_lemmas import Mathlib.Lean3Lib.init.funext import Mathlib.Lean3Lib.init.control.combinators import Mathlib.Lean3Lib.init.function import Mathlib.Lean3Lib.init.classical import Mathlib.Lean3Lib.init.util import Mathlib.Lean3Lib.init.coe import Mathlib.Lean3Lib.init.wf import Mathlib.Lean3Lib.init.meta.default import Mathlib.Lean3Lib.init.meta.well_founded_tactics import Mathlib.Lean3Lib.init.algebra.default import Mathlib.Lean3Lib.init.data.default import Mathlib.Lean3Lib.init.meta.float import Mathlib.Lean3Lib.init.meta.widget.default namespace Mathlib
ddce2ac7e455d60ae188f66e06c1750683876155
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/492.lean
8ea1197237f76b62010c4c60ea4bd5d29e050c6a
[ "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
374
lean
example : ∃ n : Nat, n = n := by refine ⟨?n, ?h⟩ case h => exact Eq.refl 3 example : ∃ n : Nat, n = n := by refine ⟨?n, ?h⟩ case h => exact rfl case n => exact 3 example : ∃ n : Nat, n = n := by refine ⟨?n, by rfl⟩ case n => exact 3 example : ∃ n : Nat, n = n := by refine ⟨?n, ?h⟩ case h => refine rfl case n => exact 3
3e3940c6769ff12a95786b6662fc777432e92bdd
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/analysis/complex.lean
ddebf63fe368c2bfd31b284fb5028be093532f72
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
4,334
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Topology of the complex numbers. -/ import data.complex.basic analysis.metric_space noncomputable theory open filter namespace complex -- TODO(Mario): these proofs are all copied from analysis/real. Generalize -- to normed fields instance : metric_space ℂ := { dist := λx y, (x - y).abs, dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, complex.abs_sub _ _, dist_triangle := assume x y z, complex.abs_sub_le _ _ _ } theorem dist_eq (x y : ℂ) : dist x y = (x - y).abs := rfl theorem uniform_continuous_add : uniform_continuous (λp : ℂ × ℂ, p.1 + p.2) := uniform_continuous_of_metric.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ theorem uniform_continuous_neg : uniform_continuous (@has_neg.neg ℂ _) := uniform_continuous_of_metric.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [dist_eq] using h⟩ instance : uniform_add_group ℂ := uniform_add_group.mk' uniform_continuous_add uniform_continuous_neg instance : topological_add_group ℂ := by apply_instance lemma uniform_continuous_inv (s : set ℂ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := uniform_continuous_of_metric.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma uniform_continuous_abs : uniform_continuous (abs : ℂ → ℝ) := uniform_continuous_of_metric.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _)⟩ lemma continuous_abs : continuous (abs : ℂ → ℝ) := uniform_continuous_abs.continuous lemma tendsto_inv {r : ℂ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma continuous_inv' : continuous (λa:{r:ℂ // r ≠ 0}, a.val⁻¹) := continuous_iff_tendsto.mpr $ assume ⟨r, hr⟩, (continuous_iff_tendsto.mp continuous_subtype_val _).comp (tendsto_inv hr) lemma continuous_inv {α} [topological_space α] {f : α → ℂ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℂ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from (continuous_subtype_mk _ hf).comp continuous_inv' lemma uniform_continuous_mul_const {x : ℂ} : uniform_continuous ((*) x) := uniform_continuous_of_metric.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma uniform_continuous_mul (s : set (ℂ × ℂ)) {r₁ r₂ : ℝ} (r₁0 : 0 < r₁) (r₂0 : 0 < r₂) (H : ∀ x ∈ s, abs (x : ℂ × ℂ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := uniform_continuous_of_metric.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 r₁0 r₂0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ lemma continuous_mul : continuous (λp : ℂ × ℂ, p.1 * p.2) := continuous_iff_tendsto.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (λ x, id)) (mem_nhds_sets (is_open_prod (continuous_abs _ $ is_open_gt' _) (continuous_abs _ $ is_open_gt' _)) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℂ := { continuous_mul := continuous_mul, ..complex.topological_add_group } instance : topological_semiring ℂ := by apply_instance end complex
de8496d09605e3570c17fed7ac8138ece6297f13
fe84e287c662151bb313504482b218a503b972f3
/src/order/sort_rank.lean
1d7517c27c18bc333e17d22f4ed2125a39e1ef00
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
21,341
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This file formalises the fact that any finite, linearly ordered set of size n has a unique order-isomorphism with the set fin n = {0,...,n-1}. -/ import data.finset data.fintype.basic import data.fin_extra open list variables {α : Type*} namespace list /- If we have a list l (of length n) and a natural number i, we might want to refer to the i'th entry in the list, but then we have to decide what to do about the possibility that i is too large so that there is no i'th entry. We always use 0-based indexing so the i'th entry is defined for i < n but not for i ≥ n. The standard library defines (l.nth i) to be of type (option α), and to have value (some x) if i < n and x is the i'th entry, but to have value (none) if i ≥ n. The standard library also defines (l.nth_le i h) to be x if h is a proof of i < n. Here we just repackage this slightly: the pair ⟨i,h⟩ gives a term of type (fin n), and we define l.fin_nth ⟨i,h⟩ to be x again. -/ def fin_nth (l : list α) (i : fin l.length) : α := l.nth_le i.val i.is_lt /- An obvious lemma about the behaviour of fin_nth. -/ lemma fin_nth_cons (a : α) (l : list α) (i : fin l.length) : (list.cons a l).fin_nth i.succ = l.fin_nth i := begin cases i,dsimp[fin.succ,fin_nth],refl, end /- If R is a relation on α and l is a list, we define (pairwise_nth R l) to be true if all entries in l are R-related to all strictly later entries. For example, if R is an order relation then this just means that the list is sorted, and if R is the relation x ≠ y then this just means that l has no duplicates. Here we define pairwise_nth in the obvious way using indices. We then prove that our pairwise_nth is equivalent to the definition of pairwise in the standard library, which is formulated by structural induction rather than using indices. -/ def pairwise_nth₀ (R : α → α → Prop) (l : list α) := ∀ (i j : fin l.length), i < j → R (l.fin_nth i) (l.fin_nth j) def pairwise_nth (R : α → α → Prop) (l : list α) := ∀ {i j : ℕ} (hi : i < j) (hj : j < l.length), R (l.nth_le i (lt_trans hi hj)) (l.nth_le j hj) lemma pairwise_nth_mp {R : α → α → Prop} {l : list α} (p : pairwise R l) : pairwise_nth R l := begin induction p with a l0 R_a_l0 p0 ih, { intros i j hi hj, cases hj }, { intros i j hi hj, cases j with j₀, { cases hi }, have hj0 : j₀ < l0.length := nat.lt_of_succ_lt_succ hj, cases i with i₀, { exact R_a_l0 _ (l0.nth_le_mem j₀ hj0) }, { exact ih (nat.lt_of_succ_lt_succ hi) hj0 } } end lemma pairwise_nth_mpr {R : α → α → Prop} {l : list α} (hl : pairwise_nth R l) : (pairwise R l) := begin induction l with a l ih, { exact @pairwise.nil _ R }, { have R_a_l : ∀ (b ∈ l), (R a b) := begin intros b b_in_l, rcases nth_le_of_mem b_in_l with ⟨j,⟨hj,eq_b⟩⟩, rw [← eq_b], exact hl (nat.zero_lt_succ j) (nat.succ_lt_succ hj) end, have : l.pairwise R := begin apply ih, intros i j hi hj, exact hl (nat.succ_lt_succ hi) (nat.succ_lt_succ hj), end, exact pairwise.cons R_a_l this } end lemma pairwise_nth_iff {R : α → α → Prop} {l : list α} : (pairwise R l) ↔ (pairwise_nth R l) := iff.intro (@pairwise_nth_mp _ R l) (@pairwise_nth_mpr _ R l) /- The standard library defines a list to be sorted if all entries are less than or equal to all strictly later entries. Here we define a list to be strongly sorted if the relevant inequalities hold strictly. This is clearly equivalent to saying that the list is sorted and has distinct entries; we also formalise this equivalence. -/ variables [linear_order α] [decidable_rel (@has_le.le α _)] def strongly_sorted (l : list α) : Prop := list.pairwise has_lt.lt l lemma strongly_sorted_of_sorted_nodup (l : list α) : l.sorted has_le.le → l.nodup → l.strongly_sorted := begin intro l_sorted, induction l_sorted with a l0 a_le_l0 l0_sorted ih, {intro,exact pairwise.nil}, {intro l_nodup, cases l_nodup with _ _ a_ne_l0 l0_nodup, have l0_strongly_sorted := ih l0_nodup, have a_lt_l0 : ∀ (x : α) (x_in_l0 : x ∈ l0), (a < x) := begin intros x x_in_l0, exact lt_of_le_of_ne (a_le_l0 x x_in_l0) (a_ne_l0 x x_in_l0), end, exact pairwise.cons a_lt_l0 l0_strongly_sorted, } end lemma sorted_of_strongly_sorted (l : list α) : l.strongly_sorted → l.sorted has_le.le := begin intro l_strongly_sorted, induction l_strongly_sorted with a l0 a_lt_l0 l0_strongly_sorted ih, {exact pairwise.nil}, {have a_le_l0 : ∀ x ∈ l0, a ≤ x := λ x x_in_l0,le_of_lt (a_lt_l0 x x_in_l0), have l0_sorted := ih, exact pairwise.cons a_le_l0 l0_sorted } end lemma nodup_of_strongly_sorted (l : list α) : l.strongly_sorted → l.nodup := begin intro l_strongly_sorted, induction l_strongly_sorted with a l0 a_ne_l0 l0_strongly_sorted ih, {exact pairwise.nil}, {have a_ne_l0 : ∀ x ∈ l0, a ≠ x := λ x x_in_l0,ne_of_lt (a_ne_l0 x x_in_l0), have l0_nodup := ih, exact pairwise.cons a_ne_l0 l0_nodup } end /- Sortedness is defined in the standard library by structural induction. Here we reformulate it in terms of indices. -/ lemma sorted_nth_lt_mp {l : list α} (l_nodup : list.nodup l) (l_sorted : list.sorted has_le.le l) {i j : ℕ} (hi : i < j) (hj : j < l.length) : (l.nth_le i (lt_trans hi hj) < l.nth_le j hj) := begin let x := l.nth_le i (lt_trans hi hj), let y := l.nth_le j hj, have x_ne_y : x ≠ y := pairwise_nth_mp l_nodup hi hj, have x_le_y : x ≤ y := pairwise_nth_mp l_sorted hi hj, exact lt_of_le_of_ne x_le_y x_ne_y, end lemma sorted_nth_le_mp {l : list α} (l_nodup : list.nodup l) (l_sorted : list.sorted has_le.le l) {i j : ℕ} (hi : i ≤ j) (hj : j < l.length) : (l.nth_le i (lt_of_le_of_lt hi hj) ≤ l.nth_le j hj) := begin by_cases h : i = j, { cases h, refl }, { have hi' : i < j := lt_of_le_of_ne hi h, exact (le_of_lt $ sorted_nth_lt_mp l_nodup l_sorted hi' hj) } end lemma sorted_nth_lt {l : list α} (l_nodup : list.nodup l) (l_sorted : list.sorted has_le.le l) { i j : ℕ } (hi : i < l.length) (hj : j < l.length) : (i < j) ↔ (l.nth_le i hi < l.nth_le j hj) := begin split, { intro hi', exact sorted_nth_lt_mp l_nodup l_sorted hi' hj }, { intro x_lt_y, rcases lt_or_ge i j with i_lt_j | j_le_i, { assumption }, { exfalso, let y_le_x := sorted_nth_le_mp l_nodup l_sorted j_le_i hi, exact not_lt_of_ge y_le_x x_lt_y } } end lemma sorted_nth_le {l : list α} (l_nodup : list.nodup l) (l_sorted : list.sorted has_le.le l) { i j : ℕ } (hi : i < l.length) (hj : j < l.length) : (i ≤ j) ↔ (l.nth_le i hi ≤ l.nth_le j hj) := begin split, { intro hi', exact sorted_nth_le_mp l_nodup l_sorted hi' hj }, { intro x_le_y, rcases le_or_gt i j with i_le_j | j_lt_i, { assumption }, { exfalso, let y_lt_x := sorted_nth_lt_mp l_nodup l_sorted j_lt_i hi, exact not_le_of_gt y_lt_x x_le_y } } end end list namespace finset variables [linear_order α] [decidable_rel (@has_le.le α _)] /- The standard library defines a function that accepts a finite set s and returns the list of elements in sorted order. The next lemma tells us how we can recognise that list if we have obtained it by other means. -/ theorem list.perm.eqv' (α : Type*) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) instance list.is_setoid' (α : Type*) : setoid (list α) := setoid.mk (@perm α) (list.perm.eqv' α) lemma sort_spec (s : finset α) (l : list α) (l_nodup : l.nodup) (l_sorted : l.sorted has_le.le) (s_eq_l : s = l.to_finset) : s.sort has_le.le = l := begin let h0 := (congr_arg val (eq.trans (eq.trans (to_finset_eq (sort_nodup has_le.le s)) (eq.trans (sort_to_finset has_le.le s) s_eq_l)) (eq.symm (to_finset_eq l_nodup)))), let h1 := list.eq_of_perm_of_sorted (@quotient.exact (list α) (list.is_setoid' α) _ _ h0) (sort_sorted has_le.le s) l_sorted, let ll : multiset α := quot.mk _ l, have ll_nodup : ll.nodup := multiset.coe_nodup.mpr l_nodup, have ll_eq : (⟨ll,ll_nodup⟩ : finset α) = l.to_finset := list.to_finset_eq l_nodup, let m := s.sort has_le.le, have m_nodup : m.nodup := s.sort_nodup has_le.le, have m_sorted : m.sorted has_le.le := s.sort_sorted has_le.le, let mm : multiset α := quot.mk _ m, have mm_nodup : mm.nodup := multiset.coe_nodup.mpr m_nodup, have mm_eq : (⟨mm,mm_nodup⟩ : finset α) = m.to_finset := list.to_finset_eq m_nodup, have m_to_finset : m.to_finset = s := s.sort_to_finset has_le.le, let mm_eq_ll := congr_arg finset.val ((mm_eq.trans (m_to_finset.trans s_eq_l)).trans ll_eq.symm), dsimp[finset.val] at mm_eq_ll, have perm_m_l : perm m l := quotient.exact mm_eq_ll, exact list.eq_of_perm_of_sorted perm_m_l m_sorted l_sorted, end /- The next lemma is equivalent to the previous one. However, as an experiment we have written it as a single term rather than using tactics. We used the command "#print sort_spec" to print the proof term generated automatically be Lean from the tactic proof, and then reorganised it a bit to eliminate some inefficiencies. -/ lemma sort_spec_alt (s : finset α) (l : list α) (l_nodup : l.nodup) (l_sorted : l.sorted has_le.le) (s_eq_l : s = l.to_finset) : s.sort has_le.le = l := list.eq_of_perm_of_sorted (@quotient.exact (list α) (list.is_setoid' α) _ _ (@congr_arg (finset α) (multiset α) _ _ finset.val (eq.trans (eq.trans (to_finset_eq (sort_nodup has_le.le s)) (eq.trans (sort_to_finset has_le.le s) s_eq_l)) (eq.symm (to_finset_eq l_nodup)) ) ) ) (sort_sorted has_le.le s) l_sorted section rank_equiv /- We now give our first version of the fact that any finite, linearly ordered set of size n is order-isomorphic to (fin n). In this version, the type α has a decidable linear order and s is a finite subset of α that need not contain all elements of α. In order to talk about an order-equivalence we need to convert s into a separate type by considering {a // a ∈ s}. The definition (rank_equiv s) gives an equivalence from this type to (fin n), but it is not initially packaged with any information about order-preserving properties. Instead, we prove those properties as four separate lemmas after the definition of rank_equiv. Note that we have arguments n and s_card : s.card = n, and we produce an equivalence with (fin n). One might think that it would be more natural to just produce an equivalence with (fin s.card), and then use eq.mp to convert this to (fin n) if necessary. Unfortunately, this leads to a lot of tedious troubles with heterogenous equality. As far as I can tell, the present approach is the simplest way to avoid that. -/ variables {s : finset α} {n : ℕ} (s_card : s.card = n) include s_card #check list.mem_to_finset def rank_equiv : { a // a ∈ s } ≃ fin n := begin let l := s.sort has_le.le, have l_nodup : list.nodup l := finset.sort_nodup has_le.le s, have l_eq_s : l.to_finset = s := by simp[finset.sort_eq], have l_len : l.length = n := ((@eq.subst (finset α) (λ t, t.card = l.length) _ _ l_eq_s (list.to_finset_card_of_nodup l_nodup)).symm).trans s_card, let mem_equiv : ∀ a : α, a ∈ s ↔ a ∈ l := λ a, @eq.subst (finset α) (λ t, a ∈ t ↔ a ∈ l) _ _ l_eq_s list.mem_to_finset, let to_fun : { a // a ∈ s } → fin n := begin intro a, have a_in_l : a.val ∈ l := (mem_equiv a.val).mp a.property, let i : ℕ := list.index_of a.val l, have i_lt_n : i < n := l_len.subst (list.index_of_lt_length.mpr a_in_l), exact ⟨i,i_lt_n⟩ end, let inv_fun : fin n → { a // a ∈ s } := begin intro i, have i_is_lt : i.val < l.length := @eq.subst ℕ (λ m, i.val < m) _ _ l_len.symm i.is_lt, let a := l.nth_le i.val i_is_lt, have a_in_s : a ∈ s := (mem_equiv a).mpr (l.nth_le_mem i.val i_is_lt), exact ⟨a,a_in_s⟩ end, have left_inv : ∀ a, inv_fun (to_fun a) = a := begin intro a, rcases a with ⟨a_val,a_in_s⟩, have a_in_l : a_val ∈ l := (mem_equiv a_val).mp a_in_s, let i := list.index_of a_val l, have i_lt_len : i < l.length := list.index_of_lt_length.mpr a_in_l, have i_lt_n : i < n := l_len.subst i_lt_len, dsimp[inv_fun,to_fun], apply subtype.eq,dsimp[subtype.val], exact list.index_of_nth_le i_lt_len, end, have right_inv : ∀ i, to_fun (inv_fun i) = i := begin intro i, rcases i with ⟨i_val,i_lt_n⟩, have i_lt_len : i_val < l.length := l_len.symm.subst i_lt_n, dsimp[inv_fun,to_fun], apply fin.eq_of_veq,dsimp[subtype.val], exact list.nth_le_index_of l_nodup i_val i_lt_len, end, exact ⟨to_fun,inv_fun,left_inv,right_inv⟩, end lemma seq_le (i1 i2 : fin n) : i1 ≤ i2 ↔ (((rank_equiv s_card).inv_fun i1).val ≤ ((rank_equiv s_card).inv_fun i2).val) := begin dsimp [rank_equiv, nth_le, has_le.le, fin.le], let l := s.sort has_le.le, have l_nodup : list.nodup l := finset.sort_nodup has_le.le s, have l_sorted : l.sorted has_le.le := sort_sorted has_le.le s, have l_eq_s : l.to_finset = s := by simp[finset.sort_eq], have l_len : l.length = n := ((@eq.subst (finset α) (λ t, t.card = l.length) _ _ l_eq_s (list.to_finset_card_of_nodup l_nodup)).symm).trans s_card, have i1p : i1.val < l.length := by { rw[l_len], exact i1.is_lt }, have i2p : i2.val < l.length := by { rw[l_len], exact i2.is_lt }, exact list.sorted_nth_le l_nodup l_sorted i1p i2p end lemma seq_lt (i1 i2 : fin n) : i1 < i2 ↔ (((rank_equiv s_card).inv_fun i1).val < ((rank_equiv s_card).inv_fun i2).val) := begin dsimp [rank_equiv, nth_le, has_le.le, fin.le], let l := s.sort has_le.le, have l_nodup : list.nodup l := finset.sort_nodup has_le.le s, have l_sorted : l.sorted has_le.le := sort_sorted has_le.le s, have l_eq_s : l.to_finset = s := by simp[finset.sort_eq], have l_len : l.length = n := ((@eq.subst (finset α) (λ t, t.card = l.length) _ _ l_eq_s (list.to_finset_card_of_nodup l_nodup)).symm).trans s_card, have i1p : i1.val < l.length := by { rw[l_len], exact i1.is_lt }, have i2p : i2.val < l.length := by { rw[l_len], exact i2.is_lt }, exact list.sorted_nth_lt l_nodup l_sorted i1p i2p end lemma rank_le (a1 a2 : {a // a ∈ s }) : a1.val ≤ a2.val ↔ (rank_equiv s_card).to_fun a1 ≤ (rank_equiv s_card).to_fun a2 := begin let f := rank_equiv s_card, let i1 := f.to_fun a1, let i2 := f.to_fun a2, let a1a := f.inv_fun i1, let a2a := f.inv_fun i2, let h := ((seq_le s_card) (f.to_fun a1) (f.to_fun a2)).symm, let e1 : (f.inv_fun i1).val = a1.val := congr_arg subtype.val (f.left_inv a1), let e2 : (f.inv_fun i2).val = a2.val := congr_arg subtype.val (f.left_inv a2), split, {intro h1,rw[← e1,← e2] at h1,exact h.mp h1,}, {intro h2,let h3 := h.mpr h2,rw[e1,e2] at h3,exact h3} end lemma rank_lt (a1 a2 : {a // a ∈ s }) : a1.val < a2.val ↔ ((rank_equiv s_card).to_fun a1) < ((rank_equiv s_card).to_fun a2) := begin let f := rank_equiv s_card, let i1 := f.to_fun a1, let i2 := f.to_fun a2, let a1a := f.inv_fun i1, let a2a := f.inv_fun i2, let h := ((seq_lt s_card) (f.to_fun a1) (f.to_fun a2)).symm, let e1 : (f.inv_fun i1).val = a1.val := congr_arg subtype.val (f.left_inv a1), let e2 : (f.inv_fun i2).val = a2.val := congr_arg subtype.val (f.left_inv a2), split, {intro h1,rw[← e1,← e2] at h1,exact h.mp h1,}, {intro h2,let h3 := h.mpr h2,rw[e1,e2] at h3,exact h3} end lemma rank_as_card (a : { x // x ∈ s}) : ((rank_equiv s_card).to_fun a).val = card (s.filter (λ x, x < a.val)) := begin let f := rank_equiv s_card, let u := s.filter (λ x, x < a.val), let ut := {x // x ∈ u}, let k := f.to_fun a, have fi_k : f.inv_fun k = a := f.left_inv a, let g_to_fun : ut → fin k.val := begin intro x, let x0 : { x // x ∈ s } := ⟨x.val,(mem_filter.mp x.property).left⟩, let x_lt_a : x0.val < a.val := (mem_filter.mp x.property).right, let i := f.to_fun x0, let i_lt_k : i < k := ((rank_lt s_card) x0 a).mp x_lt_a, let i_lt_k_val : i.val < k.val := begin let h := i_lt_k, dsimp[has_lt.lt,fin.lt] at h, exact h, end, exact ⟨i.val,i_lt_k_val⟩, end, let g_inv_fun : fin k.val → ut := begin intro i, let i0 : fin n := ⟨i.val,lt_trans i.is_lt k.is_lt⟩, have i0_lt_k : i0 < k := by { simp[has_lt.lt,fin.lt], exact i.is_lt,}, let x0 := f.inv_fun i0, let x_lt_a := ((seq_lt s_card) i0 k).mp i0_lt_k, rw[fi_k] at x_lt_a, have x_in_u : x0.val ∈ u := begin apply mem_filter.mpr, exact ⟨x0.property,x_lt_a⟩, end, exact ⟨x0.val,x_in_u⟩, end, have g_left_inv : ∀ x, g_inv_fun (g_to_fun x) = x := begin intro x, dsimp[g_to_fun,g_inv_fun], apply subtype.eq; simp[subtype.val] end, have g_right_inv : ∀ i, g_to_fun (g_inv_fun i) = i := begin intro i, dsimp[g_to_fun,g_inv_fun], apply fin.eq_of_veq; simp[subtype.val] end, let g : ut ≃ fin k.val := ⟨g_to_fun,g_inv_fun,g_left_inv,g_right_inv⟩, let h0 := fintype.card_congr g, let h1 := @finset.card_attach α u, let h2 := fintype.card_fin k.val, exact (h1.symm.trans (h0.trans h2)).symm, end end rank_equiv end finset namespace fintype open finset fintype variables [linear_order α] [decidable_rel (@has_le.le α _)] variables [fintype α] {n : ℕ} (α_card : card α = n) include α_card /- We now give our second version of the fact that any finite, linearly ordered set of size n is order-isomorphic to (fin n). In this version we assume given an instance of (fintype α), which is essentially a proof that the whole type α is finite. From this we build an equivalence from α to (fin n), and again we prove the order properties as separate lemmas. -/ def rank_equiv : α ≃ fin n := begin have h0 : finset.card (@elems α _) = n := α_card, let f := finset.rank_equiv h0, let to_fun : α → fin n := λ a, f.to_fun ⟨a,mem_univ a⟩, let inv_fun : fin n → α := λ i, (f.inv_fun i).val, have left_inv : ∀ a : α, inv_fun (to_fun a) = a := λ a, congr_arg subtype.val (f.left_inv ⟨a,mem_univ a⟩), have right_inv : ∀ i : fin n, to_fun (inv_fun i) = i := begin intro i, have e : f.inv_fun i = ⟨inv_fun i,mem_univ _⟩ := by {apply subtype.eq,simp[inv_fun]}, dsimp[inv_fun,to_fun],simp[e] end, exact ⟨to_fun,inv_fun,left_inv,right_inv⟩, end lemma seq_le (i1 i2 : fin n) : i1 ≤ i2 ↔ (rank_equiv α_card).inv_fun i1 ≤ (rank_equiv α_card).inv_fun i2 := (seq_le α_card) i1 i2 lemma seq_lt (i1 i2 : fin n) : i1 < i2 ↔ (rank_equiv α_card).inv_fun i1 < (rank_equiv α_card).inv_fun i2 := (seq_lt α_card) i1 i2 lemma rank_le (a1 a2 : α) : a1 ≤ a2 ↔ (rank_equiv α_card).to_fun a1 ≤ (rank_equiv α_card).to_fun a2 := (rank_le α_card) ⟨a1,mem_univ a1⟩ ⟨a2,mem_univ a2⟩ lemma rank_lt (a1 a2 : α) : a1 < a2 ↔ (rank_equiv α_card).to_fun a1 < (rank_equiv α_card).to_fun a2 := (rank_lt α_card) ⟨a1,mem_univ a1⟩ ⟨a2,mem_univ a2⟩ end fintype namespace fin /- The only strictly increasing self-map of (fin n) is the identity -/ lemma rigid {n : ℕ} {f : fin n → fin n} (f_mono : ∀ {i1 i2 : fin n}, i1 < i2 → (f i1) < (f i2)) : ∀ (i : fin n), f i = i := begin induction n with n0 ih, {intro i,exact fin.elim0 i}, { let f0 : fin n0 → fin n0 := begin intro i0, let h0 := ne_of_lt (lt_of_le_of_lt (fin.zero_le (f 0)) (f_mono (@fin.zero_lt_succ n0 i0))), exact fin.pred (f i0.succ) h0.symm, end, have succ_f0 : ∀ (i0 : fin n0), (f0 i0).succ = f i0.succ := begin intro i0, let h0 := ne_of_lt (lt_of_le_of_lt (fin.zero_le (f 0)) (f_mono (@fin.zero_lt_succ n0 i0))), exact fin.succ_pred (f i0.succ) h0.symm, end, have f0_mono : ∀ {i1 i2 : fin n0}, i1 < i2 → (f0 i1) < (f0 i2) := begin intros i1 i2 i1_lt_i2, let h0 := f_mono (fin.succ_lt_succ i1_lt_i2), rw[← (succ_f0 i1)] at h0, rw[← (succ_f0 i2)] at h0, exact fin.lt_of_succ_lt_succ h0, end, let f0_id := ih @f0_mono, have f_zero_a : ∀ (j : fin n0.succ), f 0 = j → j = 0 := begin intros j e, cases j with j_val j_is_lt, cases j_val with j0_val, {refl}, { exfalso, have j0_is_lt : j0_val < n0 := nat.lt_of_succ_lt_succ j_is_lt, let j0 : fin n0 := ⟨j0_val,j0_is_lt⟩, let j := j0.succ, have h0 : f j = j := (succ_f0 j0).symm.trans (congr_arg fin.succ (f0_id j0)), have h1 : f 0 < f j := f_mono (@fin.zero_lt_succ n0 j0), have h2 : j < f j := @eq.subst (fin n0.succ) (λ k, k < f j) _ _ e h1, exact (ne_of_lt h2) h0.symm, } end, have f_zero : f 0 = 0 := f_zero_a (f 0) rfl, intro i, cases i with i_val i_is_lt, cases i_val with i0_val, {exact f_zero,}, { have i0_is_lt : i0_val < n0 := nat.lt_of_succ_lt_succ i_is_lt, let h0 := congr_arg fin.succ (f0_id ⟨i0_val,i0_is_lt⟩), let h1 := succ_f0 ⟨i0_val,i0_is_lt⟩, let h2 := h1.symm.trans h0, exact h2, } } end end fin
7cc5ca88f0c0e65279c36b1ef4c2c00cc6bd49c5
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/algebra/category/Mon/colimits.lean
66c14bed4141b397835d66ccba559acb16bdd43c
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
7,799
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 algebra.category.Mon.basic import category_theory.limits.limits import category_theory.limits.concrete_category /-! # The category of monoids has all colimits. We do this construction knowing nothing about monoids. In particular, I want to claim that this file could be produced by a python script that just looks at the output of `#print monoid`: -- structure monoid : Type u → Type u -- fields: -- monoid.mul : Π {α : Type u} [c : monoid α], α → α → α -- monoid.mul_assoc : ∀ {α : Type u} [c : monoid α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) -- monoid.one : Π (α : Type u) [c : monoid α], α -- monoid.one_mul : ∀ {α : Type u} [c : monoid α] (a : α), 1 * a = a -- monoid.mul_one : ∀ {α : Type u} [c : monoid α] (a : α), a * 1 = a and if we'd fed it the output of `#print comm_ring`, this file would instead build colimits of commutative rings. A slightly bolder claim is that we could do this with tactics, as well. -/ universes v open category_theory open category_theory.limits namespace Mon.colimits /-! We build the colimit of a diagram in `Mon` by constructing the free monoid on the disjoint union of all the monoids in the diagram, then taking the quotient by the monoid laws within each monoid, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ Mon.{v}) /-- An inductive type representing all monoid expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | one : prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.one⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the monoid laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' ((F.map f) x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) | one : Π (j), relation (of j 1) one -- Then one relation per argument of each operation | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x /-- The setoid corresponding to monoid expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `Mon`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance monoid_colimit_type : monoid (colimit_type F) := { mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, one := begin exact quot.mk _ one end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end } @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled monoid giving the colimit of a diagram. -/ def colimit : Mon := ⟨colimit_type F, by apply_instance⟩ /-- The function from a given monoid in the diagram to the colimit monoid. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := quot.sound (relation.one _), map_mul' := λ x y, quot.sound (relation.mul _ _ _) } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit monoid. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F, } }. /-- The function from the free monoid on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | one := 1 | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit monoid to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { rw cocone.naturality_concrete, }, -- mul { rw monoid_hom.map_mul ((s.ι).app r_j) }, -- one { erw monoid_hom.map_one ((s.ι).app r) }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- mul_assoc { rw mul_assoc, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, } } end /-- The monoid homomorphism from the colimit monoid to the cone point of any other cocone. -/ @[simps] def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp only [desc_morphism, quot_one], erw monoid_hom.map_one m, refl, }, { simp only [desc_morphism, quot_mul], erw monoid_hom.map_mul m, rw [x_ih_a, x_ih_a_1], refl, }, refl end }. instance has_colimits_Mon : has_colimits.{v} Mon.{v} := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end Mon.colimits
707f83cb6652db503ad442438e18f1429ffc25ce
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_2045.lean
f7d5a3982622d801ddb9921cd8bf63fa20fb0d9e
[]
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
135
lean
import topology.metric_space.basic variables {X : Type*} [metric_space X] -- BEGIN example (x y : X) : 0 ≤ dist x y := sorry -- END
2e8ac1c74cc8bce583015a4be219f8a5e41edf1a
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/enat.lean
fa07a63f87ae458d91f6f6de801038155a70e29b
[ "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
19,796
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.hom.equiv import data.part import tactic.norm_num /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊤`. ## Main definitions The following instances are defined: * `ordered_add_comm_monoid enat` * `canonically_ordered_add_monoid enat` There is no additive analogue of `monoid_with_zero`; if there were then `enat` could be an `add_monoid_with_top`. * `to_with_top` : the map from `enat` to `with_top ℕ`, with theorems that it plays well with `+` and `≤`. * `with_top_add_equiv : enat ≃+ with_top ℕ` * `with_top_order_iso : enat ≃o with_top ℕ` ## Implementation details `enat` is defined to be `part ℕ`. `+` and `≤` are defined on `enat`, but there is an issue with `*` because it's not clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous so there is no `-` defined on `enat`. Before the `open_locale classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`, followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`. ## Tags enat, with_top ℕ -/ open part (hiding some) /-- Type of natural numbers with infinity (`⊤`) -/ def enat : Type := part ℕ namespace enat /-- The computable embedding `ℕ → enat`. This coincides with the coercion `coe : ℕ → enat`, see `enat.some_eq_coe`. However, `coe` is noncomputable so `some` is preferable when computability is a concern. -/ def some : ℕ → enat := part.some instance : has_zero enat := ⟨some 0⟩ instance : inhabited enat := ⟨0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance (n : ℕ) : decidable (some n).dom := is_true trivial lemma some_eq_coe (n : ℕ) : some n = n := begin induction n with n ih, { refl }, apply part.ext', { show true ↔ ((n : enat).dom ∧ true), rw [← ih, and_true], exact iff.rfl }, { intros h H, show n.succ = (n : enat).get H.1 + 1, rw [nat.cast_succ] at H, revert H, simp only [← ih], intro, refl }, end @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := by simpa only [← some_eq_coe] using part.some_inj @[simp] lemma dom_some (x : ℕ) : (some x).dom := trivial @[simp] lemma dom_coe (x : ℕ) : (x : enat).dom := by rw [← some_eq_coe]; trivial instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, part.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, part.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, part.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, part.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ lemma le_def (x y : enat) : x ≤ y ↔ ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy := iff.rfl @[elab_as_eliminator] protected lemma cases_on' {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P (some n)) → P a := part.induction_on @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := by { simp only [← some_eq_coe], exact enat.cases_on' } @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := part.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := by { rw [← some_eq_coe], exact part.ext' (iff_of_true trivial h) (λ _ _, rfl) } @[simp, norm_cast] lemma get_coe' (x : ℕ) (h : (x : enat).dom) : get (x : enat) h = x := by rw [← coe_inj, coe_get] lemma get_coe {x : ℕ} : get (x : enat) (dom_coe x) = x := get_coe' _ _ lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := by { simp only [← some_eq_coe] at h ⊢, refl } @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma get_eq_iff_eq_some {a : enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some lemma get_eq_iff_eq_coe {a : enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some, some_eq_coe] lemma dom_of_le_of_dom {x y : enat} : x ≤ y → y.dom → x.dom := λ ⟨h, _⟩, h lemma dom_of_le_some {x : enat} {y : ℕ} (h : x ≤ some y) : x.dom := dom_of_le_of_dom h trivial lemma dom_of_le_coe {x : enat} {y : ℕ} (h : x ≤ y) : x.dom := by { rw [← some_eq_coe] at h, exact dom_of_le_some h } instance decidable_le (x y : enat) [decidable x.dom] [decidable y.dom] : decidable (x ≤ y) := if hx : x.dom then decidable_of_decidable_of_iff (show decidable (∀ (hy : (y : enat).dom), x.get hx ≤ (y : enat).get hy), from forall_prop_decidable _) $ by { dsimp [(≤)], simp only [hx, exists_prop_of_true, forall_true_iff] } else if hy : y.dom then is_false $ λ h, hx $ dom_of_le_of_dom h hy else is_true ⟨λ h, (hy h).elim, λ h, (hy h).elim⟩ /-- The coercion `ℕ → enat` preserves `0` and addition. -/ def coe_hom : ℕ →+ enat := ⟨coe, nat.cast_zero, nat.cast_add⟩ @[simp] lemma coe_coe_hom : ⇑coe_hom = coe := rfl instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_rfl⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, part.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } lemma lt_def (x y : enat) : x < y ↔ ∃ (hx : x.dom), ∀ (hy : y.dom), x.get hx < y.get hy := begin rw [lt_iff_le_not_le, le_def, le_def, not_exists], split, { rintro ⟨⟨hyx, H⟩, h⟩, by_cases hx : x.dom, { use hx, intro hy, specialize H hy, specialize h (λ _, hy), rw not_forall at h, cases h with hx' h, rw not_le at h, exact h }, { specialize h (λ hx', (hx hx').elim), rw not_forall at h, cases h with hx' h, exact (hx hx').elim } }, { rintro ⟨hx, H⟩, exact ⟨⟨λ _, hx, λ hy, (H hy).le⟩, λ hxy h, not_lt_of_le (h _) (H _)⟩ } end @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := by { rw [← some_eq_coe, ← some_eq_coe], exact ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ } @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] @[simp] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} lemma le_coe_iff (x : enat) (n : ℕ) : x ≤ n ↔ ∃ h : x.dom, x.get h ≤ n := begin rw [← some_eq_coe], show (∃ (h : true → x.dom), _) ↔ ∃ h : x.dom, x.get h ≤ n, simp only [forall_prop_of_true, some_eq_coe, dom_coe, get_coe'] end lemma lt_coe_iff (x : enat) (n : ℕ) : x < n ↔ ∃ h : x.dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_coe', dom_coe] lemma coe_le_iff (n : ℕ) (x : enat) : (n : enat) ≤ x ↔ ∀ h : x.dom, n ≤ x.get h := begin rw [← some_eq_coe], simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end lemma coe_lt_iff (n : ℕ) (x : enat) : (n : enat) < x ↔ ∀ h : x.dom, n < x.get h := begin rw [← some_eq_coe], simp only [lt_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end protected lemma zero_lt_one : (0 : enat) < 1 := by { norm_cast, norm_num } instance semilattice_sup : semilattice_sup enat := { sup := (⊔), le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_bot : order_bot enat := { bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩ } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩ } lemma dom_of_lt {x y : enat} : x < y → x.dom := enat.cases_on x not_top_lt $ λ _ _, dom_coe _ lemma top_eq_none : (⊤ : enat) = none := rfl @[simp] lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := ne.lt_top (λ h, absurd (congr_arg dom h) $ by simpa only [dom_coe] using true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃ (n : ℕ), x = n := by simpa only [← some_eq_coe] using part.ne_none_iff lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 part.eq_none_iff'.symm lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma eq_top_iff_forall_lt (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) < x := begin split, { rintro rfl n, exact coe_lt_top _ }, { contrapose!, rw ne_top_iff, rintro ⟨n, rfl⟩, exact ⟨n, irrefl _⟩ } end lemma eq_top_iff_forall_le (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) ≤ x := (eq_top_iff_forall_lt x).trans ⟨λ h n, (h n).le, λ h n, lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x (by simp only [iff_true, le_top, coe_lt_top, ← @nat.cast_zero enat]) $ λ n, by { rw [← nat.cast_zero, ← nat.cast_one, enat.coe_lt_coe, enat.coe_le_coe], refl } instance : is_total enat (≤) := { total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))) } noncomputable instance : linear_order enat := { le_total := is_total.total, decidable_le := classical.dec_rel _, max := (⊔), max_def := @sup_eq_max_default _ _ (id _) _, ..enat.partial_order } instance : bounded_order enat := { ..enat.order_top, ..enat.order_bot } noncomputable instance : lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.semilattice_sup } instance : ordered_add_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro (dom_coe _) (h₁ h.2), λ h, by simpa only [coe_add_get] using add_le_add_left (h₂ _) c⟩), ..enat.linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_add_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← nat.cast_add, coe_inj, add_comm, tsub_add_cancel_of_le (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← nat.cast_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)), ..enat.semilattice_sup, ..enat.order_bot, ..enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, λ h, enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply enat.cases_on a; apply enat.cases_on b; simp; simp only [(nat.cast_add _ _).symm, enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply enat.cases_on a; apply enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)]; simp only [(nat.cast_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [decidable x.dom] : with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom} : to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_some (n : ℕ) : to_with_top (some n) = n := rfl lemma to_with_top_coe (n : ℕ) {_ : decidable (n : enat).dom} : to_with_top n = n := by simp only [← some_eq_coe, ← to_with_top_some] @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := lt_iff_lt_of_le_iff_le to_with_top_le end with_top section with_top_equiv open_locale classical @[simp] lemma to_with_top_add {x y : enat} : to_with_top (x + y) = to_with_top x + to_with_top y := by apply enat.cases_on y; apply enat.cases_on x; simp [← nat.cast_add, ← with_top.coe_add] /-- `equiv` between `enat` and `with_top ℕ` (for the order isomorphism see `with_top_order_iso`). -/ noncomputable def with_top_equiv : enat ≃ with_top ℕ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (option.some n) := coe n | none := ⊤ end, left_inv := λ x, by apply enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := by simpa only [nat.cast_zero] using with_top_equiv_coe 0 @[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt /-- `to_with_top` induces an order isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_order_iso : enat ≃o with_top ℕ := { map_rel_iff' := λ _ _, with_top_equiv_le, .. with_top_equiv} @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp /-- `to_with_top` induces an additive monoid isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_add_equiv : enat ≃+ with_top ℕ := { map_add' := λ x y, by simp only [with_top_equiv]; convert to_with_top_add, ..with_top_equiv} end with_top_equiv lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ section find variables (P : ℕ → Prop) [decidable_pred P] /-- The smallest `enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find : enat := ⟨∃ n, P n, nat.find⟩ @[simp] lemma find_get (h : (find P).dom) : (find P).get h = nat.find h := rfl lemma find_dom (h : ∃ n, P n) : (find P).dom := h lemma lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : enat) < find P := begin rw coe_lt_iff, intro h', rw find_get, have := @nat.find_spec P _ h', contrapose! this, exact h _ this end lemma lt_find_iff (n : ℕ) : (n : enat) < find P ↔ (∀ m ≤ n, ¬P m) := begin refine ⟨_, lt_find P n⟩, intros h m hm, by_cases H : (find P).dom, { apply nat.find_min H, rw coe_lt_iff at h, specialize h H, exact lt_of_le_of_lt hm h }, { exact not_exists.mp H m } end lemma find_le (n : ℕ) (h : P n) : find P ≤ n := by { rw le_coe_iff, refine ⟨⟨_, h⟩, @nat.find_min' P _ _ _ h⟩ } lemma find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n := (eq_top_iff_forall_lt _).trans ⟨λ h n, (lt_find_iff P n).mp (h n) _ le_rfl, λ h n, lt_find P n $ λ _ _, h _⟩ end find noncomputable instance : linear_ordered_add_comm_monoid_with_top enat := { top_add' := top_add, .. enat.linear_order, .. enat.ordered_add_comm_monoid, .. enat.order_top } end enat
ba38da1c9216df8e32e870b00885796ae3a9ddfc
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/fibrant_class2.lean
c07ad766d0b7741e6a6caa793ee6db8b52b354e9
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,147
lean
import general_notation inductive fibrant [class] (T : Type) : Type := fibrant_mk : fibrant T axiom pi_fibrant {A : Type} {B : A → Type} [C1 : fibrant A] [C2 : Πx : A, fibrant (B x)] : fibrant (Πx : A, B x) instance pi_fibrant inductive path {A : Type} [fA : fibrant A] (a : A) : A → Type := idpath : path a a axiom path_fibrant {A : Type} [fA : fibrant A] (a b : A) : fibrant (path a b) instance [persistent] path_fibrant notation a ≈ b := path a b definition test {A : Type} [fA : fibrant A] {x y : A} : Π (z : A), y ≈ z → fibrant (x ≈ y → x ≈ z) := take z p, _ definition test2 {A : Type} [fA : fibrant A] {x y : A} : Π (z : A), y ≈ z → fibrant (x ≈ y → x ≈ z) := _ definition test3 {A : Type} [fA : fibrant A] {x y : A} : Π (z : A), y ≈ z → fibrant (x ≈ z) := _ definition test4 {A : Type} [fA : fibrant A] {x y z : A} : fibrant (x ≈ y → x ≈ z) := _ axiom imp_fibrant {A : Type} {B : Type} [C1 : fibrant A] [C2 : fibrant B] : fibrant (A → B) instance imp_fibrant definition test5 {A : Type} [fA : fibrant A] {x y : A} : Π (z : A), y ≈ z → fibrant (x ≈ y → x ≈ z) := _
71a046312c5ec4e282204346c9f2d228dbea873f
05b503addd423dd68145d68b8cde5cd595d74365
/test/ring_exp.lean
5aee6aa7883d2f3aa7a6526e6619c2ea861e2dbc
[ "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
5,953
lean
import tactic.ring_exp import algebra.group_with_zero_power universes u section addition /-! ### `addition` section Test associativity and commutativity of `(+)`. -/ example (a b : ℚ) : a = a := by ring_exp example (a b : ℚ) : a + b = a + b := by ring_exp example (a b : ℚ) : b + a = a + b := by ring_exp example (a b : ℤ) : a + b + b = b + (a + b) := by ring_exp example (a b c : ℕ) : a + b + b + (c + c) = c + (b + c) + (a + b) := by ring_exp end addition section numerals /-! ### `numerals` section Test that numerals behave like rational numbers. -/ example (a : ℕ) : a + 5 + 5 = 0 + a + 10 := by ring_exp example (a : ℤ) : a + 5 + 5 = 0 + a + 10 := by ring_exp example (a : ℚ) : (1/2) * a + (1/2) * a = a := by ring_exp end numerals section multiplication /-! ### `multiplication section` Test that multiplication is associative and commutative. Also test distributivity of `(+)` and `(*)`. -/ example (a : ℕ) : 0 = a * 0 := by ring_exp_eq example (a : ℕ) : a = a * 1 := by ring_exp example (a : ℕ) : a + a = a * 2 := by ring_exp example (a b : ℤ) : a * b = b * a := by ring_exp example (a b : ℕ) : a * 4 * b + a = a * (4 * b + 1) := by ring_exp end multiplication section exponentiation /-! ### `exponentiation` section Test that exponentiation has the correct distributivity properties. -/ example : 0 ^ 1 = 0 := by ring_exp example : 0 ^ 2 = 0 := by ring_exp example (a : ℕ) : a ^ 0 = 1 := by ring_exp example (a : ℕ) : a ^ 1 = a := by ring_exp example (a : ℕ) : a ^ 2 = a * a := by ring_exp example (a b : ℕ) : a ^ b = a ^ b := by ring_exp example (a b : ℕ) : a ^ (b + 1) = a * a ^ b := by ring_exp example (n : ℕ) (a m : ℕ) : a * a^n * m = a^(n+1) * m := by ring_exp example (n : ℕ) (a m : ℕ) : m * a^n * a = a^(n+1) * m := by ring_exp example (n : ℕ) (a m : ℤ) : a * a^n * m = a^(n+1) * m := by ring_exp example (n : ℕ) (m : ℤ) : 2 * 2^n * m = 2^(n+1) * m := by ring_exp example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp example (n m : ℕ) (a : ℤ) : (a ^ n)^m = a^(n * m) := by ring_exp example (n m : ℕ) (a : ℤ) : a^(n^0) = a^1 := by ring_exp example (n : ℕ) : 0^(n + 1) = 0 := by ring_exp example {α} [comm_ring α] (x : α) (k : ℕ) : x ^ (k + 2) = x * x * x^k := by ring_exp example {α} [comm_ring α] (k : ℕ) (x y z : α) : x * (z * (x - y)) + (x * (y * y ^ k) - y * (y * y ^ k)) = (z * x + y * y ^ k) * (x - y) := by ring_exp -- We can represent a large exponent `n` more efficiently than just `n` multiplications: example (a b : ℚ) : (a * b) ^ 1000000 = (b * a) ^ 1000000 := by ring_exp end exponentiation section power_of_sum /-! ### `power_of_sum` section Test that raising a sum to a power behaves like repeated multiplication, if needed. -/ example (a b : ℤ) : (a + b)^2 = a^2 + b^2 + a * b + b * a := by ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp end power_of_sum section negation /-! ### `negation` section Test that negation and subtraction satisfy the expected properties, also in semirings such as `ℕ`. -/ example {α} [comm_ring α] (a : α) : a - a = 0 := by ring_exp_eq example (a : ℤ) : a - a = 0 := by ring_exp example (a : ℤ) : a + - a = 0 := by ring_exp example (a : ℤ) : - a = (-1) * a := by ring_exp example (a b : ℕ) : a - b + a + a = a - b + 2 * a := by ring_exp -- Here, (a - b) is treated as an atom. example (n : ℕ) : n + 1 - 1 = n := by ring_exp! -- But we can force a bit of evaluation anyway. end negation constant f {α} : α → α section complicated /-! ### `complicated` section Test that complicated, real-life expressions also get normalized. -/ example {α : Type} [linear_ordered_field α] (x : α) : 2 * x + 1 * 1 - (2 * f (x + 1 / 2) + 2 * 1) + (1 * 1 - (2 * x - 2 * f (x + 1 / 2))) = 0 := by ring_exp_eq example {α : Type u} [linear_ordered_field α] (x : α) : f (x + 1 / 2) ^ 1 * -2 + (f (x + 1 / 2) ^ 1 * 2 + 0) = 0 := by ring_exp_eq example (x y : ℕ) : x + id y = y + id x := by ring_exp! -- Here, we check that `n - s` is not treated as `n + additive_inverse s`, -- if `s` doesn't have an additive inverse. example (B s n : ℕ) : B * (f s * ((n - s) * f (n - s - 1))) = B * (n - s) * (f s * f (n - s - 1)) := by ring_exp -- This is a somewhat subtle case: `-c/b` is parsed as `(-c)/b`, -- so we can't simply treat both sides of the division as atoms. -- Instead, we follow the `ring` tactic in interpreting `-c / b` as `-c * b⁻¹`, -- with only `b⁻¹` an atom. example {α} [linear_ordered_field α] (a b c : α) : a*(-c/b)*(-c/b) = a*((c/b)*(c/b)) := by ring_exp -- test that `field_simp` works fine with powers and `ring_exp`. example (x y : ℚ) (n : ℕ) (hx : x ≠ 0) (hy : y ≠ 0) : 1/ (2/(x / y))^(2 * n) + y / y^(n+1) - (x/y)^n * (x/(2 * y))^n / 2 ^n = 1/y^n := begin simp [sub_eq_add_neg], field_simp [hx, hy], ring_exp end end complicated section benchmark /-! ### `benchmark` section The `ring_exp` tactic shouldn't be too slow. -/ -- This last example was copied from `data/polynomial.lean`, because it timed out. -- After some optimization, it doesn't. variables {α : Type} [comm_ring α] def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z // x^i - y^i = z*(x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases @pow_sub_pow_factor (k+1) with z hz, existsi z*x + y^(k+1), rw [_root_.pow_succ x, _root_.pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)), ←mul_sub x, hz], ring_exp_eq end -- Another benchmark: bound the growth of the complexity somewhat. example {α} [comm_semiring α] (x : α) : (x + 1) ^ 4 = (1 + x) ^ 4 := by try_for 5000 {ring_exp} example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 10000 {ring_exp} example {α} [comm_semiring α] (x : α) : (x + 1) ^ 8 = (1 + x) ^ 8 := by try_for 15000 {ring_exp} end benchmark
5d33e6e54460892caa25d454f0da00df71068f90
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/predicate_logic/iff.lean
d2da2e30b898dc00024de32727ef71393078afdd
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
1,239
lean
/- Given propositions P and Q, to prove P ↔ Q requires a proof of P → Q and a proof of Q → P. The introduction rule is iff.intro : (P → Q) → (Q → P) → P ↔ Q. -/ #check iff #check @iff.intro /- structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) -/ /- It's a special case of and. The elimination rules are analogous, too. Remember reading the next types that → is right associative. -/ #check @iff.elim_left #check @iff.elim_right /- Example. 1 = 1 ↔ 0 = 0. -/ example : 1 = 1 ↔ 0 = 0 := iff.intro (λ _, rfl) -- ⊢ 1 = 1 → 0 = 0 (λ _, rfl) -- ⊢ 0 = 0 → 1 = 1 /- And so for the eliminators. -/ #check @iff.elim_left #check @iff.elim_right /- Show: ∀ (P Q : Prop), (P ↔ Q) → Q → P. -/ example : ∀ (P Q : Prop), (P ↔ Q) → Q → P := λ P Q h q, -- use what you have to make what you need _ /- General requirement to prove P ↔ Q is to give proofs of P → Q and Q → P to ↔-intro. That is, apply ↔-intro to a proof of P → Q and a proof of Q → P. Thus: iff.intro : (P → Q) → (Q → P) → (P ↔ Q) iff.elim_left : (P ↔ Q) → (P → Q) iff.elim_right : (P ↔ Q) → (Q → P) -/ -- Exercise: Try it to test yourself.
db142307d2f384f9233cf2851d41309854ab24d4
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/forallMetaBounded.lean
78cfc9cd7dc086411747b8c2b30f9feecd5bd8ed
[ "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
400
lean
import Lean open Lean Lean.Meta def Set (α : Type) : Type := α → Prop def Set.empty {α : Type} : Set α := fun a => False def Set.insert (s : Set α) (a : α) : Set α := fun x => x = a ∨ s a #eval show MetaM Unit from do let insertType ← inferType (mkConst `Set.insert) let ⟨mvars, bInfos, resultType⟩ ← forallMetaBoundedTelescope insertType 3 println! "{resultType}"
65900fa22e5d4114d90b153bcdd810f60d62427f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/omega/eq_elim.lean
d73846762eb161ecbece2d20607945649b10fc2b
[ "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,602
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Correctness lemmas for equality elimination. See 5.5 of <http://www.decision-procedures.org/> for details. -/ import tactic.omega.clause open list.func namespace omega def symdiv (i j : int) : int := if (2 * (i % j)) < j then i / j else (i / j) + 1 def symmod (i j : int) : int := if (2 * (i % j)) < j then i % j else (i % j) - j local attribute [semireducible] int.nonneg lemma symmod_add_one_self {i : int} : 0 < i → symmod i (i+1) = -1 := begin intro h1, unfold symmod, rw [int.mod_eq_of_lt (le_of_lt h1) (lt_add_one _), if_neg], simp only [add_comm, add_neg_cancel_left, neg_add_rev, sub_eq_add_neg], have h2 : 2 * i = (1 + 1) * i := rfl, simpa only [h2, add_mul, one_mul, add_lt_add_iff_left, not_lt] using h1 end lemma mul_symdiv_eq {i j : int} : j * (symdiv i j) = i - (symmod i j) := begin unfold symdiv, unfold symmod, by_cases h1 : (2 * (i % j)) < j, { repeat {rw if_pos h1}, rw [int.mod_def, sub_sub_cancel] }, { repeat {rw if_neg h1}, rw [int.mod_def, sub_sub, sub_sub_cancel, mul_add, mul_one] } end lemma symmod_eq {i j : int} : symmod i j = i - j * (symdiv i j) := by rw [mul_symdiv_eq, sub_sub_cancel] /-- (sgm v b as n) is the new value assigned to the nth variable after a single step of equality elimination using valuation v, term ⟨b, as⟩, and variable index n. If v satisfies the initial constraint set, then (v ⟨n ↦ sgm v b as n⟩) satisfies the new constraint set after equality elimination. -/ def sgm (v : nat → int) (b : int) (as : list int) (n : nat) := let a_n : int := get n as in let m : int := a_n + 1 in ((symmod b m) + (coeffs.val v (as.map (λ x, symmod x m)))) / m open_locale list.func def rhs : nat → int → list int → term | n b as := let m := get n as + 1 in ⟨(symmod b m), (as.map (λ x, symmod x m)) {n ↦ -m}⟩ lemma rhs_correct_aux {v : nat → int} {m : int} {as : list int} : ∀ {k}, ∃ d, (m * d + coeffs.val_between v (as.map (λ (x : ℤ), symmod x m)) 0 k = coeffs.val_between v as 0 k) | 0 := begin existsi (0 : int), simp only [add_zero, mul_zero, coeffs.val_between] end | (k+1) := begin simp only [zero_add, coeffs.val_between, list.map], cases @rhs_correct_aux k with d h1, rw ← h1, by_cases hk : k < as.length, { rw [get_map hk, symmod_eq, sub_mul], existsi (d + (symdiv (get k as) m * v k)), ring }, { rw not_lt at hk, repeat {rw get_eq_default_of_le}, existsi d, rw add_assoc, exact hk, simp only [hk, list.length_map] } end open_locale omega lemma rhs_correct {v : nat → int} {b : int} {as : list int} (n : nat) : 0 < get n as → 0 = term.val v (b,as) → v n = term.val (v ⟨n ↦ sgm v b as n⟩) (rhs n b as) := begin intros h0 h1, let a_n := get n as, let m := a_n + 1, have h3 : m ≠ 0, { apply ne_of_gt, apply lt_trans h0, simp [a_n, m] }, have h2 : m * (sgm v b as n) = (symmod b m) + coeffs.val v (as.map (λ x, symmod x m)), { simp only [sgm, mul_comm m], rw [int.div_mul_cancel], have h4 : ∃ c, m * c + (symmod b (get n as + 1) + coeffs.val v (as.map (λ (x : ℤ), symmod x m))) = term.val v (b,as), { have h5: ∃ d, m * d + (coeffs.val v (as.map (λ x, symmod x m))) = coeffs.val v as, { simp only [coeffs.val, list.length_map], apply rhs_correct_aux }, cases h5 with d h5, rw symmod_eq, existsi (symdiv b m + d), unfold term.val, rw ← h5, simp only [term.val, mul_add, add_mul, m, a_n], ring }, cases h4 with c h4, rw [dvd_add_iff_right (dvd_mul_right m c), h4, ← h1], apply dvd_zero }, apply calc v n = -(m * sgm v b as n) + (symmod b m) + (coeffs.val_except n v (as.map (λ x, symmod x m))) : begin rw [h2, ← coeffs.val_except_add_eq n], have hn : n < as.length, { by_contra hc, rw not_lt at hc, rw (get_eq_default_of_le n hc) at h0, cases h0 }, rw get_map hn, simp only [a_n, m], rw [add_comm, symmod_add_one_self h0], ring end ... = term.val (v⟨n↦sgm v b as n⟩) (rhs n b as) : begin unfold rhs, unfold term.val, rw [← coeffs.val_except_add_eq n, get_set, update_eq], have h2 : ∀ a b c : int, a + b + c = b + (c + a) := by {intros, ring}, rw (h2 (- _)), apply fun_mono_2 rfl, apply fun_mono_2, { rw coeffs.val_except_update_set }, { simp only [m, a_n], ring } end end def sym_sym (m b : int) : int := symdiv b m + symmod b m def coeffs_reduce : nat → int → list int → term | n b as := let a := get n as in let m := a + 1 in (sym_sym m b, (as.map (sym_sym m)) {n ↦ -a}) lemma coeffs_reduce_correct {v : nat → int} {b : int} {as : list int} {n : nat} : 0 < get n as → 0 = term.val v (b,as) → 0 = term.val (v ⟨n ↦ sgm v b as n⟩) (coeffs_reduce n b as) := begin intros h1 h2, let a_n := get n as, let m := a_n + 1, have h3 : m ≠ 0, { apply ne_of_gt, apply lt_trans h1, simp only [m, lt_add_iff_pos_right] }, have h4 : 0 = (term.val (v⟨n↦sgm v b as n⟩) (coeffs_reduce n b as)) * m := calc 0 = term.val v (b,as) : h2 ... = b + coeffs.val_except n v as + a_n * ((rhs n b as).val (v⟨n ↦ sgm v b as n⟩)) : begin unfold term.val, rw [← coeffs.val_except_add_eq n, rhs_correct n h1 h2], simp only [a_n, add_assoc], end ... = -(m * a_n * sgm v b as n) + (b + a_n * (symmod b m)) + (coeffs.val_except n v as + a_n * coeffs.val_except n v (as.map (λ x, symmod x m))) : begin simp only [term.val, rhs, mul_add, m, a_n, add_assoc, add_right_inj, add_comm, add_left_comm], rw [← coeffs.val_except_add_eq n, get_set, update_eq, mul_add], apply fun_mono_2, { rw coeffs.val_except_eq_val_except update_eq_of_ne (get_set_eq_of_ne _) }, ring, end ... = -(m * a_n * sgm v b as n) + (b + a_n * (symmod b m)) + coeffs.val_except n v (as.map (λ a_i, a_i + a_n * (symmod a_i m))) : begin apply fun_mono_2 rfl, simp only [coeffs.val_except, mul_add], repeat {rw ← coeffs.val_between_map_mul}, rw add_add_add_comm, have h5 : add as (list.map (has_mul.mul a_n) (list.map (λ (x : ℤ), symmod x (get n as + 1)) as)) = list.map (λ (a_i : ℤ), a_i + a_n * symmod a_i m) as, { rw [list.map_map, ←map_add_map], apply fun_mono_2, { have h5 : (λ x : int, x) = id, { rw function.funext_iff, intro x, refl }, rw [h5, list.map_id] }, { apply fun_mono_2 _ rfl, rw function.funext_iff, intro x, simp only [m] } }, simp only [list.length_map], repeat { rw [← coeffs.val_between_add, h5] }, end ... = -(m * a_n * sgm v b as n) + (m * sym_sym m b) + coeffs.val_except n v (as.map (λ a_i, m * sym_sym m a_i)) : begin repeat {rw add_assoc}, apply fun_mono_2, refl, rw ← add_assoc, have h4 : ∀ (x : ℤ), x + a_n * symmod x m = m * sym_sym m x, { intro x, have h5 : a_n = m - 1, { simp only [m], rw add_sub_cancel }, rw [h5, sub_mul, one_mul, add_sub, add_comm, add_sub_assoc, ← mul_symdiv_eq], simp only [sym_sym, mul_add, add_comm] }, apply fun_mono_2 (h4 _), apply coeffs.val_except_eq_val_except; intros x h5, refl, apply congr_arg, apply fun_mono_2 _ rfl, rw function.funext_iff, apply h4 end ... = (-(a_n * sgm v b as n) + (sym_sym m b) + coeffs.val_except n v (as.map (sym_sym m))) * m : begin simp only [add_mul _ _ m], apply fun_mono_2, ring, simp only [coeffs.val_except, add_mul _ _ m], apply fun_mono_2, { rw [mul_comm _ m, ← coeffs.val_between_map_mul, list.map_map] }, simp only [list.length_map, mul_comm _ m], rw [← coeffs.val_between_map_mul, list.map_map] end ... = (sym_sym m b + (coeffs.val_except n v (as.map (sym_sym m)) + (-a_n * sgm v b as n))) * m : by ring ... = (term.val (v ⟨n ↦ sgm v b as n⟩) (coeffs_reduce n b as)) * m : begin simp only [coeffs_reduce, term.val, m, a_n], rw [← coeffs.val_except_add_eq n, coeffs.val_except_update_set, get_set, update_eq] end, rw [← int.mul_div_cancel (term.val _ _) h3, ← h4, int.zero_div] end -- Requires : t1.coeffs[m] = 1 def cancel (m : nat) (t1 t2 : term) : term := term.add (t1.mul (-(get m (t2.snd)))) t2 def subst (n : nat) (t1 t2 : term) : term := term.add (t1.mul (get n t2.snd)) (t2.fst, t2.snd {n ↦ 0}) lemma subst_correct {v : nat → int} {b : int} {as : list int} {t : term} {n : nat} : 0 < get n as → 0 = term.val v (b,as) → term.val v t = term.val (v ⟨n ↦ sgm v b as n⟩) (subst n (rhs n b as) t) := begin intros h1 h2, simp only [subst, term.val, term.val_add, term.val_mul], rw ← rhs_correct _ h1 h2, cases t with b' as', simp only [term.val], have h3 : coeffs.val (v ⟨n ↦ sgm v b as n⟩) (as' {n ↦ 0}) = coeffs.val_except n v as', { rw [← coeffs.val_except_add_eq n, get_set, zero_mul, add_zero, coeffs.val_except_update_set] }, rw [h3, ← coeffs.val_except_add_eq n], ring end /-- The type of equality elimination rules. -/ @[derive has_reflect, derive inhabited] inductive ee : Type | drop : ee | nondiv : int → ee | factor : int → ee | neg : ee | reduce : nat → ee | cancel : nat → ee namespace ee def repr : ee → string | drop := "↓" | (nondiv i) := i.repr ++ "∤" | (factor i) := "/" ++ i.repr | neg := "-" | (reduce n) := "≻" ++ n.repr | (cancel n) := "+" ++ n.repr instance has_repr : has_repr ee := ⟨repr⟩ meta instance has_to_format : has_to_format ee := ⟨λ x, x.repr⟩ end ee /-- Apply a given sequence of equality elimination steps to a clause. -/ def eq_elim : list ee → clause → clause | [] ([], les) := ([],les) | [] ((_::_), les) := ([],[]) | (_::_) ([], les) := ([],[]) | (ee.drop::es) ((eq::eqs), les) := eq_elim es (eqs, les) | (ee.neg::es) ((eq::eqs), les) := eq_elim es ((eq.neg::eqs), les) | (ee.nondiv i::es) ((b,as)::eqs, les) := if ¬(i ∣ b) ∧ (∀ x ∈ as, i ∣ x) then ([],[⟨-1,[]⟩]) else ([],[]) | (ee.factor i::es) ((b,as)::eqs, les) := if (i ∣ b) ∧ (∀ x ∈ as, i ∣ x) then eq_elim es ((term.div i (b,as)::eqs), les) else ([],[]) | (ee.reduce n::es) ((b,as)::eqs, les) := if 0 < get n as then let eq' := coeffs_reduce n b as in let r := rhs n b as in let eqs' := eqs.map (subst n r) in let les' := les.map (subst n r) in eq_elim es ((eq'::eqs'), les') else ([],[]) | (ee.cancel m::es) ((eq::eqs), les) := eq_elim es ((eqs.map (cancel m eq)), (les.map (cancel m eq))) open tactic lemma sat_empty : clause.sat ([],[]) := ⟨λ _,0, ⟨dec_trivial, dec_trivial⟩⟩ lemma sat_eq_elim : ∀ {es : list ee} {c : clause}, c.sat → (eq_elim es c).sat | [] ([], les) h := h | (e::_) ([], les) h := by {cases e; simp only [eq_elim]; apply sat_empty} | [] ((_::_), les) h := sat_empty | (ee.drop::es) ((eq::eqs), les) h1 := begin apply (@sat_eq_elim es _ _), rcases h1 with ⟨v,h1,h2⟩, refine ⟨v, list.forall_mem_of_forall_mem_cons h1, h2⟩ end | (ee.neg::es) ((eq::eqs), les) h1 := begin simp only [eq_elim], apply sat_eq_elim, cases h1 with v h1, existsi v, cases h1 with hl hr, apply and.intro _ hr, rw list.forall_mem_cons at *, apply and.intro _ hl.right, rw term.val_neg, rw ← hl.left, refl end | (ee.nondiv i::es) ((b,as)::eqs, les) h1 := begin unfold eq_elim, by_cases h2 : (¬i ∣ b ∧ ∀ (x : ℤ), x ∈ as → i ∣ x), { exfalso, cases h1 with v h1, have h3 : 0 = b + coeffs.val v as := h1.left _ (or.inl rfl), have h4 : i ∣ coeffs.val v as := coeffs.dvd_val h2.right, have h5 : i ∣ b + coeffs.val v as := by { rw ← h3, apply dvd_zero }, rw ← dvd_add_iff_left h4 at h5, apply h2.left h5 }, rw if_neg h2, apply sat_empty end | (ee.factor i::es) ((b,as)::eqs, les) h1 := begin simp only [eq_elim], by_cases h2 : (i ∣ b) ∧ (∀ x ∈ as, i ∣ x), { rw if_pos h2, apply sat_eq_elim, cases h1 with v h1, existsi v, cases h1 with h3 h4, apply and.intro _ h4, rw list.forall_mem_cons at *, cases h3 with h5 h6, apply and.intro _ h6, rw [term.val_div h2.left h2.right, ← h5, int.zero_div] }, { rw if_neg h2, apply sat_empty } end | (ee.reduce n::es) ((b,as)::eqs, les) h1 := begin simp only [eq_elim], by_cases h2 : 0 < get n as, tactic.rotate 1, { rw if_neg h2, apply sat_empty }, rw if_pos h2, apply sat_eq_elim, cases h1 with v h1, existsi v ⟨n ↦ sgm v b as n⟩, cases h1 with h1 h3, rw list.forall_mem_cons at h1, cases h1 with h4 h5, constructor, { rw list.forall_mem_cons, constructor, { apply coeffs_reduce_correct h2 h4 }, { intros x h6, rw list.mem_map at h6, cases h6 with t h6, cases h6 with h6 h7, rw [← h7, ← subst_correct h2 h4], apply h5 _ h6 } }, { intros x h6, rw list.mem_map at h6, cases h6 with t h6, cases h6 with h6 h7, rw [← h7, ← subst_correct h2 h4], apply h3 _ h6 } end | (ee.cancel m::es) ((eq::eqs), les) h1 := begin unfold eq_elim, apply sat_eq_elim, cases h1 with v h1, existsi v, cases h1 with h1 h2, rw list.forall_mem_cons at h1, cases h1 with h1 h3, constructor; intros t h4; rw list.mem_map at h4; rcases h4 with ⟨s,h4,h5⟩; rw ← h5; simp only [term.val_add, term.val_mul, cancel]; rw [← h1, mul_zero, zero_add], { apply h3 _ h4 }, { apply h2 _ h4 } end /-- If the result of equality elimination is unsatisfiable, the original clause is unsatisfiable. -/ lemma unsat_of_unsat_eq_elim (ee : list ee) (c : clause) : (eq_elim ee c).unsat → c.unsat := by {intros h1 h2, apply h1, apply sat_eq_elim h2} end omega
ef3926125aaa25ba0544ee98b6f4bf5605e16798
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/limits/preserves.lean
766b2ad7421e3e50e5c957b53a8c367938779f8e
[ "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
11,321
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.limits.limits /-! # Preservation and reflection of (co)limits. There are various distinct notions of "preserving limits". The one we aim to capture here is: A functor F : C → D "preserves limits" if it sends every limit cone in C to a limit cone in D. Informally, F preserves all the limits which exist in C. Note that: * Of course, we do not want to require F to *strictly* take chosen limit cones of C to chosen limit cones of D. Indeed, the above definition makes no reference to a choice of limit cones so it makes sense without any conditions on C or D. * Some diagrams in C may have no limit. In this case, there is no condition on the behavior of F on such diagrams. There are other notions (such as "flat functor") which impose conditions also on diagrams in C with no limits, but these are not considered here. In order to be able to express the property of preserving limits of a certain form, we say that a functor F preserves the limit of a diagram K if F sends every limit cone on K to a limit cone. This is vacuously satisfied when K does not admit a limit, which is consistent with the above definition of "preserves limits". -/ open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v} C] variables {D : Type u₂} [𝒟 : category.{v} D] include 𝒞 𝒟 variables {J : Type v} [small_category J] {K : J ⥤ C} class preserves_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cone K}, is_limit c → is_limit (F.map_cone c)) class preserves_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cocone K}, is_colimit c → is_colimit (F.map_cocone c)) /-- A functor which preserves limits preserves chosen limits up to isomorphism. -/ def preserves_limit_iso (K : J ⥤ C) [has_limit.{v} K] (F : C ⥤ D) [has_limit.{v} (K ⋙ F)] [preserves_limit K F] : F.obj (limit K) ≅ limit (K ⋙ F) := is_limit.cone_point_unique_up_to_iso (preserves_limit.preserves (limit.is_limit K)) (limit.is_limit (K ⋙ F)) /-- A functor which preserves colimits preserves chosen colimits up to isomorphism. -/ def preserves_colimit_iso (K : J ⥤ C) [has_colimit.{v} K] (F : C ⥤ D) [has_colimit.{v} (K ⋙ F)] [preserves_colimit K F] : F.obj (colimit K) ≅ colimit (K ⋙ F) := is_colimit.cone_point_unique_up_to_iso (preserves_colimit.preserves (colimit.is_colimit K)) (colimit.is_colimit (K ⋙ F)) class preserves_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_limit : Π {K : J ⥤ C}, preserves_limit K F) class preserves_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_colimit : Π {K : J ⥤ C}, preserves_colimit K F) class preserves_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_limits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_limits_of_shape J F) class preserves_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_colimits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_colimits_of_shape J F) attribute [instance, priority 100] -- see Note [lower instance priority] preserves_limits_of_shape.preserves_limit preserves_limits.preserves_limits_of_shape preserves_colimits_of_shape.preserves_colimit preserves_colimits.preserves_colimits_of_shape instance preserves_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_limits_subsingleton (F : C ⥤ D) : subsingleton (preserves_limits F) := by { split, intros, cases a, cases b, cc } instance preserves_colimits_subsingleton (F : C ⥤ D) : subsingleton (preserves_colimits F) := by { split, intros, cases a, cases b, cc } omit 𝒟 instance id_preserves_limits : preserves_limits (𝟭 C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_preserves_colimits : preserves_colimits (𝟭 C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } include 𝒟 section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) local attribute [elab_simple] preserves_limit.preserves preserves_colimit.preserves instance comp_preserves_limit [preserves_limit K F] [preserves_limit (K ⋙ F) G] : preserves_limit K (F ⋙ G) := ⟨λ c h, preserves_limit.preserves (preserves_limit.preserves h)⟩ instance comp_preserves_colimit [preserves_colimit K F] [preserves_colimit (K ⋙ F) G] : preserves_colimit K (F ⋙ G) := ⟨λ c h, preserves_colimit.preserves (preserves_colimit.preserves h)⟩ end /-- If F preserves one limit cone for the diagram K, then it preserves any limit cone for K. -/ def preserves_limit_of_preserves_limit_cone {F : C ⥤ D} {t : cone K} (h : is_limit t) (hF : is_limit (F.map_cone t)) : preserves_limit K F := ⟨λ t' h', is_limit.of_iso_limit hF (functor.map_iso _ (is_limit.unique_up_to_iso h h'))⟩ /-- If F preserves one colimit cocone for the diagram K, then it preserves any colimit cocone for K. -/ def preserves_colimit_of_preserves_colimit_cocone {F : C ⥤ D} {t : cocone K} (h : is_colimit t) (hF : is_colimit (F.map_cocone t)) : preserves_colimit K F := ⟨λ t' h', is_colimit.of_iso_colimit hF (functor.map_iso _ (is_colimit.unique_up_to_iso h h'))⟩ /- A functor F : C → D reflects limits if whenever the image of a cone under F is a limit cone in D, the cone was already a limit cone in C. Note that again we do not assume a priori that D actually has any limits. -/ class reflects_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cone K}, is_limit (F.map_cone c) → is_limit c) class reflects_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cocone K}, is_colimit (F.map_cocone c) → is_colimit c) class reflects_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_limit : Π {K : J ⥤ C}, reflects_limit K F) class reflects_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_colimit : Π {K : J ⥤ C}, reflects_colimit K F) class reflects_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_limits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_limits_of_shape J F) class reflects_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_colimits_of_shape J F) instance reflects_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_limits_subsingleton (F : C ⥤ D) : subsingleton (reflects_limits F) := by { split, intros, cases a, cases b, cc } instance reflects_colimits_subsingleton (F : C ⥤ D) : subsingleton (reflects_colimits F) := by { split, intros, cases a, cases b, cc } @[priority 100] -- see Note [lower instance priority] instance reflects_limit_of_reflects_limits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_limits_of_shape J F] : reflects_limit K F := reflects_limits_of_shape.reflects_limit @[priority 100] -- see Note [lower instance priority] instance reflects_colimit_of_reflects_colimits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_colimits_of_shape J F] : reflects_colimit K F := reflects_colimits_of_shape.reflects_colimit @[priority 100] -- see Note [lower instance priority] instance reflects_limits_of_shape_of_reflects_limits (F : C ⥤ D) [H : reflects_limits F] : reflects_limits_of_shape J F := reflects_limits.reflects_limits_of_shape @[priority 100] -- see Note [lower instance priority] instance reflects_colimits_of_shape_of_reflects_colimits (F : C ⥤ D) [H : reflects_colimits F] : reflects_colimits_of_shape J F := reflects_colimits.reflects_colimits_of_shape omit 𝒟 instance id_reflects_limits : reflects_limits (𝟭 C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_reflects_colimits : reflects_colimits (𝟭 C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } include 𝒟 section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_reflects_limit [reflects_limit K F] [reflects_limit (K ⋙ F) G] : reflects_limit K (F ⋙ G) := ⟨λ c h, reflects_limit.reflects (reflects_limit.reflects h)⟩ instance comp_reflects_colimit [reflects_colimit K F] [reflects_colimit (K ⋙ F) G] : reflects_colimit K (F ⋙ G) := ⟨λ c h, reflects_colimit.reflects (reflects_colimit.reflects h)⟩ end end category_theory.limits
f7267e3079dfae1d7dbc4e6226e6a0b0f116c8f3
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/complex/real_deriv.lean
6dd836813f070fa5954059e5cd73678873737f22
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,334
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yourong Zang -/ import analysis.calculus.cont_diff import analysis.complex.conformal import analysis.calculus.conformal.normed_space /-! # Real differentiability of complex-differentiable functions `has_deriv_at.real_of_complex` expresses that, if a function on `ℂ` is differentiable (over `ℂ`), then its restriction to `ℝ` is differentiable over `ℝ`, with derivative the real part of the complex derivative. `differentiable_at.conformal_at` states that a real-differentiable function with a nonvanishing differential from the complex plane into an arbitrary complex-normed space is conformal at a point if it's holomorphic at that point. This is a version of Cauchy-Riemann equations. `conformal_at_iff_differentiable_at_or_differentiable_at_comp_conj` proves that a real-differential function with a nonvanishing differential between the complex plane is conformal at a point if and only if it's holomorphic or antiholomorphic at that point. ## TODO * The classical form of Cauchy-Riemann equations * On a connected open set `u`, a function which is `conformal_at` each point is either holomorphic throughout or antiholomorphic throughout. ## Warning We do NOT require conformal functions to be orientation-preserving in this file. -/ section real_deriv_of_complex /-! ### Differentiability of the restriction to `ℝ` of complex functions -/ open complex variables {e : ℂ → ℂ} {e' : ℂ} {z : ℝ} /-- If a complex function is differentiable at a real point, then the induced real function is also differentiable at this point, with a derivative equal to the real part of the complex derivative. -/ theorem has_strict_deriv_at.real_of_complex (h : has_strict_deriv_at e e' z) : has_strict_deriv_at (λx:ℝ, (e x).re) e'.re z := begin have A : has_strict_fderiv_at (coe : ℝ → ℂ) of_real_clm z := of_real_clm.has_strict_fderiv_at, have B : has_strict_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ) (of_real_clm z) := h.has_strict_fderiv_at.restrict_scalars ℝ, have C : has_strict_fderiv_at re re_clm (e (of_real_clm z)) := re_clm.has_strict_fderiv_at, simpa using (C.comp z (B.comp z A)).has_strict_deriv_at end /-- If a complex function is differentiable at a real point, then the induced real function is also differentiable at this point, with a derivative equal to the real part of the complex derivative. -/ theorem has_deriv_at.real_of_complex (h : has_deriv_at e e' z) : has_deriv_at (λx:ℝ, (e x).re) e'.re z := begin have A : has_fderiv_at (coe : ℝ → ℂ) of_real_clm z := of_real_clm.has_fderiv_at, have B : has_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ) (of_real_clm z) := h.has_fderiv_at.restrict_scalars ℝ, have C : has_fderiv_at re re_clm (e (of_real_clm z)) := re_clm.has_fderiv_at, simpa using (C.comp z (B.comp z A)).has_deriv_at end theorem cont_diff_at.real_of_complex {n : with_top ℕ} (h : cont_diff_at ℂ n e z) : cont_diff_at ℝ n (λ x : ℝ, (e x).re) z := begin have A : cont_diff_at ℝ n (coe : ℝ → ℂ) z, from of_real_clm.cont_diff.cont_diff_at, have B : cont_diff_at ℝ n e z := h.restrict_scalars ℝ, have C : cont_diff_at ℝ n re (e z), from re_clm.cont_diff.cont_diff_at, exact C.comp z (B.comp z A) end theorem cont_diff.real_of_complex {n : with_top ℕ} (h : cont_diff ℂ n e) : cont_diff ℝ n (λ x : ℝ, (e x).re) := cont_diff_iff_cont_diff_at.2 $ λ x, h.cont_diff_at.real_of_complex variables {E : Type*} [normed_group E] [normed_space ℂ E] lemma has_strict_deriv_at.complex_to_real_fderiv' {f : ℂ → E} {x : ℂ} {f' : E} (h : has_strict_deriv_at f f' x) : has_strict_fderiv_at f (re_clm.smul_right f' + I • im_clm.smul_right f') x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_strict_fderiv_at.restrict_scalars ℝ lemma has_deriv_at.complex_to_real_fderiv' {f : ℂ → E} {x : ℂ} {f' : E} (h : has_deriv_at f f' x) : has_fderiv_at f (re_clm.smul_right f' + I • im_clm.smul_right f') x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_fderiv_at.restrict_scalars ℝ lemma has_deriv_within_at.complex_to_real_fderiv' {f : ℂ → E} {s : set ℂ} {x : ℂ} {f' : E} (h : has_deriv_within_at f f' s x) : has_fderiv_within_at f (re_clm.smul_right f' + I • im_clm.smul_right f') s x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_fderiv_within_at.restrict_scalars ℝ lemma has_strict_deriv_at.complex_to_real_fderiv {f : ℂ → ℂ} {f' x : ℂ} (h : has_strict_deriv_at f f' x) : has_strict_fderiv_at f (f' • (1 : ℂ →L[ℝ] ℂ)) x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_strict_fderiv_at.restrict_scalars ℝ lemma has_deriv_at.complex_to_real_fderiv {f : ℂ → ℂ} {f' x : ℂ} (h : has_deriv_at f f' x) : has_fderiv_at f (f' • (1 : ℂ →L[ℝ] ℂ)) x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_fderiv_at.restrict_scalars ℝ lemma has_deriv_within_at.complex_to_real_fderiv {f : ℂ → ℂ} {s : set ℂ} {f' x : ℂ} (h : has_deriv_within_at f f' s x) : has_fderiv_within_at f (f' • (1 : ℂ →L[ℝ] ℂ)) s x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_fderiv_within_at.restrict_scalars ℝ end real_deriv_of_complex section conformality /-! ### Conformality of real-differentiable complex maps -/ open complex continuous_linear_map open_locale complex_conjugate variables {E : Type*} [normed_group E] [normed_space ℂ E] {z : ℂ} {f : ℂ → E} /-- A real differentiable function of the complex plane into some complex normed space `E` is conformal at a point `z` if it is holomorphic at that point with a nonvanishing differential. This is a version of the Cauchy-Riemann equations. -/ lemma differentiable_at.conformal_at (h : differentiable_at ℂ f z) (hf' : deriv f z ≠ 0) : conformal_at f z := begin rw [conformal_at_iff_is_conformal_map_fderiv, (h.has_fderiv_at.restrict_scalars ℝ).fderiv], apply is_conformal_map_complex_linear, simpa only [ne.def, ext_ring_iff] end /-- A complex function is conformal if and only if the function is holomorphic or antiholomorphic with a nonvanishing differential. -/ lemma conformal_at_iff_differentiable_at_or_differentiable_at_comp_conj {f : ℂ → ℂ} {z : ℂ} : conformal_at f z ↔ (differentiable_at ℂ f z ∨ differentiable_at ℂ (f ∘ conj) (conj z)) ∧ fderiv ℝ f z ≠ 0 := begin rw conformal_at_iff_is_conformal_map_fderiv, rw is_conformal_map_iff_is_complex_or_conj_linear, apply and_congr_left, intros h, have h_diff := h.imp_symm fderiv_zero_of_not_differentiable_at, apply or_congr, { rw differentiable_at_iff_restrict_scalars ℝ h_diff }, rw ← conj_conj z at h_diff, rw differentiable_at_iff_restrict_scalars ℝ (h_diff.comp _ conj_cle.differentiable_at), refine exists_congr (λ g, rfl.congr _), have : fderiv ℝ conj (conj z) = _ := conj_cle.fderiv, simp [fderiv.comp _ h_diff conj_cle.differentiable_at, this, conj_conj], end end conformality
81fddbdeae4d7247e64642445a36962dcd7d6440
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Init/System/IOError.lean
af31f6aa3508773f5b96f016e1f319c8ed77a499
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,692
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ prelude import Init.Core import Init.Data.UInt import Init.Data.ToString.Basic import Init.Data.String.Basic /- Imitate the structure of IOErrorType in Haskell: https://hackage.haskell.org/package/base-4.12.0.0/docs/System-IO-Error.html#t:IOErrorType -/ inductive IO.Error | alreadyExists (osCode : UInt32) (details : String) -- EEXIST, EINPROGRESS, EISCONN | otherError (osCode : UInt32) (details : String) -- EFAULT, default | resourceBusy (osCode : UInt32) (details : String) -- EADDRINUSE, EBUSY, EDEADLK, ETXTBSY | resourceVanished (osCode : UInt32) (details : String) -- ECONNRESET, EIDRM, ENETDOWN, ENETRESET, -- ENOLINK, EPIPE | unsupportedOperation (osCode : UInt32) (details : String) -- EADDRNOTAVAIL, EAFNOSUPPORT, ENODEV, ENOPROTOOPT -- ENOSYS, EOPNOTSUPP, ERANGE, ESPIPE, EXDEV | hardwareFault (osCode : UInt32) (details : String) -- EIO | unsatisfiedConstraints (osCode : UInt32) (details : String) -- ENOTEMPTY | illegalOperation (osCode : UInt32) (details : String) -- ENOTTY | protocolError (osCode : UInt32) (details : String) -- EPROTO, EPROTONOSUPPORT, EPROTOTYPE | timeExpired (osCode : UInt32) (details : String) -- ETIME, ETIMEDOUT | interrupted (filename : String) (osCode : UInt32) (details : String) -- EINTR | noFileOrDirectory (filename : String) (osCode : UInt32) (details : String) -- ENOENT | invalidArgument (filename : Option String) (osCode : UInt32) (details : String) -- ELOOP, ENAMETOOLONG, EDESTADDRREQ, EILSEQ, EINVAL, EDOM, EBADF -- ENOEXEC, ENOSTR, ENOTCONN, ENOTSOCK | permissionDenied (filename : Option String) (osCode : UInt32) (details : String) -- EACCES, EROFS, ECONNABORTED, EFBIG, EPERM | resourceExhausted (filename : Option String) (osCode : UInt32) (details : String) -- EMFILE, ENFILE, ENOSPC, E2BIG, EAGAIN, EMLINK: -- EMSGSIZE, ENOBUFS, ENOLCK, ENOMEM, ENOSR: | inappropriateType (filename : Option String) (osCode : UInt32) (details : String) -- EISDIR, EBADMSG, ENOTDIR: | noSuchThing (filename : Option String) (osCode : UInt32) (details : String) -- ENXIO, EHOSTUNREACH, ENETUNREACH, ECHILD, ECONNREFUSED, -- ENODATA, ENOMSG, ESRCH | unexpectedEof | userError (msg : String) @[export mk_io_user_error] def IO.userError (s : String) : IO.Error := IO.Error.userError s instance : Coe String IO.Error := ⟨IO.userError⟩ namespace IO.Error @[export lean_mk_io_error_eof] def mkEofError : Unit → IO.Error := fun _ => unexpectedEof @[export lean_mk_io_error_inappropriate_type_file] def mkInappropriateTypeFile : String → UInt32 → String → IO.Error := inappropriateType ∘ some @[export lean_mk_io_error_interrupted] def mkInterrupted : String → UInt32 → String → IO.Error := interrupted @[export lean_mk_io_error_invalid_argument_file] def mkInvalidArgumentFile : String → UInt32 → String → IO.Error := invalidArgument ∘ some @[export lean_mk_io_error_no_file_or_directory] def mkNoFileOrDirectory : String → UInt32 → String → IO.Error := noFileOrDirectory @[export lean_mk_io_error_no_such_thing_file] def mkNoSuchThingFile : String → UInt32 → String → IO.Error := noSuchThing ∘ some @[export lean_mk_io_error_permission_denied_file] def mkPermissionDeniedFile : String → UInt32 → String → IO.Error := permissionDenied ∘ some @[export lean_mk_io_error_resource_exhausted_file] def mkResourceExhaustedFile : String → UInt32 → String → IO.Error := resourceExhausted ∘ some @[export lean_mk_io_error_unsupported_operation] def mkUnsupportedOperation : UInt32 → String → IO.Error := unsupportedOperation @[export lean_mk_io_error_resource_exhausted] def mkResourceExhausted : UInt32 → String → IO.Error := resourceExhausted none @[export lean_mk_io_error_already_exists] def mkAlreadyExists : UInt32 → String → IO.Error := alreadyExists @[export lean_mk_io_error_inappropriate_type] def mkInappropriateType : UInt32 → String → IO.Error := inappropriateType none @[export lean_mk_io_error_no_such_thing] def mkNoSuchThing : UInt32 → String → IO.Error := noSuchThing none @[export lean_mk_io_error_resource_vanished] def mkResourceVanished : UInt32 → String → IO.Error := resourceVanished @[export lean_mk_io_error_resource_busy] def mkResourceBusy : UInt32 → String → IO.Error := resourceBusy @[export lean_mk_io_error_invalid_argument] def mkInvalidArgument : UInt32 → String → IO.Error := invalidArgument none @[export lean_mk_io_error_other_error] def mkOtherError : UInt32 → String → IO.Error := otherError @[export lean_mk_io_error_permission_denied] def mkPermissionDenied : UInt32 → String → IO.Error := permissionDenied none @[export lean_mk_io_error_hardware_fault] def mkHardwareFault : UInt32 → String → IO.Error := hardwareFault @[export lean_mk_io_error_unsatisfied_constraints] def mkUnsatisfiedConstraints : UInt32 → String → IO.Error := unsatisfiedConstraints @[export lean_mk_io_error_illegal_operation] def mkIllegalOperation : UInt32 → String → IO.Error := illegalOperation @[export lean_mk_io_error_protocol_error] def mkProtocolError : UInt32 → String → IO.Error := protocolError @[export lean_mk_io_error_time_expired] def mkTimeExpired : UInt32 → String → IO.Error := timeExpired private def downCaseFirst (s : String) : String := s.modify 0 Char.toLower def fopenErrorToString (gist fn : String) (code : UInt32) : Option String → String | some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")\n file: " ++ fn | none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")\n file: " ++ fn def otherErrorToString (gist : String) (code : UInt32) : Option String → String | some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")" | none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")" @[export lean_io_error_to_string] def toString : IO.Error → String | unexpectedEof => "end of file" | inappropriateType (some fn) code details => fopenErrorToString "inappropriate type" fn code details | inappropriateType none code details => otherErrorToString "inappropriate type" code details | interrupted fn code details => fopenErrorToString "interrupted system call" fn code details | invalidArgument (some fn) code details => fopenErrorToString "invalid argument" fn code details | invalidArgument none code details => otherErrorToString "invalid argument" code details | noFileOrDirectory fn code _ => fopenErrorToString "no such file or directory" fn code none | noSuchThing (some fn) code details => fopenErrorToString "no such thing" fn code details | noSuchThing none code details => otherErrorToString "no such thing" code details | permissionDenied (some fn) code details => fopenErrorToString details fn code none | permissionDenied none code details => otherErrorToString details code none | resourceExhausted (some fn) code details => fopenErrorToString "resource exhausted" fn code details | resourceExhausted none code details => otherErrorToString "resource exhausted" code details | alreadyExists code details => otherErrorToString "already exists" code details | otherError code details => otherErrorToString details code none | resourceBusy code details => otherErrorToString "resource busy" code details | resourceVanished code details => otherErrorToString "resource vanished" code details | hardwareFault code _ => otherErrorToString "hardware fault" code none | illegalOperation code details => otherErrorToString "illegal operation" code details | protocolError code details => otherErrorToString "protocol error" code details | timeExpired code details => otherErrorToString "time expired" code details | unsatisfiedConstraints code _ => otherErrorToString "directory not empty" code none | unsupportedOperation code details => otherErrorToString "unsupported operation" code details | userError msg => msg instance : ToString IO.Error := ⟨ IO.Error.toString ⟩ instance : Inhabited IO.Error := ⟨ userError "" ⟩ end IO.Error
c277d78fc7fb487aae67d7e009e4b11637f1094e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/list/alist_auto.lean
1fd948c49a189825fff4ee7ca0fd04e4a9406f1d
[]
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
14,329
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.sigma import Mathlib.PostPort universes u v l w namespace Mathlib /-! # Association lists -/ /-- `alist β` is a key-value map stored as a `list` (i.e. a linked list). It is a wrapper around certain `list` functions with the added constraint that the list have unique keys. -/ structure alist {α : Type u} (β : α → Type v) where entries : List (sigma β) nodupkeys : list.nodupkeys entries /-- Given `l : list (sigma β)`, create a term of type `alist β` by removing entries with duplicate keys. -/ def list.to_alist {α : Type u} [DecidableEq α] {β : α → Type v} (l : List (sigma β)) : alist β := alist.mk (list.erase_dupkeys l) sorry namespace alist theorem ext {α : Type u} {β : α → Type v} {s : alist β} {t : alist β} : entries s = entries t → s = t := sorry theorem ext_iff {α : Type u} {β : α → Type v} {s : alist β} {t : alist β} : s = t ↔ entries s = entries t := { mp := congr_arg fun {s : alist β} => entries s, mpr := ext } protected instance decidable_eq {α : Type u} {β : α → Type v} [DecidableEq α] [(a : α) → DecidableEq (β a)] : DecidableEq (alist β) := fun (xs ys : alist β) => eq.mpr sorry (list.decidable_eq (entries xs) (entries ys)) /-! ### keys -/ /-- The list of keys of an association list. -/ def keys {α : Type u} {β : α → Type v} (s : alist β) : List α := list.keys (entries s) theorem keys_nodup {α : Type u} {β : α → Type v} (s : alist β) : list.nodup (keys s) := nodupkeys s /-! ### mem -/ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ protected instance has_mem {α : Type u} {β : α → Type v} : has_mem α (alist β) := has_mem.mk fun (a : α) (s : alist β) => a ∈ keys s theorem mem_keys {α : Type u} {β : α → Type v} {a : α} {s : alist β} : a ∈ s ↔ a ∈ keys s := iff.rfl theorem mem_of_perm {α : Type u} {β : α → Type v} {a : α} {s₁ : alist β} {s₂ : alist β} (p : entries s₁ ~ entries s₂) : a ∈ s₁ ↔ a ∈ s₂ := list.perm.mem_iff (list.perm.map sigma.fst p) /-! ### empty -/ /-- The empty association list. -/ protected instance has_emptyc {α : Type u} {β : α → Type v} : has_emptyc (alist β) := has_emptyc.mk (mk [] list.nodupkeys_nil) protected instance inhabited {α : Type u} {β : α → Type v} : Inhabited (alist β) := { default := ∅ } theorem not_mem_empty {α : Type u} {β : α → Type v} (a : α) : ¬a ∈ ∅ := list.not_mem_nil a @[simp] theorem empty_entries {α : Type u} {β : α → Type v} : entries ∅ = [] := rfl @[simp] theorem keys_empty {α : Type u} {β : α → Type v} : keys ∅ = [] := rfl /-! ### singleton -/ /-- The singleton association list. -/ def singleton {α : Type u} {β : α → Type v} (a : α) (b : β a) : alist β := mk [sigma.mk a b] sorry @[simp] theorem singleton_entries {α : Type u} {β : α → Type v} (a : α) (b : β a) : entries (singleton a b) = [sigma.mk a b] := rfl @[simp] theorem keys_singleton {α : Type u} {β : α → Type v} (a : α) (b : β a) : keys (singleton a b) = [a] := rfl /-! ### lookup -/ /-- Look up the value associated to a key in an association list. -/ def lookup {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : alist β) : Option (β a) := list.lookup a (entries s) @[simp] theorem lookup_empty {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) : lookup a ∅ = none := rfl theorem lookup_is_some {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s : alist β} : ↥(option.is_some (lookup a s)) ↔ a ∈ s := list.lookup_is_some theorem lookup_eq_none {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s : alist β} : lookup a s = none ↔ ¬a ∈ s := list.lookup_eq_none theorem perm_lookup {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s₁ : alist β} {s₂ : alist β} (p : entries s₁ ~ entries s₂) : lookup a s₁ = lookup a s₂ := list.perm_lookup a (nodupkeys s₁) (nodupkeys s₂) p protected instance has_mem.mem.decidable {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : alist β) : Decidable (a ∈ s) := decidable_of_iff ↥(option.is_some (lookup a s)) sorry /-! ### replace -/ /-- Replace a key with a given value in an association list. If the key is not present it does nothing. -/ def replace {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) (s : alist β) : alist β := mk (list.kreplace a b (entries s)) sorry @[simp] theorem keys_replace {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) (s : alist β) : keys (replace a b s) = keys s := list.keys_kreplace a b (entries s) @[simp] theorem mem_replace {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {b : β a} {s : alist β} : a' ∈ replace a b s ↔ a' ∈ s := eq.mpr (id (Eq._oldrec (Eq.refl (a' ∈ replace a b s ↔ a' ∈ s)) (propext mem_keys))) (eq.mpr (id (Eq._oldrec (Eq.refl (a' ∈ keys (replace a b s) ↔ a' ∈ s)) (keys_replace a b s))) (eq.mpr (id (Eq._oldrec (Eq.refl (a' ∈ keys s ↔ a' ∈ s)) (Eq.symm (propext mem_keys)))) (iff.refl (a' ∈ s)))) theorem perm_replace {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s₁ : alist β} {s₂ : alist β} : entries s₁ ~ entries s₂ → entries (replace a b s₁) ~ entries (replace a b s₂) := list.perm.kreplace (nodupkeys s₁) /-- Fold a function over the key-value pairs in the map. -/ def foldl {α : Type u} {β : α → Type v} {δ : Type w} (f : δ → (a : α) → β a → δ) (d : δ) (m : alist β) : δ := list.foldl (fun (r : δ) (a : sigma β) => f r (sigma.fst a) (sigma.snd a)) d (entries m) /-! ### erase -/ /-- Erase a key from the map. If the key is not present, do nothing. -/ def erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : alist β) : alist β := mk (list.kerase a (entries s)) sorry @[simp] theorem keys_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : alist β) : keys (erase a s) = list.erase (keys s) a := sorry @[simp] theorem mem_erase {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {s : alist β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := sorry theorem perm_erase {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s₁ : alist β} {s₂ : alist β} : entries s₁ ~ entries s₂ → entries (erase a s₁) ~ entries (erase a s₂) := list.perm.kerase (nodupkeys s₁) @[simp] theorem lookup_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : alist β) : lookup a (erase a s) = none := list.lookup_kerase a (nodupkeys s) @[simp] theorem lookup_erase_ne {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {s : alist β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s := list.lookup_kerase_ne h theorem erase_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (a' : α) (s : alist β) : erase a' (erase a s) = erase a (erase a' s) := ext list.kerase_kerase /-! ### insert -/ /-- Insert a key-value pair into an association list and erase any existing pair with the same key. -/ def insert {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) (s : alist β) : alist β := mk (list.kinsert a b (entries s)) sorry @[simp] theorem insert_entries {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s : alist β} : entries (insert a b s) = sigma.mk a b :: list.kerase a (entries s) := rfl theorem insert_entries_of_neg {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s : alist β} (h : ¬a ∈ s) : entries (insert a b s) = sigma.mk a b :: entries s := sorry @[simp] theorem mem_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {b' : β a'} (s : alist β) : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := list.mem_keys_kinsert @[simp] theorem keys_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} (s : alist β) : keys (insert a b s) = a :: list.erase (keys s) a := sorry theorem perm_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s₁ : alist β} {s₂ : alist β} (p : entries s₁ ~ entries s₂) : entries (insert a b s₁) ~ entries (insert a b s₂) := sorry @[simp] theorem lookup_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} (s : alist β) : lookup a (insert a b s) = some b := sorry @[simp] theorem lookup_insert_ne {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {b' : β a'} {s : alist β} (h : a ≠ a') : lookup a (insert a' b' s) = lookup a s := list.lookup_kinsert_ne h @[simp] theorem lookup_to_alist {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} (s : List (sigma β)) : lookup a (list.to_alist s) = list.lookup a s := sorry @[simp] theorem insert_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {b' : β a} (s : alist β) : insert a b' (insert a b s) = insert a b' s := sorry theorem insert_insert_of_ne {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {b : β a} {b' : β a'} (s : alist β) (h : a ≠ a') : entries (insert a' b' (insert a b s)) ~ entries (insert a b (insert a' b' s)) := sorry @[simp] theorem insert_singleton_eq {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {b' : β a} : insert a b (singleton a b') = singleton a b := sorry @[simp] theorem entries_to_alist {α : Type u} {β : α → Type v} [DecidableEq α] (xs : List (sigma β)) : entries (list.to_alist xs) = list.erase_dupkeys xs := rfl theorem to_alist_cons {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) (xs : List (sigma β)) : list.to_alist (sigma.mk a b :: xs) = insert a b (list.to_alist xs) := rfl /-! ### extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : alist β) : Option (β a) × alist β := (fun (this : list.nodupkeys (prod.snd (list.kextract a (entries s)))) => sorry) sorry @[simp] theorem extract_eq_lookup_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : alist β) : extract a s = (lookup a s, erase a s) := sorry /-! ### union -/ /-- `s₁ ∪ s₂` is the key-based union of two association lists. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/ def union {α : Type u} {β : α → Type v} [DecidableEq α] (s₁ : alist β) (s₂ : alist β) : alist β := mk (list.kunion (entries s₁) (entries s₂)) sorry protected instance has_union {α : Type u} {β : α → Type v} [DecidableEq α] : has_union (alist β) := has_union.mk union @[simp] theorem union_entries {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : alist β} {s₂ : alist β} : entries (s₁ ∪ s₂) = list.kunion (entries s₁) (entries s₂) := rfl @[simp] theorem empty_union {α : Type u} {β : α → Type v} [DecidableEq α] {s : alist β} : ∅ ∪ s = s := ext rfl @[simp] theorem union_empty {α : Type u} {β : α → Type v} [DecidableEq α] {s : alist β} : s ∪ ∅ = s := sorry @[simp] theorem mem_union {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s₁ : alist β} {s₂ : alist β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := list.mem_keys_kunion theorem perm_union {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : alist β} {s₂ : alist β} {s₃ : alist β} {s₄ : alist β} (p₁₂ : entries s₁ ~ entries s₂) (p₃₄ : entries s₃ ~ entries s₄) : entries (s₁ ∪ s₃) ~ entries (s₂ ∪ s₄) := sorry theorem union_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s₁ : alist β) (s₂ : alist β) : erase a (s₁ ∪ s₂) = erase a s₁ ∪ erase a s₂ := ext (Eq.symm list.kunion_kerase) @[simp] theorem lookup_union_left {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s₁ : alist β} {s₂ : alist β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ := list.lookup_kunion_left @[simp] theorem lookup_union_right {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s₁ : alist β} {s₂ : alist β} : ¬a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ := list.lookup_kunion_right @[simp] theorem mem_lookup_union {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s₁ : alist β} {s₂ : alist β} : b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ ¬a ∈ s₁ ∧ b ∈ lookup a s₂ := list.mem_lookup_kunion theorem mem_lookup_union_middle {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s₁ : alist β} {s₂ : alist β} {s₃ : alist β} : b ∈ lookup a (s₁ ∪ s₃) → ¬a ∈ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) := list.mem_lookup_kunion_middle theorem insert_union {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s₁ : alist β} {s₂ : alist β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := sorry theorem union_assoc {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : alist β} {s₂ : alist β} {s₃ : alist β} : entries (s₁ ∪ s₂ ∪ s₃) ~ entries (s₁ ∪ (s₂ ∪ s₃)) := sorry /-! ### disjoint -/ /-- Two associative lists are disjoint if they have no common keys. -/ def disjoint {α : Type u} {β : α → Type v} (s₁ : alist β) (s₂ : alist β) := ∀ (k : α), k ∈ keys s₁ → ¬k ∈ keys s₂ theorem union_comm_of_disjoint {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : alist β} {s₂ : alist β} (h : disjoint s₁ s₂) : entries (s₁ ∪ s₂) ~ entries (s₂ ∪ s₁) := sorry end Mathlib
8a772ad9895b51bc354ca21d2c79358e4de5bd2f
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Init/Data/Format/Basic.lean
cfaef5f975137d31c8da02c3cc7b1558d5abed20
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
11,484
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Control.State import Init.Data.Int.Basic import Init.Data.String.Basic namespace Std /-- Determines how groups should have linebreaks inserted when the text would overfill its remaining space. - `allOrNone` will make a linebreak on every `Format.line` in the group or none of them. ``` [1, 2, 3] ``` - `fill` will only make linebreaks on as few `Format.line`s as possible: ``` [1, 2, 3] ``` -/ inductive Format.FlattenBehavior where | allOrNone | fill deriving Inhabited, BEq open Format in /-- A string with pretty-printing information for rendering in a column-width-aware way. The pretty-printing algorithm is based on Wadler's paper [_A Prettier Printer_](https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf). -/ inductive Format where /-- The empty format. -/ | nil : Format /-- A position where a newline may be inserted if the current group does not fit within the allotted column width. -/ | line : Format /-- A node containing a plain string. -/ | text : String → Format /-- `nest n f` tells the formatter that `f` is nested inside something with length `n` so that it is pretty-printed with the correct indentation on a line break. For example, we can define a formatter for list `l : List Format` as: ``` let f := join <| l.intersperse <| ", " ++ Format.line group (nest 1 <| "[" ++ f ++ "]") ``` This will be written all on one line, but if the text is too large, the formatter will put in linebreaks after the commas and indent later lines by 1. -/ | nest (indent : Int) : Format → Format /-- Concatenation of two Formats. -/ | append : Format → Format → Format /-- Creates a new flattening group for the given inner format. -/ | group : Format → (behavior : FlattenBehavior := FlattenBehavior.allOrNone) → Format /-- Used for associating auxiliary information (e.g. `Expr`s) with `Format` objects. -/ | tag : Nat → Format → Format deriving Inhabited namespace Format /-- Check whether the given format contains no characters. -/ def isEmpty : Format → Bool | nil => true | line => false | text msg => msg == "" | nest _ f => f.isEmpty | append f₁ f₂ => f₁.isEmpty && f₂.isEmpty | group f _ => f.isEmpty | tag _ f => f.isEmpty /-- Alias for a group with `FlattenBehavior` set to `fill`. -/ def fill (f : Format) : Format := group f (behavior := FlattenBehavior.fill) @[export lean_format_append] protected def appendEx (a b : Format) : Format := append a b @[export lean_format_group] protected def groupEx : Format → Format := group instance : Append Format := ⟨Format.append⟩ instance : Coe String Format := ⟨text⟩ def join (xs : List Format) : Format := xs.foldl (·++·) "" def isNil : Format → Bool | nil => true | _ => false private structure SpaceResult where foundLine : Bool := false foundFlattenedHardLine : Bool := false space : Nat := 0 deriving Inhabited @[inline] private def merge (w : Nat) (r₁ : SpaceResult) (r₂ : Nat → SpaceResult) : SpaceResult := if r₁.space > w || r₁.foundLine then r₁ else let r₂ := r₂ (w - r₁.space); { r₂ with space := r₁.space + r₂.space } private def spaceUptoLine : Format → Bool → Nat → SpaceResult | nil, _, _ => {} | line, flatten, _ => if flatten then { space := 1 } else { foundLine := true } | text s, flatten, _ => let p := s.posOf '\n'; let off := s.offsetOfPos p; { foundLine := p != s.endPos, foundFlattenedHardLine := flatten && p != s.endPos, space := off } | append f₁ f₂, flatten, w => merge w (spaceUptoLine f₁ flatten w) (spaceUptoLine f₂ flatten) | nest _ f, flatten, w => spaceUptoLine f flatten w | group f _, _, w => spaceUptoLine f true w | tag _ f, flatten, w => spaceUptoLine f flatten w private structure WorkItem where f : Format indent : Int activeTags : Nat private structure WorkGroup where flatten : Bool flb : FlattenBehavior items : List WorkItem private partial def spaceUptoLine' : List WorkGroup → Nat → SpaceResult | [], _ => {} | { items := [], .. }::gs, w => spaceUptoLine' gs w | g@{ items := i::is, .. }::gs, w => merge w (spaceUptoLine i.f g.flatten w) (spaceUptoLine' ({ g with items := is }::gs)) /-- A monad in which we can pretty-print `Format` objects. -/ class MonadPrettyFormat (m : Type → Type) where pushOutput (s : String) : m Unit pushNewline (indent : Nat) : m Unit currColumn : m Nat /-- Start a scope tagged with `n`. -/ startTag : Nat → m Unit /-- Exit the scope of `n`-many opened tags. -/ endTags : Nat → m Unit open MonadPrettyFormat private def pushGroup (flb : FlattenBehavior) (items : List WorkItem) (gs : List WorkGroup) (w : Nat) [Monad m] [MonadPrettyFormat m] : m (List WorkGroup) := do let k ← currColumn -- Flatten group if it + the remainder (gs) fits in the remaining space. For `fill`, measure only up to the next (ungrouped) line break. let g := { flatten := flb == FlattenBehavior.allOrNone, flb := flb, items := items : WorkGroup } let r := spaceUptoLine' [g] (w-k) let r' := merge (w-k) r (spaceUptoLine' gs); -- Prevent flattening if any item contains a hard line break, except within `fill` if it is ungrouped (=> unflattened) return { g with flatten := !r.foundFlattenedHardLine && r'.space <= w-k }::gs private partial def be (w : Nat) [Monad m] [MonadPrettyFormat m] : List WorkGroup → m Unit | [] => pure () | { items := [], .. }::gs => be w gs | g@{ items := i::is, .. }::gs => do let gs' (is' : List WorkItem) := { g with items := is' }::gs; match i.f with | nil => endTags i.activeTags be w (gs' is) | tag t f => startTag t be w (gs' ({ i with f, activeTags := i.activeTags + 1 }::is)) | append f₁ f₂ => be w (gs' ({ i with f := f₁, activeTags := 0 }::{ i with f := f₂ }::is)) | nest n f => be w (gs' ({ i with f, indent := i.indent + n }::is)) | text s => let p := s.posOf '\n' if p == s.endPos then pushOutput s endTags i.activeTags be w (gs' is) else pushOutput (s.extract {} p) pushNewline i.indent.toNat let is := { i with f := text (s.extract (s.next p) s.endPos) }::is -- after a hard line break, re-evaluate whether to flatten the remaining group pushGroup g.flb is gs w >>= be w | line => match g.flb with | FlattenBehavior.allOrNone => if g.flatten then -- flatten line = text " " pushOutput " " endTags i.activeTags be w (gs' is) else pushNewline i.indent.toNat endTags i.activeTags be w (gs' is) | FlattenBehavior.fill => let breakHere := do pushNewline i.indent.toNat -- make new `fill` group and recurse endTags i.activeTags pushGroup FlattenBehavior.fill is gs w >>= be w -- if preceding fill item fit in a single line, try to fit next one too if g.flatten then let gs'@(g'::_) ← pushGroup FlattenBehavior.fill is gs (w - " ".length) | panic "unreachable" if g'.flatten then pushOutput " "; endTags i.activeTags be w gs' -- TODO: use `return` else breakHere else breakHere | group f flb => if g.flatten then -- flatten (group f) = flatten f be w (gs' ({ i with f }::is)) else pushGroup flb [{ i with f }] (gs' is) w >>= be w /-- Render the given `f : Format` with a line width of `w`. `indent` is the starting amount to indent each line by. -/ def prettyM (f : Format) (w : Nat) (indent : Nat := 0) [Monad m] [MonadPrettyFormat m] : m Unit := be w [{ flb := FlattenBehavior.allOrNone, flatten := false, items := [{ f := f, indent, activeTags := 0 }]}] /-- Create a format `l ++ f ++ r` with a flatten group. FlattenBehaviour is `allOrNone`; for `fill` use `bracketFill`. -/ @[inline] def bracket (l : String) (f : Format) (r : String) : Format := group (nest l.length $ l ++ f ++ r) /-- Creates the format `"(" ++ f ++ ")"` with a flattening group.-/ @[inline] def paren (f : Format) : Format := bracket "(" f ")" /-- Creates the format `"[" ++ f ++ "]"` with a flattening group.-/ @[inline] def sbracket (f : Format) : Format := bracket "[" f "]" /-- Same as `bracket` except uses the `fill` flattening behaviour. -/ @[inline] def bracketFill (l : String) (f : Format) (r : String) : Format := fill (nest l.length $ l ++ f ++ r) /-- Default indentation. -/ def defIndent := 2 def defUnicode := true /-- Default width of the targeted output pane. -/ def defWidth := 120 /-- Nest with the default indentation amount.-/ def nestD (f : Format) : Format := nest defIndent f /-- Insert a newline and then `f`, all nested by the default indent amount. -/ def indentD (f : Format) : Format := nestD (Format.line ++ f) /-- State for formatting a pretty string. -/ private structure State where out : String := "" column : Nat := 0 instance : MonadPrettyFormat (StateM State) where -- We avoid a structure instance update, and write these functions using pattern matching because of issue #316 pushOutput s := modify fun ⟨out, col⟩ => ⟨out ++ s, col + s.length⟩ pushNewline indent := modify fun ⟨out, _⟩ => ⟨out ++ "\n".pushn ' ' indent, indent⟩ currColumn := return (← get).column startTag _ := return () endTags _ := return () /-- Pretty-print a `Format` object as a string with expected width `w`. -/ @[export lean_format_pretty] def pretty (f : Format) (w : Nat := defWidth) : String := let act: StateM State Unit := prettyM f w act {} |>.snd.out end Format /-- Class for converting a given type α to a `Format` object for pretty-printing. See also `Repr`, which also outputs a `Format` object. -/ class ToFormat (α : Type u) where format : α → Format export ToFormat (format) -- note: must take precendence over the above instance to avoid premature formatting instance : ToFormat Format where format f := f instance : ToFormat String where format s := Format.text s /-- Intersperse the given list (each item printed with `format`) with the given `sep` format. -/ def Format.joinSep {α : Type u} [ToFormat α] : List α → Format → Format | [], _ => nil | [a], _ => format a | a::as, sep => format a ++ sep ++ joinSep as sep /-- Format each item in `items` and prepend prefix `pre`. -/ def Format.prefixJoin {α : Type u} [ToFormat α] (pre : Format) : List α → Format | [] => nil | a::as => pre ++ format a ++ prefixJoin pre as /-- Format each item in `items` and append `suffix`. -/ def Format.joinSuffix {α : Type u} [ToFormat α] : List α → Format → Format | [], _ => nil | a::as, suffix => format a ++ suffix ++ joinSuffix as suffix end Std
8d236d07f716dfe129ae6e9f70704e78e6c7fc53
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/euclidean/default.lean
9002867580ffe74a6f5b176310ed923024bec384
[ "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
199
lean
import geometry.euclidean.angle.unoriented.right_angle import geometry.euclidean.basic import geometry.euclidean.circumcenter import geometry.euclidean.monge_point import geometry.euclidean.triangle
570b71c7ba5ee1a4e012a83757c835aef321ea03
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/nat_add_assoc_no_axioms.lean
51d9b97b98996bf1476e6720381bdb1bf583d29f
[ "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
27
lean
print axioms nat.add_assoc
b564418a83e9cd7e45eb45a154eb6324a6c6cbf8
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/adjoin_root.lean
8c7305cacffc948016cb6ed5a77dd199d433ede4
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,716
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial.field_division import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import ring_theory.power_basis import ring_theory.principal_ideal_domain /-! # Adjoining roots of polynomials This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is irreducible, the field structure on `adjoin_root f` is constructed. ## Main definitions and results The main definitions are in the `adjoin_root` namespace. * `mk f : polynomial R →+* adjoin_root f`, the natural ring homomorphism. * `of f : R →+* adjoin_root f`, the natural ring homomorphism. * `root f : adjoin_root f`, the image of X in R[X]/(f). * `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`. * `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x` * `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S` -/ noncomputable theory open_locale classical open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {K : Type w} open polynomial ideal /-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring as the quotient of `R` by the principal ideal of `f`. -/ def adjoin_root [comm_ring R] (f : polynomial R) : Type u := ideal.quotient (span {f} : ideal (polynomial R)) namespace adjoin_root section comm_ring variables [comm_ring R] (f : polynomial R) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : inhabited (adjoin_root f) := ⟨0⟩ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ /-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/ def mk : polynomial R →+* adjoin_root f := ideal.quotient.mk _ @[elab_as_eliminator] theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f) (ih : ∀ p : polynomial R, C (mk f p)) : C x := quotient.induction_on' x ih /-- Embedding of the original ring `R` into `adjoin_root f`. -/ def of : R →+* adjoin_root f := (mk f).comp (ring_hom.of C) instance : algebra R (adjoin_root f) := (of f).to_algebra @[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl /-- The adjoined root. -/ def root : adjoin_root f := mk f X variables {f} instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩ @[simp] lemma mk_self : mk f f = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) @[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl @[simp] lemma mk_X : mk f X = root f := rfl @[simp] lemma aeval_eq (p : polynomial R) : aeval (root f) p = mk f p := polynomial.induction_on p (λ x, by { rw aeval_C, refl }) (λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq]) (λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X, ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl }) theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ := algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p, (algebra.adjoin_singleton_eq_range R (root f)).symm ▸ ⟨p, set.mem_univ _, aeval_eq p⟩ @[simp] lemma eval₂_root (f : polynomial R) : f.eval₂ (of f) (root f) = 0 := by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self] lemma is_root_root (f : polynomial R) : is_root (f.map (of f)) (root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring S] /-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/ def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S := begin apply ideal.quotient.lift _ (eval₂_ring_hom i x), intros g H, rcases mem_span_singleton.1 H with ⟨y, hy⟩, rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul] end variables {i : R →+* S} {a : S} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial R} : lift i a h (mk f g) = g.eval₂ i a := ideal.quotient.lift_mk _ _ _ @[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X] @[simp] lemma lift_of {x : R} : lift i a h x = i x := by rw [← mk_C x, lift_mk, eval₂_C] @[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i := ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _ variables (f) [algebra R S] /-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to a root of `f` in `S`. -/ def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S := { commutes' := λ r, show lift _ _ hfx r = _, from lift_of, .. lift (algebra_map R S) x hfx } @[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) : (lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl @[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 := begin have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes), rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂], refl, end @[simp] lemma lift_hom_eq_alg_hom (f : polynomial R) (ϕ : adjoin_root f →ₐ[R] S) : lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ := begin suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤, { exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm }, rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff], exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm, end /-- If `E` is a field extension of `F` and `f` is a polynomial over `F` then the set of maps from `F[x]/(f)` into `E` is in bijection with the set of roots of `f` in `E`. -/ def equiv (F E : Type*) [field F] [field E] [algebra F E] (f : polynomial F) (hf : f ≠ 0) : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots} := { to_fun := λ ϕ, ⟨ϕ (root f), begin rw [mem_roots (map_ne_zero hf), is_root.def, ←eval₂_eq_eval_map], exact aeval_alg_hom_eq_zero f ϕ, exact field.to_nontrivial E, end⟩, inv_fun := λ x, lift_hom f ↑x (begin rw [aeval_def, eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf)], exact subtype.mem x, exact field.to_nontrivial E end), left_inv := λ ϕ, lift_hom_eq_alg_hom f ϕ, right_inv := λ x, begin ext, refine @lift_root F E _ f _ _ ↑x _, rw [eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf), ←multiset.mem_to_finset], exact multiset.mem_to_finset.mpr (subtype.mem x), exact field.to_nontrivial E end } end comm_ring section irreducible variables [field K] {f : polynomial K} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial K)) := principal_ideal_ring.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : field (adjoin_root f) := { ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal (polynomial K)) } lemma coe_injective : function.injective (coe : K → adjoin_root f) := (of f).injective variable (f) lemma mul_div_root_cancel : ((X - C (root f)) * (f.map (of f) / (X - C (root f))) : polynomial (adjoin_root f)) = f.map (of f) := mul_div_eq_iff_is_root.2 $ is_root_root _ end irreducible section power_basis variables [field K] {f : polynomial K} lemma power_basis_is_basis (hf : f ≠ 0) : is_basis K (λ (i : fin f.nat_degree), (root f ^ i.val)) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have f'_monic : monic f' := monic_mul_leading_coeff_inv hf, have aeval_f' : aeval (root f) f' = 0, { rw [f'_def, alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, have hx : is_integral K (root f) := ⟨f', f'_monic, aeval_f'⟩, have minpoly_eq : f' = minpoly K (root f), { apply minpoly.unique K _ f'_monic aeval_f', intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, deg_f'], apply nat_degree_le_of_dvd, { rw [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem], change mk f q = 0, rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero] }, { exact q_monic.ne_zero } }, refine ⟨_, eq_top_iff.mpr _⟩, { rw [←deg_f', minpoly_eq], exact hx.linear_independent_pow }, { rintros y -, rw [←deg_f', minpoly_eq], apply hx.mem_span_pow, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ noncomputable def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, is_basis := power_basis_is_basis hf } end power_basis end adjoin_root
aa4f9341a348f28f6d764f55e155a328dd21e36e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/homology/differential_object.lean
02f49a1f5775f2545e937dc937902d48c1b22064
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,640
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.homology.homological_complex import category_theory.differential_object /-! # Homological complexes are differential graded objects. We verify that a `homological_complex` indexed by an `add_comm_group` is essentially the same thing as a differential graded object. This equivalence is probably not particularly useful in practice; it's here to check that definitions match up as expected. -/ open category_theory open category_theory.limits open_locale classical noncomputable theory namespace homological_complex variables {β : Type*} [add_comm_group β] (b : β) variables (V : Type*) [category V] [has_zero_morphisms V] /-- The functor from differential graded objects to homological complexes. -/ @[simps] def dgo_to_homological_complex : differential_object (graded_object_with_shift b V) ⥤ homological_complex V (complex_shape.up' b) := { obj := λ X, { X := λ i, X.X i, d := λ i j, if h : i + b = j then X.d i ≫ eq_to_hom (congr_arg X.X h) else 0, shape' := λ i j w, by { dsimp at w, rw dif_neg w, }, d_comp_d' := λ i j k hij hjk, begin dsimp at hij hjk, substs hij hjk, simp only [category.comp_id, eq_to_hom_refl, dif_pos rfl], exact congr_fun (X.d_squared) i, end }, map := λ X Y f, { f := f.f, comm' := λ i j h, begin dsimp at h ⊢, subst h, simp only [category.comp_id, eq_to_hom_refl, dif_pos rfl], exact (congr_fun f.comm i).symm end, } } /-- The functor from homological complexes to differential graded objects. -/ @[simps] def homological_complex_to_dgo : homological_complex V (complex_shape.up' b) ⥤ differential_object (graded_object_with_shift b V) := { obj := λ X, { X := λ i, X.X i, d := λ i, X.d i (i + b), d_squared' := by { ext i, dsimp, simp, } }, map := λ X Y f, { f := f.f, comm' := by { ext i, dsimp, simp, }, } } /-- The unit isomorphism for `dgo_equiv_homological_complex`. -/ @[simps] def dgo_equiv_homological_complex_unit_iso : 𝟭 (differential_object (graded_object_with_shift b V)) ≅ dgo_to_homological_complex b V ⋙ homological_complex_to_dgo b V := nat_iso.of_components (λ X, { hom := { f := λ i, 𝟙 (X.X i), }, inv := { f := λ i, 𝟙 (X.X i), }, }) (by tidy) /-- The counit isomorphism for `dgo_equiv_homological_complex`. -/ @[simps] def dgo_equiv_homological_complex_counit_iso : homological_complex_to_dgo b V ⋙ dgo_to_homological_complex b V ≅ 𝟭 (homological_complex V (complex_shape.up' b)) := nat_iso.of_components (λ X, { hom := { f := λ i, 𝟙 (X.X i), comm' := λ i j h, begin dsimp at h ⊢, subst h, simp only [category.comp_id, category.id_comp, dif_pos rfl, eq_to_hom_refl], end }, inv := { f := λ i, 𝟙 (X.X i), comm' := λ i j h, begin dsimp at h ⊢, subst h, simp only [category.comp_id, category.id_comp, dif_pos rfl, eq_to_hom_refl], end }, }) (by tidy) /-- The category of differential graded objects in `V` is equivalent to the category of homological complexes in `V`. -/ @[simps] def dgo_equiv_homological_complex : differential_object (graded_object_with_shift b V) ≌ homological_complex V (complex_shape.up' b) := { functor := dgo_to_homological_complex b V, inverse := homological_complex_to_dgo b V, unit_iso := dgo_equiv_homological_complex_unit_iso b V, counit_iso := dgo_equiv_homological_complex_counit_iso b V, } end homological_complex
a1cd3175a51d5f00404fd3515d01b86777177177
1f6fe2f89976b14a4567ab298c35792b21f2e50b
/algebra/spectral_sequence.hlean
42eeb34f3f447b78f9b0a3c9eaf2a89cfc245aec
[ "Apache-2.0" ]
permissive
jonas-frey/Spectral
e5c1c2f7bcac26aa55f7b1e041a81272a146198d
72d521091525a4bc9a31cac859840efe9461cf66
refs/heads/master
1,610,235,743,345
1,505,417,795,000
1,505,417,795,000
102,653,342
0
0
null
1,504,728,483,000
1,504,728,483,000
null
UTF-8
Lean
false
false
29,424
hlean
/- Exact couples of graded (left-) R-modules. This file includes: - Constructing exact couples from sequences of maps - Deriving an exact couple - The convergence theorem for exact couples -/ -- Author: Floris van Doorn import .graded ..spectrum.basic .product_group open algebra is_trunc left_module is_equiv equiv eq function nat sigma sigma.ops set_quotient /- exact couples -/ namespace left_module structure exact_couple (R : Ring) (I : Set) : Type := (D E : graded_module R I) (i : D →gm D) (j : D →gm E) (k : E →gm D) (ij : is_exact_gmod i j) (jk : is_exact_gmod j k) (ki : is_exact_gmod k i) open exact_couple namespace derived_couple section parameters {R : Ring} {I : Set} (X : exact_couple R I) local abbreviation D := D X local abbreviation E := E X local abbreviation i := i X local abbreviation j := j X local abbreviation k := k X local abbreviation ij := ij X local abbreviation jk := jk X local abbreviation ki := ki X definition d : E →gm E := j ∘gm k definition D' : graded_module R I := graded_image i definition E' : graded_module R I := graded_homology d d definition is_contr_E' {x : I} (H : is_contr (E x)) : is_contr (E' x) := !is_contr_homology definition is_contr_D' {x : I} (H : is_contr (D x)) : is_contr (D' x) := !is_contr_image_module definition i' : D' →gm D' := graded_image_lift i ∘gm graded_submodule_incl (λx, image (i ← x)) lemma is_surjective_i' {x y : I} (p : deg i' x = y) (H : Π⦃z⦄ (q : deg i z = x), is_surjective (i ↘ q)) : is_surjective (i' ↘ p) := begin apply is_surjective_graded_hom_compose, { intro y q, apply is_surjective_graded_image_lift }, { intro y q, apply is_surjective_of_is_equiv, induction q, exact to_is_equiv (equiv_of_isomorphism (image_module_isomorphism (i ← x) (H _))) } end lemma j_lemma1 ⦃x : I⦄ (m : D x) : d ((deg j) x) (j x m) = 0 := begin rewrite [graded_hom_compose_fn,↑d,graded_hom_compose_fn], refine ap (graded_hom_fn j (deg k (deg j x))) _ ⬝ !to_respect_zero, exact compose_constant.elim (gmod_im_in_ker (jk)) x m end lemma j_lemma2 : Π⦃x : I⦄ ⦃m : D x⦄ (p : i x m = 0), (graded_homology_intro _ _ ∘gm graded_hom_lift _ j j_lemma1) x m = 0 :> E' _ := begin have Π⦃x y : I⦄ (q : deg k x = y) (r : deg d x = deg j y) (s : ap (deg j) q = r) ⦃m : D y⦄ (p : i y m = 0), image (d ↘ r) (j y m), begin intros, induction s, induction q, note m_in_im_k := is_exact.ker_in_im (ki idp _) _ p, induction m_in_im_k with e q, induction q, apply image.mk e idp end, have Π⦃x : I⦄ ⦃m : D x⦄ (p : i x m = 0), image (d ← (deg j x)) (j x m), begin intros, refine this _ _ _ p, exact to_right_inv (deg k) _ ⬝ to_left_inv (deg j) x, apply is_set.elim -- rewrite [ap_con, -adj], end, intros, rewrite [graded_hom_compose_fn], exact @quotient_map_eq_zero _ _ _ _ _ (this p) end definition j' : D' →gm E' := graded_image_elim (graded_homology_intro d d ∘gm graded_hom_lift _ j j_lemma1) j_lemma2 -- degree deg j - deg i lemma k_lemma1 ⦃x : I⦄ (m : E x) (p : d x m = 0) : image (i ← (deg k x)) (k x m) := gmod_ker_in_im (exact_couple.ij X) (k x m) p definition k₂ : graded_kernel d →gm D' := graded_submodule_functor k k_lemma1 lemma k_lemma2 ⦃x : I⦄ (m : E x) (h₁ : lm_kernel (d x) m) (h₂ : image (d ← x) m) : k₂ x ⟨m, h₁⟩ = 0 := begin assert H₁ : Π⦃x' y z w : I⦄ (p : deg k x' = y) (q : deg j y = z) (r : deg k z = w) (n : E x'), k ↘ r (j ↘ q (k ↘ p n)) = 0, { intros, exact gmod_im_in_ker (exact_couple.jk X) q r (k ↘ p n) }, induction h₂ with n p, assert H₂ : k x m = 0, { rewrite [-p], refine ap (k x) (graded_hom_compose_fn_out j k x n) ⬝ _, apply H₁ }, exact subtype_eq H₂ end definition k' : E' →gm D' := @graded_quotient_elim _ _ _ _ _ _ (graded_submodule_functor k k_lemma1) (by intro x m h; cases m with [m1, m2]; exact k_lemma2 m1 m2 h) definition i'_eq ⦃x : I⦄ (m : D x) (h : image (i ← x) m) : (i' x ⟨m, h⟩).1 = i x m := by reflexivity definition k'_eq ⦃x : I⦄ (m : E x) (h : d x m = 0) : (k' x (class_of ⟨m, h⟩)).1 = k x m := by reflexivity lemma j'_eq {x : I} (m : D x) : j' ↘ (ap (deg j) (left_inv (deg i) x)) (graded_image_lift i x m) = class_of (graded_hom_lift _ j proof j_lemma1 qed x m) := begin refine graded_image_elim_destruct _ _ _ idp _ m, apply is_set.elim, end definition deg_i' : deg i' ~ deg i := by reflexivity definition deg_j' : deg j' ~ deg j ∘ (deg i)⁻¹ := by reflexivity definition deg_k' : deg k' ~ deg k := by reflexivity open group set_option pp.coercions true lemma i'j' : is_exact_gmod i' j' := begin intro x, refine equiv_rect (deg i) _ _, intros y z p q, revert z q x p, refine eq.rec_grading (deg i ⬝e deg j') (deg j) (ap (deg j) (left_inv (deg i) y)) _, intro x, revert y, refine eq.rec_equiv (deg i) _, apply transport (λx, is_exact_mod x _) (idpath (i' x)), apply transport (λx, is_exact_mod _ (j' ↘ (ap (deg j) (left_inv (deg i) x)))) (idpath x), apply is_exact_mod.mk, { revert x, refine equiv_rect (deg i) _ _, intro x, refine graded_image.rec _, intro m, transitivity j' ↘ _ (graded_image_lift i (deg i x) (i x m)), apply ap (λx, j' ↘ _ x), apply subtype_eq, apply i'_eq, refine !j'_eq ⬝ _, apply ap class_of, apply subtype_eq, exact is_exact.im_in_ker (exact_couple.ij X idp idp) m }, { revert x, refine equiv_rect (deg k) _ _, intro x, refine graded_image.rec _, intro m p, assert q : graded_homology_intro d d (deg j (deg k x)) (graded_hom_lift _ j j_lemma1 (deg k x) m) = 0, { exact !j'_eq⁻¹ ⬝ p }, note q2 := image_of_graded_homology_intro_eq_zero idp (graded_hom_lift _ j _ _ m) q, induction q2 with n r, assert s : j (deg k x) (m - k x n) = 0, { refine respect_sub (j (deg k x)) m (k x n) ⬝ _, refine ap (sub _) r ⬝ _, apply sub_self }, assert t : trunctype.carrier (image (i ← (deg k x)) (m - k x n)), { exact is_exact.ker_in_im (exact_couple.ij X _ _) _ s }, refine image.mk ⟨m - k x n, t⟩ _, apply subtype_eq, refine !i'_eq ⬝ !to_respect_sub ⬝ _, refine ap (@sub (D (deg i (deg k x))) _ _) _ ⬝ @sub_zero _ _ _, apply is_exact.im_in_ker (exact_couple.ki X _ _) } end lemma j'k' : is_exact_gmod j' k' := begin refine equiv_rect (deg i) _ _, intros x y z p, revert y p z, refine eq.rec_grading (deg i ⬝e deg j') (deg j) (ap (deg j) (left_inv (deg i) x)) _, intro z q, induction q, apply is_exact_mod.mk, { refine graded_image.rec _, intro m, refine ap (k' _) (j'_eq m) ⬝ _, apply subtype_eq, refine k'_eq _ _ ⬝ _, exact is_exact.im_in_ker (exact_couple.jk X idp idp) m }, { intro m p, induction m using set_quotient.rec_prop with m, induction m with m h, note q := (k'_eq m h)⁻¹ ⬝ ap pr1 p, induction is_exact.ker_in_im (exact_couple.jk X idp idp) m q with n r, apply image.mk (graded_image_lift i x n), refine !j'_eq ⬝ _, apply ap class_of, apply subtype_eq, exact r } end lemma k'i' : is_exact_gmod k' i' := begin apply is_exact_gmod.mk, { intro x m, induction m using set_quotient.rec_prop with m, cases m with m p, apply subtype_eq, change i (deg k x) (k x m) = 0, exact is_exact.im_in_ker (exact_couple.ki X idp idp) m }, { intro x m, induction m with m h, intro p, have i (deg k x) m = 0, from ap pr1 p, induction is_exact.ker_in_im (exact_couple.ki X idp idp) m this with n q, have j (deg k x) m = 0, from @(is_exact.im_in_ker2 (exact_couple.ij X _ _)) m h, have d x n = 0, from ap (j (deg k x)) q ⬝ this, exact image.mk (class_of ⟨n, this⟩) (subtype_eq q) } end end end derived_couple open derived_couple definition derived_couple [constructor] {R : Ring} {I : Set} (X : exact_couple R I) : exact_couple R I := ⦃exact_couple, D := D' X, E := E' X, i := i' X, j := j' X, k := k' X, ij := i'j' X, jk := j'k' X, ki := k'i' X⦄ /- if an exact couple is bounded, we can prove the convergence theorem for it -/ structure is_bounded {R : Ring} {I : Set} (X : exact_couple R I) : Type := mk' :: (B B' : I → ℕ) (Dub : Π⦃x y⦄ ⦃s : ℕ⦄, (deg (i X))^[s] x = y → B x ≤ s → is_contr (D X y)) (Dlb : Π⦃x y z⦄ ⦃s : ℕ⦄ (p : deg (i X) x = y), (deg (i X))^[s] y = z → B' z ≤ s → is_surjective (i X ↘ p)) (Elb : Π⦃x y⦄ ⦃s : ℕ⦄, (deg (i X))⁻¹ᵉ^[s] x = y → B x ≤ s → is_contr (E X y)) (deg_ik_commute : hsquare (deg (k X)) (deg (k X)) (deg (i X)) (deg (i X))) (deg_ij_commute : hsquare (deg (j X)) (deg (j X)) (deg (i X)) (deg (i X))) /- Note: Elb proves Dlb for some bound B', but we want tight control over when B' = 0 -/ protected definition is_bounded.mk [constructor] {R : Ring} {I : Set} {X : exact_couple R I} (B B' B'' : I → ℕ) (Dub : Π⦃x : I⦄ ⦃s : ℕ⦄, B x ≤ s → is_contr (D X ((deg (i X))^[s] x))) (Dlb : Π⦃x : I⦄ ⦃s : ℕ⦄, B' x ≤ s → is_surjective (i X (((deg (i X))⁻¹ᵉ^[s + 1] x)))) (Elb : Π⦃x : I⦄ ⦃s : ℕ⦄, B'' x ≤ s → is_contr (E X ((deg (i X))⁻¹ᵉ^[s] x))) (deg_ik_commute : hsquare (deg (k X)) (deg (k X)) (deg (i X)) (deg (i X))) (deg_ij_commute : hsquare (deg (j X)) (deg (j X)) (deg (i X)) (deg (i X))) : is_bounded X := begin apply is_bounded.mk' (λx, max (B x) (B'' x)) B', { intro x y s p h, induction p, exact Dub (le.trans !le_max_left h) }, { intro x y z s p q h, induction p, induction q, refine transport (λx, is_surjective (i X x)) _ (Dlb h), rewrite [-iterate_succ], apply iterate_left_inv }, { intro x y s p h, induction p, exact Elb (le.trans !le_max_right h) }, { assumption }, { assumption } end namespace convergence_theorem section open is_bounded parameters {R : Ring} {I : Set} (X : exact_couple R I) (HH : is_bounded X) local abbreviation B := B HH local abbreviation B' := B' HH local abbreviation Dub := Dub HH local abbreviation Dlb := Dlb HH local abbreviation Elb := Elb HH local abbreviation deg_ik_commute := deg_ik_commute HH local abbreviation deg_ij_commute := deg_ij_commute HH definition deg_iterate_ik_commute (n : ℕ) : hsquare (deg (k X)) (deg (k X)) ((deg (i X))^[n]) ((deg (i X))^[n]) := iterate_commute n deg_ik_commute definition deg_iterate_ij_commute (n : ℕ) : hsquare (deg (j X)) (deg (j X)) ((deg (i X))⁻¹ᵉ^[n]) ((deg (i X))⁻¹ᵉ^[n]) := iterate_commute n (hvinverse deg_ij_commute) definition B2 (x : I) : ℕ := max (B (deg (k X) x)) (B ((deg (j X))⁻¹ x)) definition Eub ⦃x y : I⦄ ⦃s : ℕ⦄ (p : (deg (i X))^[s] x = y) (h : B2 x ≤ s) : is_contr (E X y) := begin induction p, refine @(is_contr_middle_of_is_exact (exact_couple.jk X (right_inv (deg (j X)) _) idp)) _ _ _, exact Dub (iterate_commute s (hhinverse deg_ij_commute) x) (le.trans !le_max_right h), exact Dub !deg_iterate_ik_commute (le.trans !le_max_left h) end -- we start counting pages at 0 definition page (r : ℕ) : exact_couple R I := iterate derived_couple r X definition is_contr_E (r : ℕ) (x : I) (h : is_contr (E X x)) : is_contr (E (page r) x) := by induction r with r IH; exact h; exact is_contr_E' (page r) IH definition is_contr_D (r : ℕ) (x : I) (h : is_contr (D X x)) : is_contr (D (page r) x) := by induction r with r IH; exact h; exact is_contr_D' (page r) IH definition deg_i (r : ℕ) : deg (i (page r)) ~ deg (i X) := begin induction r with r IH, { reflexivity }, { exact IH } end definition deg_k (r : ℕ) : deg (k (page r)) ~ deg (k X) := begin induction r with r IH, { reflexivity }, { exact IH } end definition deg_j (r : ℕ) : deg (j (page r)) ~ deg (j X) ∘ iterate (deg (i X))⁻¹ r := begin induction r with r IH, { reflexivity }, { refine hwhisker_left (deg (j (page r))) (to_inv_homotopy_inv (deg_i r)) ⬝hty _, refine hwhisker_right _ IH ⬝hty _, apply hwhisker_left, symmetry, apply iterate_succ } end definition deg_j_inv (r : ℕ) : (deg (j (page r)))⁻¹ ~ iterate (deg (i X)) r ∘ (deg (j X))⁻¹ := have H : deg (j (page r)) ~ iterate_equiv (deg (i X))⁻¹ᵉ r ⬝e deg (j X), from deg_j r, λx, to_inv_homotopy_inv H x ⬝ iterate_inv (deg (i X))⁻¹ᵉ r ((deg (j X))⁻¹ x) definition deg_d (r : ℕ) : deg (d (page r)) ~ deg (j X) ∘ iterate (deg (i X))⁻¹ r ∘ deg (k X) := compose2 (deg_j r) (deg_k r) definition deg_d_inv (r : ℕ) : (deg (d (page r)))⁻¹ ~ (deg (k X))⁻¹ ∘ iterate (deg (i X)) r ∘ (deg (j X))⁻¹ := compose2 (to_inv_homotopy_inv (deg_k r)) (deg_j_inv r) definition B3 (x : I) : ℕ := max (B (deg (j X) (deg (k X) x))) (B2 ((deg (k X))⁻¹ ((deg (j X))⁻¹ x))) definition Estable {x : I} {r : ℕ} (H : B3 x ≤ r) : E (page (r + 1)) x ≃lm E (page r) x := begin change homology (d (page r) x) (d (page r) ← x) ≃lm E (page r) x, apply homology_isomorphism: apply is_contr_E, exact Eub (hhinverse (deg_iterate_ik_commute r) _ ⬝ (deg_d_inv r x)⁻¹) (le.trans !le_max_right H), exact Elb (deg_iterate_ij_commute r _ ⬝ (deg_d r x)⁻¹) (le.trans !le_max_left H) end definition is_surjective_i {x y z : I} {r s : ℕ} (H : B' z ≤ s + r) (p : deg (i (page r)) x = y) (q : iterate (deg (i X)) s y = z) : is_surjective (i (page r) ↘ p) := begin revert x y z s H p q, induction r with r IH: intro x y z s H p q, { exact Dlb p q H }, /- the following is a start of the proof that i is surjective using that E is contractible (but this makes the bound 1 higher than necessary -/ -- induction p, change is_surjective (i X x), -- apply @(is_surjective_of_is_exact_of_is_contr (exact_couple.ij X idp idp)), -- refine Elb _ H, -- exact sorry { change is_surjective (i' (page r) ↘ p), apply is_surjective_i', intro z' q', refine IH _ _ _ _ (le.trans H (le_of_eq (succ_add s r)⁻¹)) _ _, refine !iterate_succ ⬝ ap ((deg (i X))^[s]) _ ⬝ q, exact !deg_i⁻¹ ⬝ p } end definition Dstable {x : I} {r : ℕ} (H : B' x ≤ r) : D (page (r + 1)) x ≃lm D (page r) x := begin change image_module (i (page r) ← x) ≃lm D (page r) x, refine image_module_isomorphism (i (page r) ← x) (is_surjective_i (le.trans H (le_of_eq !zero_add⁻¹)) _ _), reflexivity end /- the infinity pages of E and D -/ definition Einf : graded_module R I := λx, E (page (B3 x)) x definition Dinf : graded_module R I := λx, D (page (B' x)) x definition Einfstable {x y : I} {r : ℕ} (Hr : B3 y ≤ r) (p : x = y) : Einf y ≃lm E (page r) x := by symmetry; induction p; induction Hr with r Hr IH; reflexivity; exact Estable Hr ⬝lm IH definition Dinfstable {x y : I} {r : ℕ} (Hr : B' y ≤ r) (p : x = y) : Dinf y ≃lm D (page r) x := by symmetry; induction p; induction Hr with r Hr IH; reflexivity; exact Dstable Hr ⬝lm IH parameters (x : I) definition r (n : ℕ) : ℕ := max (max (B (deg (j X) (deg (k X) x)) + n + 1) (B3 ((deg (i X))^[n] x))) (max (B' (deg (k X) ((deg (i X))^[n] x))) (max (B' (deg (k X) ((deg (i X))^[n+1] x))) (B ((deg (j X))⁻¹ ((deg (i X))^[n] x))))) lemma rb0 (n : ℕ) : r n ≥ n + 1 := ge.trans !le_max_left (ge.trans !le_max_left !le_add_left) lemma rb1 (n : ℕ) : B (deg (j X) (deg (k X) x)) ≤ r n - (n + 1) := nat.le_sub_of_add_le (le.trans !le_max_left !le_max_left) lemma rb2 (n : ℕ) : B3 ((deg (i X))^[n] x) ≤ r n := le.trans !le_max_right !le_max_left lemma rb3 (n : ℕ) : B' (deg (k X) ((deg (i X))^[n] x)) ≤ r n := le.trans !le_max_left !le_max_right lemma rb4 (n : ℕ) : B' (deg (k X) ((deg (i X))^[n+1] x)) ≤ r n := le.trans (le.trans !le_max_left !le_max_right) !le_max_right lemma rb5 (n : ℕ) : B ((deg (j X))⁻¹ ((deg (i X))^[n] x)) ≤ r n := le.trans (le.trans !le_max_right !le_max_right) !le_max_right definition Einfdiag : graded_module R ℕ := λn, Einf ((deg (i X))^[n] x) definition Dinfdiag : graded_module R ℕ := λn, Dinf (deg (k X) ((deg (i X))^[n] x)) definition short_exact_mod_page_r (n : ℕ) : short_exact_mod (E (page (r n)) ((deg (i X))^[n] x)) (D (page (r n)) (deg (k (page (r n))) ((deg (i X))^[n] x))) (D (page (r n)) (deg (i (page (r n))) (deg (k (page (r n))) ((deg (i X))^[n] x)))) := begin fapply short_exact_mod_of_is_exact, { exact j (page (r n)) ← ((deg (i X))^[n] x) }, { exact k (page (r n)) ((deg (i X))^[n] x) }, { exact i (page (r n)) (deg (k (page (r n))) ((deg (i X))^[n] x)) }, { exact j (page (r n)) _ }, { apply is_contr_D, refine Dub !deg_j_inv⁻¹ (rb5 n) }, { apply is_contr_E, refine Elb _ (rb1 n), refine !deg_iterate_ij_commute ⬝ _, refine ap (deg (j X)) _ ⬝ !deg_j⁻¹, refine iterate_sub _ !rb0 _ ⬝ _, apply ap (_^[r n]), exact ap (deg (i X)) (!deg_iterate_ik_commute ⬝ !deg_k⁻¹) ⬝ !deg_i⁻¹ }, { apply jk (page (r n)) }, { apply ki (page (r n)) }, { apply ij (page (r n)) } end /- the convergence theorem is a combination of the following three results -/ definition short_exact_mod_infpage (n : ℕ) : short_exact_mod (Einfdiag n) (Dinfdiag n) (Dinfdiag (n+1)) := begin refine short_exact_mod_isomorphism _ _ _ (short_exact_mod_page_r n), { exact Einfstable !rb2 idp }, { exact Dinfstable !rb3 !deg_k }, { exact Dinfstable !rb4 (!deg_i ⬝ ap (deg (i X)) !deg_k ⬝ !deg_ik_commute) } end definition Dinfdiag0 (bound_zero : B' (deg (k X) x) = 0) : Dinfdiag 0 ≃lm D X (deg (k X) x) := Dinfstable (le_of_eq bound_zero) idp lemma Dinfdiag_stable {s : ℕ} (h : B (deg (k X) x) ≤ s) : is_contr (Dinfdiag s) := is_contr_D _ _ (Dub !deg_iterate_ik_commute h) end end convergence_theorem -- open convergence_theorem -- print axioms short_exact_mod_infpage -- print axioms Dinfdiag0 -- print axioms Dinfdiag_stable open int group prod convergence_theorem prod.ops definition Z2 [constructor] : Set := gℤ ×g gℤ structure converges_to.{u v w} {R : Ring} (E' : gℤ → gℤ → LeftModule.{u v} R) (Dinf : gℤ → LeftModule.{u w} R) : Type.{max u (v+1) (w+1)} := (X : exact_couple.{u 0 v w} R Z2) (HH : is_bounded X) (s₀ : gℤ → gℤ) (p : Π(n : gℤ), is_bounded.B' HH (deg (k X) (n, s₀ n)) = 0) (e : Π(x : gℤ ×g gℤ), exact_couple.E X x ≃lm E' x.1 x.2) (f : Π(n : gℤ), exact_couple.D X (deg (k X) (n, s₀ n)) ≃lm Dinf n) infix ` ⟹ `:25 := converges_to definition converges_to_g [reducible] (E' : gℤ → gℤ → AbGroup) (Dinf : gℤ → AbGroup) : Type := (λn s, LeftModule_int_of_AbGroup (E' n s)) ⟹ (λn, LeftModule_int_of_AbGroup (Dinf n)) infix ` ⟹ᵍ `:25 := converges_to_g section open converges_to parameters {R : Ring} {E' : gℤ → gℤ → LeftModule R} {Dinf : gℤ → LeftModule R} (c : E' ⟹ Dinf) local abbreviation X := X c local abbreviation i := i X local abbreviation HH := HH c local abbreviation s₀ := s₀ c local abbreviation Dinfdiag (n : gℤ) (k : ℕ) := Dinfdiag X HH (n, s₀ n) k local abbreviation Einfdiag (n : gℤ) (k : ℕ) := Einfdiag X HH (n, s₀ n) k definition converges_to_isomorphism {E'' : gℤ → gℤ → LeftModule R} {Dinf' : graded_module R gℤ} (e' : Πn s, E' n s ≃lm E'' n s) (f' : Πn, Dinf n ≃lm Dinf' n) : E'' ⟹ Dinf' := converges_to.mk X HH s₀ (p c) begin intro x, induction x with n s, exact e c (n, s) ⬝lm e' n s end (λn, f c n ⬝lm f' n) theorem is_contr_converges_to_precise (n : gℤ) (H : Π(n : gℤ) (l : ℕ), is_contr (E' ((deg i)^[l] (n, s₀ n)).1 ((deg i)^[l] (n, s₀ n)).2)) : is_contr (Dinf n) := begin assert H2 : Π(l : ℕ), is_contr (Einfdiag n l), { intro l, apply is_contr_E, refine @(is_trunc_equiv_closed_rev -2 (equiv_of_isomorphism (e c _))) (H n l) }, assert H3 : is_contr (Dinfdiag n 0), { fapply nat.rec_down (λk, is_contr (Dinfdiag n k)), { exact is_bounded.B HH (deg (k X) (n, s₀ n)) }, { apply Dinfdiag_stable, reflexivity }, { intro l H, exact is_contr_middle_of_short_exact_mod (short_exact_mod_infpage X HH (n, s₀ n) l) (H2 l) H }}, refine @is_trunc_equiv_closed _ _ _ _ H3, exact equiv_of_isomorphism (Dinfdiag0 X HH (n, s₀ n) (p c n) ⬝lm f c n) end theorem is_contr_converges_to (n : gℤ) (H : Π(n s : gℤ), is_contr (E' n s)) : is_contr (Dinf n) := is_contr_converges_to_precise n (λn s, !H) end variables {E' : gℤ → gℤ → AbGroup} {Dinf : gℤ → AbGroup} (c : E' ⟹ᵍ Dinf) definition converges_to_g_isomorphism {E'' : gℤ → gℤ → AbGroup} {Dinf' : gℤ → AbGroup} (e' : Πn s, E' n s ≃g E'' n s) (f' : Πn, Dinf n ≃g Dinf' n) : E'' ⟹ᵍ Dinf' := converges_to_isomorphism c (λn s, lm_iso_int.mk (e' n s)) (λn, lm_iso_int.mk (f' n)) end left_module open left_module namespace pointed open pointed int group is_trunc trunc is_conn definition homotopy_group_conn_nat (n : ℕ) (A : Type*[1]) : AbGroup := AbGroup.mk (π[n] A) (ab_group_homotopy_group_of_is_conn n A) definition homotopy_group_conn : Π(n : ℤ) (A : Type*[1]), AbGroup | (of_nat n) A := homotopy_group_conn_nat n A | (-[1+ n]) A := trivial_ab_group_lift notation `πc[`:95 n:0 `]`:0 := homotopy_group_conn n definition homotopy_group_conn_nat_functor (n : ℕ) {A B : Type*[1]} (f : A →* B) : homotopy_group_conn_nat n A →g homotopy_group_conn_nat n B := begin cases n with n, { apply trivial_homomorphism }, cases n with n, { apply trivial_homomorphism }, exact π→g[n+2] f end definition homotopy_group_conn_functor : Π(n : ℤ) {A B : Type*[1]} (f : A →* B), πc[n] A →g πc[n] B | (of_nat n) A B f := homotopy_group_conn_nat_functor n f | (-[1+ n]) A B f := trivial_homomorphism _ _ notation `π→c[`:95 n:0 `]`:0 := homotopy_group_conn_functor n section open prod prod.ops fiber parameters {A : ℤ → Type*[1]} (f : Π(n : ℤ), A n →* A (n - 1)) [Hf : Πn, is_conn_fun 1 (f n)] include Hf local abbreviation I [constructor] := Z2 -- definition D_sequence : graded_module rℤ I := -- λv, LeftModule_int_of_AbGroup (πc[v.2] (A (v.1))) -- definition E_sequence : graded_module rℤ I := -- λv, LeftModule_int_of_AbGroup (πc[v.2] (pconntype.mk (pfiber (f (v.1))) !Hf pt)) /- first need LES of these connected homotopy groups -/ -- definition exact_couple_sequence : exact_couple rℤ I := -- exact_couple.mk D_sequence E_sequence sorry sorry sorry sorry sorry sorry end end pointed namespace spectrum open pointed int group is_trunc trunc is_conn prod prod.ops group fin chain_complex section parameters {A : ℤ → spectrum} (f : Π(s : ℤ), A s →ₛ A (s - 1)) -- protected definition I [constructor] : Set := gℤ ×g gℤ local abbreviation I [constructor] := Z2 definition D_sequence : graded_module rℤ I := λv, LeftModule_int_of_AbGroup (πₛ[v.1] (A (v.2))) definition E_sequence : graded_module rℤ I := λv, LeftModule_int_of_AbGroup (πₛ[v.1] (sfiber (f (v.2)))) include f definition i_sequence : D_sequence →gm D_sequence := begin fapply graded_hom.mk, exact (prod_equiv_prod erfl (add_right_action (- 1))), intro v, apply lm_hom_int.mk, esimp, exact πₛ→[v.1] (f v.2) end definition deg_j_seq_inv [constructor] : I ≃ I := prod_equiv_prod (add_right_action 1) (add_right_action (- 1)) definition fn_j_sequence [unfold 3] (x : I) : D_sequence (deg_j_seq_inv x) →lm E_sequence x := begin induction x with n s, apply lm_hom_int.mk, esimp, rexact shomotopy_groups_fun (f s) (n, 2) end definition j_sequence : D_sequence →gm E_sequence := graded_hom.mk_out deg_j_seq_inv⁻¹ᵉ fn_j_sequence definition k_sequence : E_sequence →gm D_sequence := begin fapply graded_hom.mk erfl, intro v, induction v with n s, apply lm_hom_int.mk, esimp, exact πₛ→[n] (spoint (f s)) end lemma ij_sequence : is_exact_gmod i_sequence j_sequence := begin intro x y z p q, revert y z q p, refine eq.rec_right_inv (deg j_sequence) _, intro y, induction x with n s, induction y with m t, refine equiv_rect !pair_eq_pair_equiv⁻¹ᵉ _ _, intro pq, esimp at pq, induction pq with p q, revert t q, refine eq.rec_equiv (add_right_action (- 1)) _, induction p using eq.rec_symm, apply is_exact_homotopy homotopy.rfl, { symmetry, exact graded_hom_mk_out_destruct deg_j_seq_inv⁻¹ᵉ fn_j_sequence }, rexact is_exact_of_is_exact_at (is_exact_LES_of_shomotopy_groups (f s) (m, 2)), end lemma jk_sequence : is_exact_gmod j_sequence k_sequence := begin intro x y z p q, induction q, revert x y p, refine eq.rec_right_inv (deg j_sequence) _, intro x, induction x with n s, apply is_exact_homotopy, { symmetry, exact graded_hom_mk_out_destruct deg_j_seq_inv⁻¹ᵉ fn_j_sequence }, { reflexivity }, rexact is_exact_of_is_exact_at (is_exact_LES_of_shomotopy_groups (f s) (n, 1)), end lemma ki_sequence : is_exact_gmod k_sequence i_sequence := begin intro i j k p q, induction p, induction q, induction i with n s, rexact is_exact_of_is_exact_at (is_exact_LES_of_shomotopy_groups (f s) (n, 0)), end definition exact_couple_sequence [constructor] : exact_couple rℤ I := exact_couple.mk D_sequence E_sequence i_sequence j_sequence k_sequence ij_sequence jk_sequence ki_sequence open int parameters (ub : ℤ) (lb : ℤ → ℤ) (Aub : Π(s n : ℤ), s ≥ ub + 1 → is_equiv (f s n)) (Alb : Π(s n : ℤ), s ≤ lb n → is_contr (πₛ[n] (A s))) definition B : I → ℕ | (n, s) := max0 (s - lb n) definition B' : I → ℕ | (n, s) := max0 (ub - s) definition B'' : I → ℕ | (n, s) := max0 (ub + 1 - s) lemma iterate_deg_i (n s : ℤ) (m : ℕ) : (deg i_sequence)^[m] (n, s) = (n, s - m) := begin induction m with m IH, { exact prod_eq idp !sub_zero⁻¹ }, { exact ap (deg i_sequence) IH ⬝ (prod_eq idp !sub_sub) } end lemma iterate_deg_i_inv (n s : ℤ) (m : ℕ) : (deg i_sequence)⁻¹ᵉ^[m] (n, s) = (n, s + m) := begin induction m with m IH, { exact prod_eq idp !add_zero⁻¹ }, { exact ap (deg i_sequence)⁻¹ᵉ IH ⬝ (prod_eq idp !add.assoc) } end include Aub Alb lemma Dub ⦃x : I⦄ ⦃t : ℕ⦄ (h : B x ≤ t) : is_contr (D_sequence ((deg i_sequence)^[t] x)) := begin apply Alb, induction x with n s, rewrite [iterate_deg_i], apply sub_le_of_sub_le, exact le_of_max0_le h, end lemma Dlb ⦃x : I⦄ ⦃t : ℕ⦄ (h : B' x ≤ t) : is_surjective (i_sequence ((deg i_sequence)⁻¹ᵉ^[t+1] x)) := begin apply is_surjective_of_is_equiv, apply is_equiv_homotopy_group_functor, apply Aub, induction x with n s, rewrite [iterate_deg_i_inv, ▸*, of_nat_add, -add.assoc], apply add_le_add_right, apply le_add_of_sub_left_le, exact le_of_max0_le h end lemma Elb ⦃x : I⦄ ⦃t : ℕ⦄ (h : B'' x ≤ t) : is_contr (E_sequence ((deg i_sequence)⁻¹ᵉ^[t] x)) := begin apply is_contr_homotopy_group_of_is_contr, apply is_contr_fiber_of_is_equiv, apply Aub, induction x with n s, rewrite [iterate_deg_i_inv, ▸*], apply le_add_of_sub_left_le, apply le_of_max0_le h, end definition is_bounded_sequence [constructor] : is_bounded exact_couple_sequence := is_bounded.mk B B' B'' Dub Dlb Elb (by intro x; reflexivity) begin intro x, induction x with n s, apply pair_eq, esimp, esimp, esimp [j_sequence, i_sequence], refine !add.assoc ⬝ ap (add s) !add.comm ⬝ !add.assoc⁻¹, end definition converges_to_sequence : (λn s, πₛ[n] (sfiber (f s))) ⟹ᵍ (λn, πₛ[n] (A ub)) := begin fapply converges_to.mk, { exact exact_couple_sequence }, { exact is_bounded_sequence }, { intro n, exact ub }, { intro n, change max0 (ub - ub) = 0, exact ap max0 (sub_self ub) }, { intro ns, reflexivity }, { intro n, reflexivity } end end -- Uncomment the next line to see that the proof uses univalence, but that there are no holes --('sorry') in the proof: -- print axioms is_bounded_sequence -- I think it depends on univalence in an essential way. The reason is that the long exact sequence -- of homotopy groups already depends on univalence. Namely, in that proof we need to show that if f -- : A → B and g : B → C are exact at B, then ∥A∥₀ → ∥B∥₀ → ∥C∥₀ is exact at ∥B∥₀. For this we need -- that the equality |b|₀ = |b'|₀ is equivalent to ∥b = b'∥₋₁, which requires univalence. end spectrum
a70cbe71bc0f4a387614ad920f0e733fe63f7e31
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/padics/hensel.lean
499605aa266135cca3d4d20dd00eed7f8a7f3ab0
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
20,631
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import analysis.specific_limits.basic import data.polynomial.identities import number_theory.padics.padic_integers import topology.algebra.polynomial import topology.metric_space.cau_seq_filter /-! # Hensel's lemma on ℤ_p This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> Hensel's lemma gives a simple condition for the existence of a root of a polynomial. The proof and motivation are described in the paper [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]. ## References * <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/Hensel%27s_lemma> ## Tags p-adic, p adic, padic, p-adic integer -/ noncomputable theory open_locale classical topological_space -- We begin with some general lemmas that are used below in the computation. lemma padic_polynomial_dist {p : ℕ} [fact p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz] ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) ... = ∥x - y∥ : by simp open filter metric private lemma comp_tendsto_lim {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) := F.continuous_at.tendsto.comp ncs.tendsto_limit section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 ∥F.derivative.eval a∥) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 (∥F.derivative.eval ncs.lim∥)) := tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _) private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ := tendsto_nhds_unique ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (𝓝 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0) include hnorm /-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/ private def T : ℝ := ∥(F.eval a / (F.derivative.eval a)^2 : ℚ_[p])∥ private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, sq]) private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 := by simp [T, ← padic_int.norm_def] private lemma T_lt_one : T < 1 := let h := (div_lt_one deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_nonneg : 0 ≤ T := norm_nonneg _ private lemma T_pow_nonneg (n : ℕ) : 0 ≤ T ^ n := pow_nonneg T_nonneg _ private lemma T_pow {n : ℕ} (hn : n ≠ 0) : T ^ n < 1 := pow_lt_one T_nonneg T_lt_one hn private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := T_pow (pow_ne_zero _ two_ne_zero) /-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 := calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : norm_div _ _ ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1] ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel _ _ ... ≤ 1 : mul_le_one (padic_int.norm_le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ := calc ∥F.derivative.eval z' - F.derivative.eval z∥ ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _ ... = ∥z1∥ : by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg] ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1 ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel _ _ ... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow' _) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from have hdzne : F.derivative.eval z ≠ 0, from mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), λ h, hdzne $ subtype.ext_iff_val.2 h, let ⟨q, hq⟩ := F.binom_expansion z (-z1) in have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1, by { rw padic_norm_e.mul, exact mul_le_one (padic_int.norm_le_one _) (norm_nonneg _) h1 }, have F.derivative.eval z * (-z1) = -F.eval z, from calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : mul_neg _ _ ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext $ by simp only [padic_int.coe_neg, padic_int.coe_mul, subtype.coe_mk] ... = -(F.eval z) : by simp only [mul_div_cancel' _ hdzne', subtype.coe_eta], have heq : F.eval z' = q * z1^2, by simpa only [sub_eq_add_neg, this, hz', add_right_neg, neg_sq, zero_add] using hq, ⟨q, heq⟩ private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) := calc ∥F.eval z'∥ = ∥q∥ * ∥z1∥^2 : by simp [heq] ... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (pow_nonneg (norm_nonneg _) _) ... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 : by simp [hzeq, hz.1, div_pow] ... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [mul_pow] ... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel _ _ ... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul, pow_succ' 2] set_option eqn_compiler.zeta true /-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/ private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_int.norm_eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ := by simp [newton_seq, newton_seq_aux, ih_n, sub_eq_add_neg, add_comm] private lemma newton_seq_succ_dist (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := calc ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _ ... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm ... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel _ _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, exact div_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm) end private lemma newton_seq_succ_dist_weak (n : ℕ) : ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ∥newton_seq (n+2) - newton_seq (n+1)∥ ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ∥F.eval a∥ / ∥F.derivative.eval a∥ : begin rw [T, sq, pow_one, norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left, apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) | 0 := by simp [T_pow_nonneg hnorm, mul_nonneg] | (k+1) := have 2^n ≤ 2^(n+k), by {apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ∥newton_seq (n + (k + 1)) - newton_seq n∥ = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by rw add_assoc ... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel ... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_int.nonarchimedean _ _ ... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ∥F.derivative.eval a∥ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ | 1 h := by simp [sub_eq_add_neg, add_assoc, newton_seq, newton_seq_aux, ih_n] | (k+2) h := have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt, calc ∥newton_seq (k + 2) - a∥ = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel ... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_int.norm_add_eq_max_of_ne hne' ... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt ... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (𝓝 0) := begin rw ←mul_zero (∥F.derivative.eval a∥), exact tendsto_const_nhds.mul (tendsto.comp (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm)) (nat.tendsto_pow_at_top_at_top_of_one_lt (by norm_num))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε := begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [abs_of_nonneg (T_nonneg _)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (𝓝 0) := begin rw [←mul_zero (∥F.derivative.eval a∥), sq], simp only [mul_assoc], apply tendsto.mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, exact le_rfl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (𝓝 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 (∥F.eval a∥ / ∥F.derivative.eval a∥)) := tendsto_const_nhds.congr' $ eventually_at_top.2 ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩ private lemma newton_seq_dist_tendsto' : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 ∥soln - a∥) := (continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds) private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ := tendsto_nhds_unique newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ := begin rw [soln_dist_to_a, div_lt_iff], { rwa sq at hnorm }, { apply deriv_norm_pos, assumption } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) : z = soln := have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_int.nonarchimedean _ _ ... < ∥F.derivative.eval a∥ : max_lt hnlt (norm_sub_rev soln a ▸ soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [sq, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero_left this, lt_irrefl ∥F.derivative.eval soln∥ (calc ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this ... ≤ 1 * ∥h∥ : by { rw padic_int.norm_mul, exact mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) } ... = ∥z - soln∥ : by simp [h] ... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [sq, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero_left this, lt_irrefl ∥F.derivative.eval a∥ (calc ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this] ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) ... < ∥F.derivative.eval a∥ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a := ⟨ha, by simp [deriv_ne_zero hnorm], rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
83c45c47b5ef15a2db161891fefc15b322445d53
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/algebra/normed_group.lean
bb6956d6b493f8b582e5cf3df19a52ee91c39348
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
1,441
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.algebra.group_completion import topology.metric_space.completion /-! # Completion of normed groups In this file we show that the completion of a normed group is naturally a normed group. ## Main declaration * `uniform_space.completion.normed_group`: the normed group instance on the completion of a normed group -/ noncomputable theory variables (V : Type*) namespace uniform_space namespace completion instance [uniform_space V] [has_norm V] : has_norm (completion V) := { norm := completion.extension has_norm.norm } @[simp] lemma norm_coe {V} [semi_normed_group V] (v : V) : ∥(v : completion V)∥ = ∥v∥ := completion.extension_coe uniform_continuous_norm v instance [semi_normed_group V] : normed_group (completion V) := { dist_eq := begin intros x y, apply completion.induction_on₂ x y; clear x y, { refine is_closed_eq (completion.uniform_continuous_extension₂ _).continuous _, exact continuous.comp completion.continuous_extension continuous_sub }, { intros x y, rw [← completion.coe_sub, norm_coe, metric.completion.dist_eq, dist_eq_norm] } end, .. (show add_comm_group (completion V), by apply_instance), .. (show metric_space (completion V), by apply_instance) } end completion end uniform_space
ea1f564a54a0a6d6d2623c827ff6358e9209a50e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/shapes/equivalence.lean
9f38875f671d1112649f3b503c837bd1f3ffb271
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,453
lean
/- Copyright (c) Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.adjunction.limits import category_theory.limits.shapes.terminal /-! # Transporting existence of specific limits across equivalences > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For now, we only treat the case of initial and terminal objects, but other special shapes can be added in the future. -/ open category_theory category_theory.limits namespace category_theory universes v₁ v₂ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] lemma has_initial_of_equivalence (e : D ⥤ C) [is_equivalence e] [has_initial C] : has_initial D := adjunction.has_colimits_of_shape_of_equivalence e lemma equivalence.has_initial_iff (e : C ≌ D) : has_initial C ↔ has_initial D := ⟨λ h, by exactI has_initial_of_equivalence e.inverse, λ h, by exactI has_initial_of_equivalence e.functor⟩ lemma has_terminal_of_equivalence (e : D ⥤ C) [is_equivalence e] [has_terminal C] : has_terminal D := adjunction.has_limits_of_shape_of_equivalence e lemma equivalence.has_terminal_iff (e : C ≌ D) : has_terminal C ↔ has_terminal D := ⟨λ h, by exactI has_terminal_of_equivalence e.inverse, λ h, by exactI has_terminal_of_equivalence e.functor⟩ end category_theory
481e7e1d9de1cce667b97727645a61d561e91f0d
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/for_mathlib/algebra/category/Group/kernels.lean
b38a6527c86bddc54c35af5fadd83e9fc1de3c2c
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
3,786
lean
import algebra.category.Group.limits import algebra.category.Group.images import category_theory.limits.shapes.kernels import group_theory.quotient_group import category_theory.over open category_theory open category_theory.limits universes u section variables {C : Type (u+1)} [large_category C] [concrete_category C] local attribute [instance] concrete_category.has_coe_to_sort local attribute [instance] concrete_category.has_coe_to_fun variables [has_zero_morphisms C] variables {X Y : C} (f : X ⟶ Y) @[simp] lemma kernel_condition_apply [has_kernel f] (x : kernel f) : f (kernel.ι f x) = (0 : kernel f ⟶ Y) x := begin have h := congr_arg (λ k : kernel f ⟶ Y, (k : kernel f → Y) x) (kernel.condition f), dsimp at h, rw coe_comp at h, exact h end @[simp] lemma cokernel_condition_apply [has_cokernel f] (x : X) : cokernel.π f (f x) = (0 : X ⟶ cokernel f) x := begin have h := congr_arg (λ k : X ⟶ cokernel f, (k : X → cokernel f) x) (cokernel.condition f), dsimp at h, rw coe_comp at h, exact h end end namespace AddCommGroup @[simp] lemma coe_of {G : Type*} [add_comm_group G] : (AddCommGroup.of G : Type*) = G := rfl def of_add_subgroup_bot {G : Type*} [add_comm_group G] : AddCommGroup.of (⊥ : add_subgroup G) ≅ 0 := by tidy. def of_add_subgroup_le {G : Type*} [add_comm_group G] {H K : add_subgroup G} (w : H ≤ K) : AddCommGroup.of H ⟶ AddCommGroup.of K := { to_fun := λ h, ⟨h.1, add_subgroup.le_def.mp w h.2⟩, map_zero' := by tidy, map_add' := by tidy, } @[simp] lemma of_add_subgroup_le_apply_val {G : Type*} [add_comm_group G] {H K : add_subgroup G} (w : H ≤ K) (h : H) : (of_add_subgroup_le w h : K).1 = h.1 := rfl @[simps] def of_add_subgroup_eq {G : Type*} [add_comm_group G] {H K : add_subgroup G} (w : H = K) : AddCommGroup.of H ≅ AddCommGroup.of K := { hom := of_add_subgroup_le (le_of_eq w), inv := of_add_subgroup_le (le_of_eq w.symm), } -- What is the right generality to prove this? @[simp] lemma zero_morphism_apply {G H : AddCommGroup} (g : G) : (0 : G ⟶ H) g = 0 := rfl def kernel_iso_ker {G H : AddCommGroup} (f : G ⟶ H) : kernel f ≅ AddCommGroup.of f.ker := { hom := { to_fun := λ g, ⟨kernel.ι f g, begin -- FIXME where is this `has_coe_t_aux.coe` coming from? how do we get rid of it? change (kernel.ι f) g ∈ f.ker, simp [add_monoid_hom.mem_ker], end⟩, map_zero' := rfl, map_add' := λ g g', rfl, }, inv := kernel.lift f (add_subgroup.subtype f.ker) (by tidy), }. @[simp] lemma kernel_iso_ker_hom_comp_subtype {G H : AddCommGroup} (f : G ⟶ H) : (kernel_iso_ker f).hom ≫ add_subgroup.subtype f.ker = kernel.ι f := rfl @[simp] lemma kernel_iso_ker_inv_comp_ι {G H : AddCommGroup} (f : G ⟶ H) : (kernel_iso_ker f).inv ≫ kernel.ι f = add_subgroup.subtype f.ker := rfl @[simps] def kernel_iso_ker_over {G H : AddCommGroup} (f : G ⟶ H) : over.mk (kernel.ι f) ≅ @over.mk _ _ G (AddCommGroup.of f.ker) (add_subgroup.subtype f.ker) := -- TODO this would be cleaner if we made a `over.iso_mk`. { hom := over.hom_mk (kernel_iso_ker f).hom (by simp), inv := over.hom_mk (kernel_iso_ker f).inv (by simp), }. -- TODO why is this not always an instance? local attribute [instance] normal_add_subgroup_of_add_comm_group open quotient_add_group def cokernel_iso_quotient {G H : AddCommGroup} (f : G ⟶ H) : cokernel f ≅ AddCommGroup.of (quotient (set.range f)) := { hom := cokernel.desc f (add_monoid_hom.of mk) begin ext, apply quotient.sound, fsplit, exact -x, simp, end, inv := add_monoid_hom.of (quotient_add_group.lift (set.range f) (cokernel.π f) (by tidy)), } def image_iso_range {G H : AddCommGroup} (f : G ⟶ H) : image f ≅ AddCommGroup.of (set.range f) := iso.refl _ end AddCommGroup
dc57cc6984cf16908feba1b4ee93f201400861b7
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/simplifier.lean
b445b7ebb4387241d71370d585109dd4d4e9eb7d
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,742
lean
prelude import init.logic init.classical universe variables u -- For n-ary support structure [class] is_associative {A : Type u} (op : A → A → A) := (op_assoc : ∀ x y z : A, op (op x y) z = op x (op y z)) attribute [instance] definition and_is_associative : is_associative and := is_associative.mk (λ x y z, propext (@and.assoc x y z)) attribute [instance] definition or_is_associative : is_associative or := is_associative.mk (λ x y z, propext (@or.assoc x y z)) -- Basic congruence theorems over equality (using propext) attribute [congr] theorem imp_congr_ctx_eq {P₁ P₂ Q₁ Q₂ : Prop} (H₁ : P₁ = P₂) (H₂ : P₂ → (Q₁ = Q₂)) : (P₁ → Q₁) = (P₂ → Q₂) := propext (imp_congr_ctx (iff.of_eq H₁) (assume p₂, iff.of_eq (H₂ p₂))) attribute [congr] theorem forall_congr_eq {A : Type u} (P Q : A → Prop) (H : ∀ a, P a = Q a) : ((∀ a, P a) = (∀ a, Q a)) := propext (forall_congr (assume a, iff.of_eq (H a))) -- Congruence theorems for flattening namespace simplifier variables {A : Type u} theorem congr_bin_op {op op' : A → A → A} (H : op = op') (x y : A) : op x y = op' x y := congr_fun (congr_fun H x) y theorem congr_bin_arg1 {op : A → A → A} {x x' y : A} (Hx : x = x') : op x y = op x' y := congr_fun (congr_arg op Hx) y theorem congr_bin_arg2 {op : A → A → A} {x y y' : A} (Hy : y = y') : op x y = op x y' := congr_arg (op x) Hy theorem congr_bin_args {op : A → A → A} {x x' y y' : A} (Hx : x = x') (Hy : y = y') : op x y = op x' y' := congr (congr_arg op Hx) Hy theorem assoc_subst {op op' : A → A → A} (H : op = op') (H_assoc : ∀ x y z, op (op x y) z = op x (op y z)) : (∀ x y z, op' (op' x y) z = op' x (op' y z)) := H ▸ H_assoc end simplifier
6f03bef36496185eb7543f083af693d7d1320cd1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/precompile/bar/lakefile.lean
be265d5d01536729e3431033a23e25504fb46be8
[ "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
131
lean
import Lake open Lake DSL package bar { precompileModules := false } require foo from "../foo" @[default_target] lean_lib Bar
8514b17e8cbad2ede0ff3a0c83871bde51e6c94f
1fbca480c1574e809ae95a3eda58188ff42a5e41
/test/tactic/ite.lean
36f791a9f530145d8e98b7f806377801e0094cf3
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
1,365
lean
import util.meta.tactic example (x y : ℕ) (h : x ≤ 7) (h' : y ≤ 7) : (if x ≤ y then x else y) ≤ 7 := begin ite_cases with h₃, all_goals { assumption } end example (x y : ℕ) (h : x ≤ 7) (h' : y ≤ 7) : (if h'' : x ≤ y then x else y) ≤ 7 := begin ite_cases with h₃, all_goals { assumption } end example (x y i j : ℕ) (h : x ≤ i) (h' : y ≤ j) : (if h : x ≤ y then x else y) ≤ (if x ≤ y then i else j) := begin ite_cases with h₃, all_goals { assumption } end example (x y i j : ℕ) (h : x ≤ i) (h' : y ≤ j) : (if x ≤ y then x else y) ≤ if (if x ≤ y then tt else ff) then i else j := begin ite_cases with h₃, all_goals { assumption } end example (x y i j : ℕ) (f : ℕ → ℕ) (h'' : (if h : x ≤ y then x ≤ i else y ≤ j)) (h''' : f (if h : x ≤ y then y else x) ≤ 7) (h'''' : (if h : x ≤ y then y else x) ≤ 7) : (if h : x ≤ y then x else y) ≤ (if x ≤ y then i else j) := begin ite_cases with h₃ at ⊢ h'' h''', all_goals { assumption } end example (x y i j : ℕ) (f : ℕ → ℕ) (h'' : (if h : x ≤ y then x ≤ i else y ≤ j)) (h''' : f (if h : x ≤ y then y else x) ≤ 7) (h'''' : (if h : x ≤ y then y else x) ≤ 7) : x ≤ i ∨ y ≤ j := begin ite_cases with h₃ at ⊢ h'' h''' ; [ right , left ] ; assumption end
53710227d93a32fea8e711b3e46931fce0754c0c
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Lean/ReducibilityAttrs.lean
88fc0956c71f4ad200df30ec2242de4091e1e8cd
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,881
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Attributes namespace Lean inductive ReducibilityStatus where | reducible | semireducible | irreducible deriving Inhabited builtin_initialize reducibilityAttrs : EnumAttributes ReducibilityStatus ← registerEnumAttributes `reducibility [(`reducible, "reducible", ReducibilityStatus.reducible), (`semireducible, "semireducible", ReducibilityStatus.semireducible), (`irreducible, "irreducible", ReducibilityStatus.irreducible)] @[export lean_get_reducibility_status] def getReducibilityStatusImp (env : Environment) (declName : Name) : ReducibilityStatus := match reducibilityAttrs.getValue env declName with | some s => s | none => ReducibilityStatus.semireducible @[export lean_set_reducibility_status] def setReducibilityStatusImp (env : Environment) (declName : Name) (s : ReducibilityStatus) : Environment := match reducibilityAttrs.setValue env declName s with | Except.ok env => env | _ => env -- TODO(Leo): we should extend EnumAttributes.setValue in the future and ensure it never fails def getReducibilityStatus {m} [Monad m] [MonadEnv m] (declName : Name) : m ReducibilityStatus := do return getReducibilityStatusImp (← getEnv) declName def setReducibilityStatus {m} [Monad m] [MonadEnv m] (declName : Name) (s : ReducibilityStatus) : m Unit := do modifyEnv fun env => setReducibilityStatusImp env declName s def setReducibleAttribute {m} [Monad m] [MonadEnv m] (declName : Name) : m Unit := do setReducibilityStatus declName ReducibilityStatus.reducible def isReducible {m} [Monad m] [MonadEnv m] (declName : Name) : m Bool := do match ← getReducibilityStatus declName with | ReducibilityStatus.reducible => true | _ => false end Lean
79317952908cd5ec5aa1273639f23bd3bf7c7203
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/box_integral/basic.lean
eb617857d3890e949a76765752465df165ab4e3d
[ "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
43,283
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.partition.filter import analysis.box_integral.partition.measure import topology.uniform_space.compact /-! # Integrals of Riemann, Henstock-Kurzweil, and McShane In this file we define the integral of a function over a box in `ℝⁿ. The same definition works for Riemann, Henstock-Kurzweil, and McShane integrals. As usual, we represent `ℝⁿ` as the type of functions `ι → ℝ` for some finite type `ι`. A rectangular box `(l, u]` in `ℝⁿ` is defined to be the set `{x : ι → ℝ | ∀ i, l i < x i ∧ x i ≤ u i}`, see `box_integral.box`. Let `vol` be a box-additive function on boxes in `ℝⁿ` with codomain `E →L[ℝ] F`. Given a function `f : ℝⁿ → E`, a box `I` and a tagged partition `π` of this box, the *integral sum* of `f` over `π` with respect to the volume `vol` is the sum of `vol J (f (π.tag J))` over all boxes of `π`. Here `π.tag J` is the point (tag) in `ℝⁿ` associated with the box `J`. The integral is defined as the limit of integral sums along a filter. Different filters correspond to different integration theories. In order to avoid code duplication, all our definitions and theorems take an argument `l : box_integral.integration_params`. This is a type that holds three boolean values, and encodes eight filters including those corresponding to Riemann, Henstock-Kurzweil, and McShane integrals. Following the design of infinite sums (see `has_sum` and `tsum`), we define a predicate `box_integral.has_integral` and a function `box_integral.integral` that returns a vector satisfying the predicate or zero if the function is not integrable. Then we prove some basic properties of box integrals (linearity, a formula for the integral of a constant). We also prove a version of the Henstock-Sacks inequality (see `box_integral.integrable.dist_integral_sum_le_of_mem_base_set` and `box_integral.integrable.dist_integral_sum_sum_integral_le_of_mem_base_set_of_Union_eq`), prove integrability of continuous functions, and provide a criterion for integrability w.r.t. a non-Riemann filter (e.g., Henstock-Kurzweil and McShane). ## Notation - `ℝⁿ`: local notation for `ι → ℝ` ## Tags integral -/ open_locale big_operators classical topology nnreal filter uniformity box_integral open set finset function filter metric box_integral.integration_params noncomputable theory namespace box_integral universes u v w variables {ι : Type u} {E : Type v} {F : Type w} [normed_add_comm_group E] [normed_space ℝ E] [normed_add_comm_group F] [normed_space ℝ F] {I J : box ι} {π : tagged_prepartition I} open tagged_prepartition local notation `ℝⁿ` := ι → ℝ /-! ### Integral sum and its basic properties -/ /-- The integral sum of `f : ℝⁿ → E` over a tagged prepartition `π` w.r.t. box-additive volume `vol` with codomain `E →L[ℝ] F` is the sum of `vol J (f (π.tag J))` over all boxes of `π`. -/ def integral_sum (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : tagged_prepartition I) : F := ∑ J in π.boxes, vol J (f (π.tag J)) lemma integral_sum_bUnion_tagged (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : prepartition I) (πi : Π J, tagged_prepartition J) : integral_sum f vol (π.bUnion_tagged πi) = ∑ J in π.boxes, integral_sum f vol (πi J) := begin refine (π.sum_bUnion_boxes _ _).trans (sum_congr rfl $ λ J hJ, sum_congr rfl $ λ J' hJ', _), rw π.tag_bUnion_tagged hJ hJ' end lemma integral_sum_bUnion_partition (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : tagged_prepartition I) (πi : Π J, prepartition J) (hπi : ∀ J ∈ π, (πi J).is_partition) : integral_sum f vol (π.bUnion_prepartition πi) = integral_sum f vol π := begin refine (π.to_prepartition.sum_bUnion_boxes _ _).trans (sum_congr rfl $ λ J hJ, _), calc ∑ J' in (πi J).boxes, vol J' (f (π.tag $ π.to_prepartition.bUnion_index πi J')) = ∑ J' in (πi J).boxes, vol J' (f (π.tag J)) : sum_congr rfl (λ J' hJ', by rw [prepartition.bUnion_index_of_mem _ hJ hJ']) ... = vol J (f (π.tag J)) : (vol.map ⟨λ g : E →L[ℝ] F, g (f (π.tag J)), rfl, λ _ _, rfl⟩).sum_partition_boxes le_top (hπi J hJ) end lemma integral_sum_inf_partition (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : tagged_prepartition I) {π' : prepartition I} (h : π'.is_partition) : integral_sum f vol (π.inf_prepartition π') = integral_sum f vol π := integral_sum_bUnion_partition f vol π _ $ λ J hJ, h.restrict (prepartition.le_of_mem _ hJ) lemma integral_sum_fiberwise {α} (g : box ι → α) (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : tagged_prepartition I) : ∑ y in π.boxes.image g, integral_sum f vol (π.filter (λ x, g x = y)) = integral_sum f vol π := π.to_prepartition.sum_fiberwise g (λ J, vol J (f $ π.tag J)) lemma integral_sum_sub_partitions (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) {π₁ π₂ : tagged_prepartition I} (h₁ : π₁.is_partition) (h₂ : π₂.is_partition) : integral_sum f vol π₁ - integral_sum f vol π₂ = ∑ J in (π₁.to_prepartition ⊓ π₂.to_prepartition).boxes, (vol J (f $ (π₁.inf_prepartition π₂.to_prepartition).tag J) - vol J (f $ (π₂.inf_prepartition π₁.to_prepartition).tag J)) := begin rw [← integral_sum_inf_partition f vol π₁ h₂, ← integral_sum_inf_partition f vol π₂ h₁, integral_sum, integral_sum, finset.sum_sub_distrib], simp only [inf_prepartition_to_prepartition, _root_.inf_comm] end @[simp] lemma integral_sum_disj_union (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) {π₁ π₂ : tagged_prepartition I} (h : disjoint π₁.Union π₂.Union) : integral_sum f vol (π₁.disj_union π₂ h) = integral_sum f vol π₁ + integral_sum f vol π₂ := begin refine (prepartition.sum_disj_union_boxes h _).trans (congr_arg2 (+) (sum_congr rfl $ λ J hJ, _) (sum_congr rfl $ λ J hJ, _)), { rw disj_union_tag_of_mem_left _ hJ }, { rw disj_union_tag_of_mem_right _ hJ } end @[simp] lemma integral_sum_add (f g : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : tagged_prepartition I) : integral_sum (f + g) vol π = integral_sum f vol π + integral_sum g vol π := by simp only [integral_sum, pi.add_apply, (vol _).map_add, finset.sum_add_distrib] @[simp] lemma integral_sum_neg (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : tagged_prepartition I) : integral_sum (-f) vol π = -integral_sum f vol π := by simp only [integral_sum, pi.neg_apply, (vol _).map_neg, finset.sum_neg_distrib] @[simp] lemma integral_sum_smul (c : ℝ) (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (π : tagged_prepartition I) : integral_sum (c • f) vol π = c • integral_sum f vol π := by simp only [integral_sum, finset.smul_sum, pi.smul_apply, continuous_linear_map.map_smul] variables [fintype ι] /-! ### Basic integrability theory -/ /-- The predicate `has_integral I l f vol y` says that `y` is the integral of `f` over `I` along `l` w.r.t. volume `vol`. This means that integral sums of `f` tend to `𝓝 y` along `box_integral.integration_params.to_filter_Union I ⊤`. -/ def has_integral (I : box ι) (l : integration_params) (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) (y : F) : Prop := tendsto (integral_sum f vol) (l.to_filter_Union I ⊤) (𝓝 y) /-- A function is integrable if there exists a vector that satisfies the `has_integral` predicate. -/ def integrable (I : box ι) (l : integration_params) (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) := ∃ y, has_integral I l f vol y /-- The integral of a function `f` over a box `I` along a filter `l` w.r.t. a volume `vol`. Returns zero on non-integrable functions. -/ def integral (I : box ι) (l : integration_params) (f : ℝⁿ → E) (vol : ι →ᵇᵃ (E →L[ℝ] F)) := if h : integrable I l f vol then h.some else 0 variables {l : integration_params} {f g : ℝⁿ → E} {vol : ι →ᵇᵃ (E →L[ℝ] F)} {y y' : F} /-- Reinterpret `box_integral.has_integral` as `filter.tendsto`, e.g., dot-notation theorems that are shadowed in the `box_integral.has_integral` namespace. -/ lemma has_integral.tendsto (h : has_integral I l f vol y) : tendsto (integral_sum f vol) (l.to_filter_Union I ⊤) (𝓝 y) := h /-- The `ε`-`δ` definition of `box_integral.has_integral`. -/ lemma has_integral_iff : has_integral I l f vol y ↔ ∀ ε > (0 : ℝ), ∃ r : ℝ≥0 → ℝⁿ → Ioi (0 : ℝ), (∀ c, l.r_cond (r c)) ∧ ∀ c π, l.mem_base_set I c (r c) π → is_partition π → dist (integral_sum f vol π) y ≤ ε := ((l.has_basis_to_filter_Union_top I).tendsto_iff nhds_basis_closed_ball).trans $ by simp [@forall_swap ℝ≥0 (tagged_prepartition I)] /-- Quite often it is more natural to prove an estimate of the form `a * ε`, not `ε` in the RHS of `box_integral.has_integral_iff`, so we provide this auxiliary lemma. -/ lemma has_integral_of_mul (a : ℝ) (h : ∀ ε : ℝ, 0 < ε → ∃ r: ℝ≥0 → ℝⁿ → Ioi (0 : ℝ), (∀ c, l.r_cond (r c)) ∧ ∀ c π, l.mem_base_set I c (r c) π → is_partition π → dist (integral_sum f vol π) y ≤ a * ε) : has_integral I l f vol y := begin refine has_integral_iff.2 (λ ε hε, _), rcases exists_pos_mul_lt hε a with ⟨ε', hε', ha⟩, rcases h ε' hε' with ⟨r, hr, H⟩, exact ⟨r, hr, λ c π hπ hπp, (H c π hπ hπp).trans ha.le⟩ end lemma integrable_iff_cauchy [complete_space F] : integrable I l f vol ↔ cauchy ((l.to_filter_Union I ⊤).map (integral_sum f vol)) := cauchy_map_iff_exists_tendsto.symm /-- In a complete space, a function is integrable if and only if its integral sums form a Cauchy net. Here we restate this fact in terms of `∀ ε > 0, ∃ r, ...`. -/ lemma integrable_iff_cauchy_basis [complete_space F] : integrable I l f vol ↔ ∀ ε > (0 : ℝ), ∃ r : ℝ≥0 → ℝⁿ → Ioi (0 : ℝ), (∀ c, l.r_cond (r c)) ∧ ∀ c₁ c₂ π₁ π₂, l.mem_base_set I c₁ (r c₁) π₁ → π₁.is_partition → l.mem_base_set I c₂ (r c₂) π₂ → π₂.is_partition → dist (integral_sum f vol π₁) (integral_sum f vol π₂) ≤ ε := begin rw [integrable_iff_cauchy, cauchy_map_iff', (l.has_basis_to_filter_Union_top _).prod_self.tendsto_iff uniformity_basis_dist_le], refine forall₂_congr (λ ε ε0, exists_congr $ λ r, _), simp only [exists_prop, prod.forall, set.mem_Union, exists_imp_distrib, prod_mk_mem_set_prod_eq, and_imp, mem_inter_iff, mem_set_of_eq], exact and_congr iff.rfl ⟨λ H c₁ c₂ π₁ π₂ h₁ hU₁ h₂ hU₂, H π₁ π₂ c₁ h₁ hU₁ c₂ h₂ hU₂, λ H π₁ π₂ c₁ h₁ hU₁ c₂ h₂ hU₂, H c₁ c₂ π₁ π₂ h₁ hU₁ h₂ hU₂⟩ end lemma has_integral.mono {l₁ l₂ : integration_params} (h : has_integral I l₁ f vol y) (hl : l₂ ≤ l₁) : has_integral I l₂ f vol y := h.mono_left $ integration_params.to_filter_Union_mono _ hl _ protected lemma integrable.has_integral (h : integrable I l f vol) : has_integral I l f vol (integral I l f vol) := by { rw [integral, dif_pos h], exact classical.some_spec h } lemma integrable.mono {l'} (h : integrable I l f vol) (hle : l' ≤ l) : integrable I l' f vol := ⟨_, h.has_integral.mono hle⟩ lemma has_integral.unique (h : has_integral I l f vol y) (h' : has_integral I l f vol y') : y = y' := tendsto_nhds_unique h h' lemma has_integral.integrable (h : has_integral I l f vol y) : integrable I l f vol := ⟨_, h⟩ lemma has_integral.integral_eq (h : has_integral I l f vol y) : integral I l f vol = y := h.integrable.has_integral.unique h lemma has_integral.add (h : has_integral I l f vol y) (h' : has_integral I l g vol y') : has_integral I l (f + g) vol (y + y') := by simpa only [has_integral, ← integral_sum_add] using h.add h' lemma integrable.add (hf : integrable I l f vol) (hg : integrable I l g vol) : integrable I l (f + g) vol := (hf.has_integral.add hg.has_integral).integrable lemma integral_add (hf : integrable I l f vol) (hg : integrable I l g vol) : integral I l (f + g) vol = integral I l f vol + integral I l g vol := (hf.has_integral.add hg.has_integral).integral_eq lemma has_integral.neg (hf : has_integral I l f vol y) : has_integral I l (-f) vol (-y) := by simpa only [has_integral, ← integral_sum_neg] using hf.neg lemma integrable.neg (hf : integrable I l f vol) : integrable I l (-f) vol := hf.has_integral.neg.integrable lemma integrable.of_neg (hf : integrable I l (-f) vol) : integrable I l f vol := neg_neg f ▸ hf.neg @[simp] lemma integrable_neg : integrable I l (-f) vol ↔ integrable I l f vol := ⟨λ h, h.of_neg, λ h, h.neg⟩ @[simp] lemma integral_neg : integral I l (-f) vol = -integral I l f vol := if h : integrable I l f vol then h.has_integral.neg.integral_eq else by rw [integral, integral, dif_neg h, dif_neg (mt integrable.of_neg h), neg_zero] lemma has_integral.sub (h : has_integral I l f vol y) (h' : has_integral I l g vol y') : has_integral I l (f - g) vol (y - y') := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma integrable.sub (hf : integrable I l f vol) (hg : integrable I l g vol) : integrable I l (f - g) vol := (hf.has_integral.sub hg.has_integral).integrable lemma integral_sub (hf : integrable I l f vol) (hg : integrable I l g vol) : integral I l (f - g) vol = integral I l f vol - integral I l g vol := (hf.has_integral.sub hg.has_integral).integral_eq lemma has_integral_const (c : E) : has_integral I l (λ _, c) vol (vol I c) := tendsto_const_nhds.congr' $ (l.eventually_is_partition I).mono $ λ π hπ, ((vol.map ⟨λ g : E →L[ℝ] F, g c, rfl, λ _ _, rfl⟩).sum_partition_boxes le_top hπ).symm @[simp] lemma integral_const (c : E) : integral I l (λ _, c) vol = vol I c := (has_integral_const c).integral_eq lemma integrable_const (c : E) : integrable I l (λ _, c) vol := ⟨_, has_integral_const c⟩ lemma has_integral_zero : has_integral I l (λ _, (0:E)) vol 0 := by simpa only [← (vol I).map_zero] using has_integral_const (0 : E) lemma integrable_zero : integrable I l (λ _, (0:E)) vol := ⟨0, has_integral_zero⟩ lemma integral_zero : integral I l (λ _, (0:E)) vol = 0 := has_integral_zero.integral_eq lemma has_integral_sum {α : Type*} {s : finset α} {f : α → ℝⁿ → E} {g : α → F} (h : ∀ i ∈ s, has_integral I l (f i) vol (g i)) : has_integral I l (λ x, ∑ i in s, f i x) vol (∑ i in s, g i) := begin induction s using finset.induction_on with a s ha ihs, { simp [has_integral_zero] }, simp only [finset.sum_insert ha], rw finset.forall_mem_insert at h, exact h.1.add (ihs h.2) end lemma has_integral.smul (hf : has_integral I l f vol y) (c : ℝ) : has_integral I l (c • f) vol (c • y) := by simpa only [has_integral, ← integral_sum_smul] using (tendsto_const_nhds : tendsto _ _ (𝓝 c)).smul hf lemma integrable.smul (hf : integrable I l f vol) (c : ℝ) : integrable I l (c • f) vol := (hf.has_integral.smul c).integrable lemma integrable.of_smul {c : ℝ} (hf : integrable I l (c • f) vol) (hc : c ≠ 0) : integrable I l f vol := by { convert hf.smul c⁻¹, ext x, simp only [pi.smul_apply, inv_smul_smul₀ hc] } @[simp] lemma integral_smul (c : ℝ) : integral I l (λ x, c • f x) vol = c • integral I l f vol := begin rcases eq_or_ne c 0 with rfl | hc, { simp only [zero_smul, integral_zero] }, by_cases hf : integrable I l f vol, { exact (hf.has_integral.smul c).integral_eq }, { have : ¬integrable I l (λ x, c • f x) vol, from mt (λ h, h.of_smul hc) hf, rw [integral, integral, dif_neg hf, dif_neg this, smul_zero] } end open measure_theory /-- The integral of a nonnegative function w.r.t. a volume generated by a locally-finite measure is nonnegative. -/ lemma integral_nonneg {g : ℝⁿ → ℝ} (hg : ∀ x ∈ I.Icc, 0 ≤ g x) (μ : measure ℝⁿ) [is_locally_finite_measure μ] : 0 ≤ integral I l g μ.to_box_additive.to_smul := begin by_cases hgi : integrable I l g μ.to_box_additive.to_smul, { refine ge_of_tendsto' hgi.has_integral (λ π, sum_nonneg $ λ J hJ, _), exact mul_nonneg ennreal.to_real_nonneg (hg _ $ π.tag_mem_Icc _) }, { rw [integral, dif_neg hgi] } end /-- If `‖f x‖ ≤ g x` on `[l, u]` and `g` is integrable, then the norm of the integral of `f` is less than or equal to the integral of `g`. -/ lemma norm_integral_le_of_norm_le {g : ℝⁿ → ℝ} (hle : ∀ x ∈ I.Icc, ‖f x‖ ≤ g x) (μ : measure ℝⁿ) [is_locally_finite_measure μ] (hg : integrable I l g μ.to_box_additive.to_smul) : ‖(integral I l f μ.to_box_additive.to_smul : E)‖ ≤ integral I l g μ.to_box_additive.to_smul := begin by_cases hfi : integrable.{u v v} I l f μ.to_box_additive.to_smul, { refine le_of_tendsto_of_tendsto' hfi.has_integral.norm hg.has_integral (λ π, _), refine norm_sum_le_of_le _ (λ J hJ, _), simp only [box_additive_map.to_smul_apply, norm_smul, smul_eq_mul, real.norm_eq_abs, μ.to_box_additive_apply, abs_of_nonneg ennreal.to_real_nonneg], exact mul_le_mul_of_nonneg_left (hle _ $ π.tag_mem_Icc _) ennreal.to_real_nonneg }, { rw [integral, dif_neg hfi, norm_zero], exact integral_nonneg (λ x hx, (norm_nonneg _).trans (hle x hx)) μ } end lemma norm_integral_le_of_le_const {c : ℝ} (hc : ∀ x ∈ I.Icc, ‖f x‖ ≤ c) (μ : measure ℝⁿ) [is_locally_finite_measure μ] : ‖(integral I l f μ.to_box_additive.to_smul : E)‖ ≤ (μ I).to_real * c := by simpa only [integral_const] using norm_integral_le_of_norm_le hc μ (integrable_const c) /-! # Henstock-Sacks inequality and integrability on subboxes Henstock-Sacks inequality for Henstock-Kurzweil integral says the following. Let `f` be a function integrable on a box `I`; let `r : ℝⁿ → (0, ∞)` be a function such that for any tagged partition of `I` subordinate to `r`, the integral sum over this partition is `ε`-close to the integral. Then for any tagged prepartition (i.e. a finite collections of pairwise disjoint subboxes of `I` with tagged points) `π`, the integral sum over `π` differs from the integral of `f` over the part of `I` covered by `π` by at most `ε`. The actual statement in the library is a bit more complicated to make it work for any `box_integral.integration_params`. We formalize several versions of this inequality in `box_integral.integrable.dist_integral_sum_le_of_mem_base_set`, `box_integral.integrable.dist_integral_sum_sum_integral_le_of_mem_base_set_of_Union_eq`, and `box_integral.integrable.dist_integral_sum_sum_integral_le_of_mem_base_set`. Instead of using predicate assumptions on `r`, we define `box_integral.integrable.convergence_r (h : integrable I l f vol) (ε : ℝ) (c : ℝ≥0) : ℝⁿ → (0, ∞)` to be a function `r` such that - if `l.bRiemann`, then `r` is a constant; - if `ε > 0`, then for any tagged partition `π` of `I` subordinate to `r` (more precisely, satisfying the predicate `l.mem_base_set I c r`), the integral sum of `f` over `π` differs from the integral of `f` over `I` by at most `ε`. The proof is mostly based on [Russel A. Gordon, *The integrals of Lebesgue, Denjoy, Perron, and Henstock*][Gordon55]. -/ namespace integrable /-- If `ε > 0`, then `box_integral.integrable.convergence_r` is a function `r : ℝ≥0 → ℝⁿ → (0, ∞)` such that for every `c : ℝ≥0`, for every tagged partition `π` subordinate to `r` (and satisfying additional distortion estimates if `box_integral.integration_params.bDistortion l = tt`), the corresponding integral sum is `ε`-close to the integral. If `box.integral.integration_params.bRiemann = tt`, then `r c x` does not depend on `x`. If `ε ≤ 0`, then we use `r c x = 1`. -/ def convergence_r (h : integrable I l f vol) (ε : ℝ) : ℝ≥0 → ℝⁿ → Ioi (0 : ℝ) := if hε : 0 < ε then (has_integral_iff.1 h.has_integral ε hε).some else λ _ _, ⟨1, set.mem_Ioi.2 zero_lt_one⟩ variables {c c₁ c₂ : ℝ≥0} {ε ε₁ ε₂ : ℝ} {π₁ π₂ : tagged_prepartition I} lemma convergence_r_cond (h : integrable I l f vol) (ε : ℝ) (c : ℝ≥0) : l.r_cond (h.convergence_r ε c) := begin rw convergence_r, split_ifs with h₀, exacts [(has_integral_iff.1 h.has_integral ε h₀).some_spec.1 _, λ _ x, rfl] end lemma dist_integral_sum_integral_le_of_mem_base_set (h : integrable I l f vol) (h₀ : 0 < ε) (hπ : l.mem_base_set I c (h.convergence_r ε c) π) (hπp : π.is_partition) : dist (integral_sum f vol π) (integral I l f vol) ≤ ε := begin rw [convergence_r, dif_pos h₀] at hπ, exact (has_integral_iff.1 h.has_integral ε h₀).some_spec.2 c _ hπ hπp end /-- **Henstock-Sacks inequality**. Let `r₁ r₂ : ℝⁿ → (0, ∞)` be function such that for any tagged *partition* of `I` subordinate to `rₖ`, `k=1,2`, the integral sum of `f` over this partition differs from the integral of `f` by at most `εₖ`. Then for any two tagged *prepartition* `π₁ π₂` subordinate to `r₁` and `r₂` respectively and covering the same part of `I`, the integral sums of `f` over these prepartitions differ from each other by at most `ε₁ + ε₂`. The actual statement - uses `box_integral.integrable.convergence_r` instead of a predicate assumption on `r`; - uses `box_integral.integration_params.mem_base_set` instead of “subordinate to `r`” to account for additional requirements like being a Henstock partition or having a bounded distortion. See also `box_integral.integrable.dist_integral_sum_sum_integral_le_of_mem_base_set_of_Union_eq` and `box_integral.integrable.dist_integral_sum_sum_integral_le_of_mem_base_set`. -/ lemma dist_integral_sum_le_of_mem_base_set (h : integrable I l f vol) (hpos₁ : 0 < ε₁) (hpos₂ : 0 < ε₂) (h₁ : l.mem_base_set I c₁ (h.convergence_r ε₁ c₁) π₁) (h₂ : l.mem_base_set I c₂ (h.convergence_r ε₂ c₂) π₂) (HU : π₁.Union = π₂.Union) : dist (integral_sum f vol π₁) (integral_sum f vol π₂) ≤ ε₁ + ε₂ := begin rcases h₁.exists_common_compl h₂ HU with ⟨π, hπU, hπc₁, hπc₂⟩, set r : ℝⁿ → Ioi (0 : ℝ) := λ x, min (h.convergence_r ε₁ c₁ x) (h.convergence_r ε₂ c₂ x), have hr : l.r_cond r := (h.convergence_r_cond _ c₁).min (h.convergence_r_cond _ c₂), set πr := π.to_subordinate r, have H₁ : dist (integral_sum f vol (π₁.union_compl_to_subordinate π hπU r)) (integral I l f vol) ≤ ε₁, from h.dist_integral_sum_integral_le_of_mem_base_set hpos₁ (h₁.union_compl_to_subordinate (λ _ _, min_le_left _ _) hπU hπc₁) (is_partition_union_compl_to_subordinate _ _ _ _), rw HU at hπU, have H₂ : dist (integral_sum f vol (π₂.union_compl_to_subordinate π hπU r)) (integral I l f vol) ≤ ε₂, from h.dist_integral_sum_integral_le_of_mem_base_set hpos₂ (h₂.union_compl_to_subordinate (λ _ _, min_le_right _ _) hπU hπc₂) (is_partition_union_compl_to_subordinate _ _ _ _), simpa [union_compl_to_subordinate] using (dist_triangle_right _ _ _).trans (add_le_add H₁ H₂) end /-- If `f` is integrable on `I` along `l`, then for two sufficiently fine tagged prepartitions (in the sense of the filter `box_integral.integration_params.to_filter l I`) such that they cover the same part of `I`, the integral sums of `f` over `π₁` and `π₂` are very close to each other. -/ lemma tendsto_integral_sum_to_filter_prod_self_inf_Union_eq_uniformity (h : integrable I l f vol) : tendsto (λ π : tagged_prepartition I × tagged_prepartition I, (integral_sum f vol π.1, integral_sum f vol π.2)) ((l.to_filter I ×ᶠ l.to_filter I) ⊓ 𝓟 {π | π.1.Union = π.2.Union}) (𝓤 F) := begin refine (((l.has_basis_to_filter I).prod_self.inf_principal _).tendsto_iff uniformity_basis_dist_le).2 (λ ε ε0, _), replace ε0 := half_pos ε0, use [h.convergence_r (ε / 2), h.convergence_r_cond (ε / 2)], rintro ⟨π₁, π₂⟩ ⟨⟨h₁, h₂⟩, hU⟩, rw ← add_halves ε, exact h.dist_integral_sum_le_of_mem_base_set ε0 ε0 h₁.some_spec h₂.some_spec hU end /-- If `f` is integrable on a box `I` along `l`, then for any fixed subset `s` of `I` that can be represented as a finite union of boxes, the integral sums of `f` over tagged prepartitions that cover exactly `s` form a Cauchy “sequence” along `l`. -/ lemma cauchy_map_integral_sum_to_filter_Union (h : integrable I l f vol) (π₀ : prepartition I) : cauchy ((l.to_filter_Union I π₀).map (integral_sum f vol)) := begin refine ⟨infer_instance, _⟩, rw [prod_map_map_eq, ← to_filter_inf_Union_eq, ← prod_inf_prod, prod_principal_principal], exact h.tendsto_integral_sum_to_filter_prod_self_inf_Union_eq_uniformity.mono_left (inf_le_inf_left _ $ principal_mono.2 $ λ π h, h.1.trans h.2.symm) end variable [complete_space F] lemma to_subbox_aux (h : integrable I l f vol) (hJ : J ≤ I) : ∃ y : F, has_integral J l f vol y ∧ tendsto (integral_sum f vol) (l.to_filter_Union I (prepartition.single I J hJ)) (𝓝 y) := begin refine (cauchy_map_iff_exists_tendsto.1 (h.cauchy_map_integral_sum_to_filter_Union (prepartition.single I J hJ))).imp (λ y hy, ⟨_, hy⟩), convert hy.comp (l.tendsto_embed_box_to_filter_Union_top hJ) -- faster than `exact` here end /-- If `f` is integrable on a box `I`, then it is integrable on any subbox of `I`. -/ lemma to_subbox (h : integrable I l f vol) (hJ : J ≤ I) : integrable J l f vol := (h.to_subbox_aux hJ).imp $ λ y, and.left /-- If `f` is integrable on a box `I`, then integral sums of `f` over tagged prepartitions that cover exactly a subbox `J ≤ I` tend to the integral of `f` over `J` along `l`. -/ lemma tendsto_integral_sum_to_filter_Union_single (h : integrable I l f vol) (hJ : J ≤ I) : tendsto (integral_sum f vol) (l.to_filter_Union I (prepartition.single I J hJ)) (𝓝 $ integral J l f vol) := let ⟨y, h₁, h₂⟩ := h.to_subbox_aux hJ in h₁.integral_eq.symm ▸ h₂ /-- **Henstock-Sacks inequality**. Let `r : ℝⁿ → (0, ∞)` be a function such that for any tagged *partition* of `I` subordinate to `r`, the integral sum of `f` over this partition differs from the integral of `f` by at most `ε`. Then for any tagged *prepartition* `π` subordinate to `r`, the integral sum of `f` over this prepartition differs from the integral of `f` over the part of `I` covered by `π` by at most `ε`. The actual statement - uses `box_integral.integrable.convergence_r` instead of a predicate assumption on `r`; - uses `box_integral.integration_params.mem_base_set` instead of “subordinate to `r`” to account for additional requirements like being a Henstock partition or having a bounded distortion; - takes an extra argument `π₀ : prepartition I` and an assumption `π.Union = π₀.Union` instead of using `π.to_prepartition`. -/ lemma dist_integral_sum_sum_integral_le_of_mem_base_set_of_Union_eq (h : integrable I l f vol) (h0 : 0 < ε) (hπ : l.mem_base_set I c (h.convergence_r ε c) π) {π₀ : prepartition I} (hU : π.Union = π₀.Union) : dist (integral_sum f vol π) (∑ J in π₀.boxes, integral J l f vol) ≤ ε := begin /- Let us prove that the distance is less than or equal to `ε + δ` for all positive `δ`. -/ refine le_of_forall_pos_le_add (λ δ δ0, _), /- First we choose some constants. -/ set δ' : ℝ := δ / (π₀.boxes.card + 1), have H0 : 0 < (π₀.boxes.card + 1 : ℝ) := nat.cast_add_one_pos _, have δ'0 : 0 < δ' := div_pos δ0 H0, set C := max π₀.distortion π₀.compl.distortion, /- Next we choose a tagged partition of each `J ∈ π₀` such that the integral sum of `f` over this partition is `δ'`-close to the integral of `f` over `J`. -/ have : ∀ J ∈ π₀, ∃ πi : tagged_prepartition J, πi.is_partition ∧ dist (integral_sum f vol πi) (integral J l f vol) ≤ δ' ∧ l.mem_base_set J C (h.convergence_r δ' C) πi, { intros J hJ, have Hle : J ≤ I := π₀.le_of_mem hJ, have HJi : integrable J l f vol := h.to_subbox Hle, set r := λ x, min (h.convergence_r δ' C x) (HJi.convergence_r δ' C x), have hr : l.r_cond r, from (h.convergence_r_cond _ C).min (HJi.convergence_r_cond _ C), have hJd : J.distortion ≤ C, from le_trans (finset.le_sup hJ) (le_max_left _ _), rcases l.exists_mem_base_set_is_partition J hJd r with ⟨πJ, hC, hp⟩, have hC₁ : l.mem_base_set J C (HJi.convergence_r δ' C) πJ, { refine hC.mono J le_rfl le_rfl (λ x hx, _), exact min_le_right _ _ }, have hC₂ : l.mem_base_set J C (h.convergence_r δ' C) πJ, { refine hC.mono J le_rfl le_rfl (λ x hx, _), exact min_le_left _ _ }, exact ⟨πJ, hp, HJi.dist_integral_sum_integral_le_of_mem_base_set δ'0 hC₁ hp, hC₂⟩ }, /- Now we combine these tagged partitions into a tagged prepartition of `I` that covers the same part of `I` as `π₀` and apply `box_integral.dist_integral_sum_le_of_mem_base_set` to `π` and this prepartition. -/ choose! πi hπip hπiδ' hπiC, have : l.mem_base_set I C (h.convergence_r δ' C) (π₀.bUnion_tagged πi), from bUnion_tagged_mem_base_set hπiC hπip (λ _, le_max_right _ _), have hU' : π.Union = (π₀.bUnion_tagged πi).Union, from hU.trans (prepartition.Union_bUnion_partition _ hπip).symm, have := h.dist_integral_sum_le_of_mem_base_set h0 δ'0 hπ this hU', rw integral_sum_bUnion_tagged at this, calc dist (integral_sum f vol π) (∑ J in π₀.boxes, integral J l f vol) ≤ dist (integral_sum f vol π) (∑ J in π₀.boxes, integral_sum f vol (πi J)) + dist (∑ J in π₀.boxes, integral_sum f vol (πi J)) (∑ J in π₀.boxes, integral J l f vol) : dist_triangle _ _ _ ... ≤ (ε + δ') + ∑ J in π₀.boxes, δ' : add_le_add this (dist_sum_sum_le_of_le _ hπiδ') ... = ε + δ : by { field_simp [H0.ne'], ring } end /-- **Henstock-Sacks inequality**. Let `r : ℝⁿ → (0, ∞)` be a function such that for any tagged *partition* of `I` subordinate to `r`, the integral sum of `f` over this partition differs from the integral of `f` by at most `ε`. Then for any tagged *prepartition* `π` subordinate to `r`, the integral sum of `f` over this prepartition differs from the integral of `f` over the part of `I` covered by `π` by at most `ε`. The actual statement - uses `box_integral.integrable.convergence_r` instead of a predicate assumption on `r`; - uses `box_integral.integration_params.mem_base_set` instead of “subordinate to `r`” to account for additional requirements like being a Henstock partition or having a bounded distortion; -/ lemma dist_integral_sum_sum_integral_le_of_mem_base_set (h : integrable I l f vol) (h0 : 0 < ε) (hπ : l.mem_base_set I c (h.convergence_r ε c) π) : dist (integral_sum f vol π) (∑ J in π.boxes, integral J l f vol) ≤ ε := h.dist_integral_sum_sum_integral_le_of_mem_base_set_of_Union_eq h0 hπ rfl /-- Integral sum of `f` over a tagged prepartition `π` such that `π.Union = π₀.Union` tends to the sum of integrals of `f` over the boxes of `π₀`. -/ lemma tendsto_integral_sum_sum_integral (h : integrable I l f vol) (π₀ : prepartition I) : tendsto (integral_sum f vol) (l.to_filter_Union I π₀) (𝓝 $ ∑ J in π₀.boxes, integral J l f vol) := begin refine ((l.has_basis_to_filter_Union I π₀).tendsto_iff nhds_basis_closed_ball).2 (λ ε ε0, _), refine ⟨h.convergence_r ε, h.convergence_r_cond ε, _⟩, simp only [mem_inter_iff, set.mem_Union, mem_set_of_eq], rintro π ⟨c, hc, hU⟩, exact h.dist_integral_sum_sum_integral_le_of_mem_base_set_of_Union_eq ε0 hc hU end /-- If `f` is integrable on `I`, then `λ J, integral J l f vol` is box-additive on subboxes of `I`: if `π₁`, `π₂` are two prepartitions of `I` covering the same part of `I`, then the sum of integrals of `f` over the boxes of `π₁` is equal to the sum of integrals of `f` over the boxes of `π₂`. See also `box_integral.integrable.to_box_additive` for a bundled version. -/ lemma sum_integral_congr (h : integrable I l f vol) {π₁ π₂ : prepartition I} (hU : π₁.Union = π₂.Union) : ∑ J in π₁.boxes, integral J l f vol = ∑ J in π₂.boxes, integral J l f vol := begin refine tendsto_nhds_unique (h.tendsto_integral_sum_sum_integral π₁) _, rw l.to_filter_Union_congr _ hU, exact h.tendsto_integral_sum_sum_integral π₂ end /-- If `f` is integrable on `I`, then `λ J, integral J l f vol` is box-additive on subboxes of `I`: if `π₁`, `π₂` are two prepartitions of `I` covering the same part of `I`, then the sum of integrals of `f` over the boxes of `π₁` is equal to the sum of integrals of `f` over the boxes of `π₂`. See also `box_integral.integrable.sum_integral_congr` for an unbundled version. -/ @[simps] def to_box_additive (h : integrable I l f vol) : ι →ᵇᵃ[I] F := { to_fun := λ J, integral J l f vol, sum_partition_boxes' := λ J hJ π hπ, begin replace hπ := hπ.Union_eq, rw ← prepartition.Union_top at hπ, rw [(h.to_subbox (with_top.coe_le_coe.1 hJ)).sum_integral_congr hπ, prepartition.top_boxes, sum_singleton] end } end integrable open measure_theory /-! ### Integrability conditions -/ variable (l) /-- A continuous function is box-integrable with respect to any locally finite measure. This is true for any volume with bounded variation. -/ lemma integrable_of_continuous_on [complete_space E] {I : box ι} {f : ℝⁿ → E} (hc : continuous_on f I.Icc) (μ : measure ℝⁿ) [is_locally_finite_measure μ] : integrable.{u v v} I l f μ.to_box_additive.to_smul := begin have huc := I.is_compact_Icc.uniform_continuous_on_of_continuous hc, rw metric.uniform_continuous_on_iff_le at huc, refine integrable_iff_cauchy_basis.2 (λ ε ε0, _), rcases exists_pos_mul_lt ε0 (μ.to_box_additive I) with ⟨ε', ε0', hε⟩, rcases huc ε' ε0' with ⟨δ, δ0 : 0 < δ, Hδ⟩, refine ⟨λ _ _, ⟨δ / 2, half_pos δ0⟩, λ _ _ _, rfl, λ c₁ c₂ π₁ π₂ h₁ h₁p h₂ h₂p, _⟩, simp only [dist_eq_norm, integral_sum_sub_partitions _ _ h₁p h₂p, box_additive_map.to_smul_apply, ← smul_sub], have : ∀ J ∈ π₁.to_prepartition ⊓ π₂.to_prepartition, ‖μ.to_box_additive J • (f ((π₁.inf_prepartition π₂.to_prepartition).tag J) - f ((π₂.inf_prepartition π₁.to_prepartition).tag J))‖ ≤ μ.to_box_additive J * ε', { intros J hJ, have : 0 ≤ μ.to_box_additive J, from ennreal.to_real_nonneg, rw [norm_smul, real.norm_eq_abs, abs_of_nonneg this, ← dist_eq_norm], refine mul_le_mul_of_nonneg_left _ this, refine Hδ _ (tagged_prepartition.tag_mem_Icc _ _) _ (tagged_prepartition.tag_mem_Icc _ _) _, rw [← add_halves δ], refine (dist_triangle_left _ _ J.upper).trans (add_le_add (h₁.1 _ _ _) (h₂.1 _ _ _)), { exact prepartition.bUnion_index_mem _ hJ }, { exact box.le_iff_Icc.1 (prepartition.le_bUnion_index _ hJ) J.upper_mem_Icc }, { rw _root_.inf_comm at hJ, exact prepartition.bUnion_index_mem _ hJ }, { rw _root_.inf_comm at hJ, exact box.le_iff_Icc.1 (prepartition.le_bUnion_index _ hJ) J.upper_mem_Icc } }, refine (norm_sum_le_of_le _ this).trans _, rw [← finset.sum_mul, μ.to_box_additive.sum_partition_boxes le_top (h₁p.inf h₂p)], exact hε.le end variable {l} /-- This is an auxiliary lemma used to prove two statements at once. Use one of the next two lemmas instead. -/ lemma has_integral_of_bRiemann_eq_ff_of_forall_is_o (hl : l.bRiemann = ff) (B : ι →ᵇᵃ[I] ℝ) (hB0 : ∀ J, 0 ≤ B J) (g : ι →ᵇᵃ[I] F) (s : set ℝⁿ) (hs : s.countable) (hlH : s.nonempty → l.bHenstock = tt) (H₁ : ∀ (c : ℝ≥0) (x ∈ I.Icc ∩ s) (ε > (0 : ℝ)), ∃ δ > 0, ∀ J ≤ I, J.Icc ⊆ metric.closed_ball x δ → x ∈ J.Icc → (l.bDistortion → J.distortion ≤ c) → dist (vol J (f x)) (g J) ≤ ε) (H₂ : ∀ (c : ℝ≥0) (x ∈ I.Icc \ s) (ε > (0 : ℝ)), ∃ δ > 0, ∀ J ≤ I, J.Icc ⊆ metric.closed_ball x δ → (l.bHenstock → x ∈ J.Icc) → (l.bDistortion → J.distortion ≤ c) → dist (vol J (f x)) (g J) ≤ ε * B J) : has_integral I l f vol (g I) := begin /- We choose `r x` differently for `x ∈ s` and `x ∉ s`. For `x ∈ s`, we choose `εs` such that `∑' x : s, εs x < ε / 2 / 2 ^ #ι`, then choose `r x` so that `dist (vol J (f x)) (g J) ≤ εs x` for `J` in the `r x`-neighborhood of `x`. This guarantees that the sum of these distances over boxes `J` such that `π.tag J ∈ s` is less than `ε / 2`. We need an additional multiplier `2 ^ #ι` because different boxes can have the same tag. For `x ∉ s`, we choose `r x` so that `dist (vol (J (f x))) (g J) ≤ (ε / 2 / B I) * B J` for a box `J` in the `δ`-neighborhood of `x`. -/ refine ((l.has_basis_to_filter_Union_top _).tendsto_iff metric.nhds_basis_closed_ball).2 _, intros ε ε0, simp only [subtype.exists'] at H₁ H₂, choose! δ₁ Hδ₁ using H₁, choose! δ₂ Hδ₂ using H₂, have ε0' := half_pos ε0, have H0 : 0 < (2 ^ fintype.card ι : ℝ), from pow_pos zero_lt_two _, rcases hs.exists_pos_forall_sum_le (div_pos ε0' H0) with ⟨εs, hεs0, hεs⟩, simp only [le_div_iff' H0, mul_sum] at hεs, rcases exists_pos_mul_lt ε0' (B I) with ⟨ε', ε'0, hεI⟩, set δ : ℝ≥0 → ℝⁿ → Ioi (0 : ℝ) := λ c x, if x ∈ s then δ₁ c x (εs x) else (δ₂ c) x ε', refine ⟨δ, λ c, l.r_cond_of_bRiemann_eq_ff hl, _⟩, simp only [set.mem_Union, mem_inter_iff, mem_set_of_eq], rintro π ⟨c, hπδ, hπp⟩, /- Now we split the sum into two parts based on whether `π.tag J` belongs to `s` or not. -/ rw [← g.sum_partition_boxes le_rfl hπp, mem_closed_ball, integral_sum, ← sum_filter_add_sum_filter_not π.boxes (λ J, π.tag J ∈ s), ← sum_filter_add_sum_filter_not π.boxes (λ J, π.tag J ∈ s), ← add_halves ε], refine dist_add_add_le_of_le _ _, { unfreezingI { rcases s.eq_empty_or_nonempty with rfl|hsne }, { simp [ε0'.le] }, /- For the boxes such that `π.tag J ∈ s`, we use the fact that at most `2 ^ #ι` boxes have the same tag. -/ specialize hlH hsne, have : ∀ J ∈ π.boxes.filter (λ J, π.tag J ∈ s), dist (vol J (f $ π.tag J)) (g J) ≤ εs (π.tag J), { intros J hJ, rw finset.mem_filter at hJ, cases hJ with hJ hJs, refine Hδ₁ c _ ⟨π.tag_mem_Icc _, hJs⟩ _ (hεs0 _) _ (π.le_of_mem' _ hJ) _ (hπδ.2 hlH J hJ) (λ hD, (finset.le_sup hJ).trans (hπδ.3 hD)), convert hπδ.1 J hJ, exact (dif_pos hJs).symm }, refine (dist_sum_sum_le_of_le _ this).trans _, rw sum_comp, refine (sum_le_sum _).trans (hεs _ _), { rintro b -, rw [← nat.cast_two, ← nat.cast_pow, ← nsmul_eq_mul], refine nsmul_le_nsmul (hεs0 _).le _, refine (finset.card_le_of_subset _).trans ((hπδ.is_Henstock hlH).card_filter_tag_eq_le b), exact filter_subset_filter _ (filter_subset _ _) }, { rw [finset.coe_image, set.image_subset_iff], exact λ J hJ, (finset.mem_filter.1 hJ).2 } }, /- Now we deal with boxes such that `π.tag J ∉ s`. In this case the estimate is straightforward. -/ have H₂ : ∀ J ∈ π.boxes.filter (λ J, π.tag J ∉ s), dist (vol J (f $ π.tag J)) (g J) ≤ ε' * B J, { intros J hJ, rw finset.mem_filter at hJ, cases hJ with hJ hJs, refine Hδ₂ c _ ⟨π.tag_mem_Icc _, hJs⟩ _ ε'0 _ (π.le_of_mem' _ hJ) _ (λ hH, hπδ.2 hH J hJ) (λ hD, (finset.le_sup hJ).trans (hπδ.3 hD)), convert hπδ.1 J hJ, exact (dif_neg hJs).symm }, refine (dist_sum_sum_le_of_le _ H₂).trans ((sum_le_sum_of_subset_of_nonneg (filter_subset _ _) _).trans _), { exact λ _ _ _, mul_nonneg ε'0.le (hB0 _) }, { rw [← mul_sum, B.sum_partition_boxes le_rfl hπp, mul_comm], exact hεI.le } end /-- A function `f` has Henstock (or `⊥`) integral over `I` is equal to the value of a box-additive function `g` on `I` provided that `vol J (f x)` is sufficiently close to `g J` for sufficiently small boxes `J ∋ x`. This lemma is useful to prove, e.g., to prove the Divergence theorem for integral along `⊥`. Let `l` be either `box_integral.integration_params.Henstock` or `⊥`. Let `g` a box-additive function on subboxes of `I`. Suppose that there exists a nonnegative box-additive function `B` and a countable set `s` with the following property. For every `c : ℝ≥0`, a point `x ∈ I.Icc`, and a positive `ε` there exists `δ > 0` such that for any box `J ≤ I` such that - `x ∈ J.Icc ⊆ metric.closed_ball x δ`; - if `l.bDistortion` (i.e., `l = ⊥`), then the distortion of `J` is less than or equal to `c`, the distance between the term `vol J (f x)` of an integral sum corresponding to `J` and `g J` is less than or equal to `ε` if `x ∈ s` and is less than or equal to `ε * B J` otherwise. Then `f` is integrable on `I along `l` with integral `g I`. -/ lemma has_integral_of_le_Henstock_of_forall_is_o (hl : l ≤ Henstock) (B : ι →ᵇᵃ[I] ℝ) (hB0 : ∀ J, 0 ≤ B J) (g : ι →ᵇᵃ[I] F) (s : set ℝⁿ) (hs : s.countable) (H₁ : ∀ (c : ℝ≥0) (x ∈ I.Icc ∩ s) (ε > (0 : ℝ)), ∃ δ > 0, ∀ J ≤ I, J.Icc ⊆ metric.closed_ball x δ → x ∈ J.Icc → (l.bDistortion → J.distortion ≤ c) → dist (vol J (f x)) (g J) ≤ ε) (H₂ : ∀ (c : ℝ≥0) (x ∈ I.Icc \ s) (ε > (0 : ℝ)), ∃ δ > 0, ∀ J ≤ I, J.Icc ⊆ metric.closed_ball x δ → x ∈ J.Icc → (l.bDistortion → J.distortion ≤ c) → dist (vol J (f x)) (g J) ≤ ε * B J) : has_integral I l f vol (g I) := have A : l.bHenstock, from hl.2.1.resolve_left dec_trivial, has_integral_of_bRiemann_eq_ff_of_forall_is_o (hl.1.resolve_right dec_trivial) B hB0 _ s hs (λ _, A) H₁ $ by simpa only [A, true_implies_iff] using H₂ /-- Suppose that there exists a nonnegative box-additive function `B` with the following property. For every `c : ℝ≥0`, a point `x ∈ I.Icc`, and a positive `ε` there exists `δ > 0` such that for any box `J ≤ I` such that - `J.Icc ⊆ metric.closed_ball x δ`; - if `l.bDistortion` (i.e., `l = ⊥`), then the distortion of `J` is less than or equal to `c`, the distance between the term `vol J (f x)` of an integral sum corresponding to `J` and `g J` is less than or equal to `ε * B J`. Then `f` is McShane integrable on `I` with integral `g I`. -/ lemma has_integral_McShane_of_forall_is_o (B : ι →ᵇᵃ[I] ℝ) (hB0 : ∀ J, 0 ≤ B J) (g : ι →ᵇᵃ[I] F) (H : ∀ (c : ℝ≥0) (x ∈ I.Icc) (ε > (0 : ℝ)), ∃ δ > 0, ∀ J ≤ I, J.Icc ⊆ metric.closed_ball x δ → dist (vol J (f x)) (g J) ≤ ε * B J) : has_integral I McShane f vol (g I) := has_integral_of_bRiemann_eq_ff_of_forall_is_o rfl B hB0 g ∅ countable_empty (λ ⟨x, hx⟩, hx.elim) (λ c x hx, hx.2.elim) $ by simpa only [McShane, coe_sort_ff, false_implies_iff, true_implies_iff, diff_empty] using H end box_integral
7cfb7d8deebd1d99405057ce9b444085eb2d9ddf
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/ind_ns.lean
582ee14a585102caa772b57ba074083cf3c4a7cb
[ "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
126
lean
inductive day := monday | tuesday | wednesday | thursday | friday | saturday | sunday check day.monday open day check monday
113cde824b1c89220fd4e02a20b15875dbfacb61
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Compiler/IR/EmitC.lean
5bd7656381ac972f00268e1175de256a6d11e229
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
26,146
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Runtime import Lean.Compiler.NameMangling import Lean.Compiler.ExportAttr import Lean.Compiler.InitAttr import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.EmitUtil import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.SimpCase import Lean.Compiler.IR.Boxing namespace Lean.IR.EmitC open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName) def leanMainFn := "_lean_main" structure Context where env : Environment modName : Name jpMap : JPParamsMap := {} mainFn : FunId := default mainParams : Array Param := #[] abbrev M := ReaderT Context (EStateM String String) def getEnv : M Environment := Context.env <$> read def getModName : M Name := Context.modName <$> read def getDecl (n : Name) : M Decl := do let env ← getEnv match findEnvDecl env n with | some d => pure d | none => throw s!"unknown declaration '{n}'" @[inline] def emit {α : Type} [ToString α] (a : α) : M Unit := modify fun out => out ++ toString a @[inline] def emitLn {α : Type} [ToString α] (a : α) : M Unit := do emit a; emit "\n" def emitLns {α : Type} [ToString α] (as : List α) : M Unit := as.forM fun a => emitLn a def argToCString (x : Arg) : String := match x with | Arg.var x => toString x | _ => "lean_box(0)" def emitArg (x : Arg) : M Unit := emit (argToCString x) def toCType : IRType → String | IRType.float => "double" | IRType.uint8 => "uint8_t" | IRType.uint16 => "uint16_t" | IRType.uint32 => "uint32_t" | IRType.uint64 => "uint64_t" | IRType.usize => "size_t" | IRType.object => "lean_object*" | IRType.tobject => "lean_object*" | IRType.irrelevant => "lean_object*" | IRType.struct _ _ => panic! "not implemented yet" | IRType.union _ _ => panic! "not implemented yet" def throwInvalidExportName {α : Type} (n : Name) : M α := throw s!"invalid export name '{n}'" def toCName (n : Name) : M String := do let env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor? env n with | some (.str .anonymous s) => pure s | some _ => throwInvalidExportName n | none => if n == `main then pure leanMainFn else pure n.mangle def emitCName (n : Name) : M Unit := toCName n >>= emit def toCInitName (n : Name) : M String := do let env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor? env n with | some (.str .anonymous s) => return "_init_" ++ s | some _ => throwInvalidExportName n | none => pure ("_init_" ++ n.mangle) def emitCInitName (n : Name) : M Unit := toCInitName n >>= emit def emitFnDeclAux (decl : Decl) (cppBaseName : String) (isExternal : Bool) : M Unit := do let ps := decl.params let env ← getEnv if ps.isEmpty then if isClosedTermName env decl.name then emit "static " else if isExternal then emit "extern " else emit "LEAN_EXPORT " else if !isExternal then emit "LEAN_EXPORT " emit (toCType decl.resultType ++ " " ++ cppBaseName) unless ps.isEmpty do emit "(" -- We omit irrelevant parameters for extern constants let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps if ps.size > closureMaxArgs && isBoxedName decl.name then emit "lean_object**" else ps.size.forM fun i => do if i > 0 then emit ", " emit (toCType ps[i]!.ty) emit ")" emitLn ";" def emitFnDecl (decl : Decl) (isExternal : Bool) : M Unit := do let cppBaseName ← toCName decl.name emitFnDeclAux decl cppBaseName isExternal def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do let env ← getEnv let extC := isExternC env decl.name emitFnDeclAux decl cNameStr extC def emitFnDecls : M Unit := do let env ← getEnv let decls := getDecls env let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {} let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {} let usedDecls := usedDecls.toList usedDecls.forM fun n => do let decl ← getDecl n; match getExternNameFor env `c decl.name with | some cName => emitExternDeclAux decl cName | none => emitFnDecl decl (!modDecls.contains n) def emitMainFn : M Unit := do let d ← getDecl `main match d with | .fdecl (xs := xs) .. => do unless xs.size == 2 || xs.size == 1 do throw "invalid main function, incorrect arity when generating code" let env ← getEnv let usesLeanAPI := usesModuleFrom env `Lean if usesLeanAPI then emitLn "void lean_initialize();" else emitLn "void lean_initialize_runtime_module();"; emitLn " #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif int main(int argc, char ** argv) { #if defined(WIN32) || defined(_WIN32) SetErrorMode(SEM_FAILCRITICALERRORS); #endif lean_object* in; lean_object* res;"; if usesLeanAPI then emitLn "lean_initialize();" else emitLn "lean_initialize_runtime_module();" let modName ← getModName /- We disable panic messages because they do not mesh well with extracted closed terms. See issue #534. We can remove this workaround after we implement issue #467. -/ emitLn "lean_set_panic_messages(false);" emitLn ("res = " ++ mkModuleInitializationFunctionName modName ++ "(1 /* builtin */, lean_io_mk_world());") emitLn "lean_set_panic_messages(true);" emitLns ["lean_io_mark_end_initialization();", "if (lean_io_result_is_ok(res)) {", "lean_dec_ref(res);", "lean_init_task_manager();"]; if xs.size == 2 then emitLns ["in = lean_box(0);", "int i = argc;", "while (i > 1) {", " lean_object* n;", " i--;", " n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);", " in = n;", "}"] emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());") else emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());") emitLn "}" -- `IO _` let retTy := env.find? `main |>.get! |>.type |>.getForallBody -- either `UInt32` or `(P)Unit` let retTy := retTy.appArg! -- finalize at least the task manager to avoid leak sanitizer false positives from tasks outliving the main thread emitLns ["lean_finalize_task_manager();", "if (lean_io_result_is_ok(res)) {", " int ret = " ++ if retTy.constName? == some ``UInt32 then "lean_unbox_uint32(lean_io_result_get_value(res));" else "0;", " lean_dec_ref(res);", " return ret;", "} else {", " lean_io_result_show_error(res);", " lean_dec_ref(res);", " return 1;", "}"] emitLn "}" | _ => throw "function declaration expected" def hasMainFn : M Bool := do let env ← getEnv let decls := getDecls env return decls.any (fun d => d.name == `main) def emitMainFnIfNeeded : M Unit := do if (← hasMainFn) then emitMainFn def emitFileHeader : M Unit := do let env ← getEnv let modName ← getModName emitLn "// Lean compiler output" emitLn ("// Module: " ++ toString modName) emit "// Imports:" env.imports.forM fun m => emit (" " ++ toString m) emitLn "" emitLn "#include <lean/lean.h>" emitLns [ "#if defined(__clang__)", "#pragma clang diagnostic ignored \"-Wunused-parameter\"", "#pragma clang diagnostic ignored \"-Wunused-label\"", "#elif defined(__GNUC__) && !defined(__CLANG__)", "#pragma GCC diagnostic ignored \"-Wunused-parameter\"", "#pragma GCC diagnostic ignored \"-Wunused-label\"", "#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"", "#endif", "#ifdef __cplusplus", "extern \"C\" {", "#endif" ] def emitFileFooter : M Unit := emitLns [ "#ifdef __cplusplus", "}", "#endif" ] def throwUnknownVar {α : Type} (x : VarId) : M α := throw s!"unknown variable '{x}'" def getJPParams (j : JoinPointId) : M (Array Param) := do let ctx ← read; match ctx.jpMap.find? j with | some ps => pure ps | none => throw "unknown join point" def declareVar (x : VarId) (t : IRType) : M Unit := do emit (toCType t); emit " "; emit x; emit "; " def declareParams (ps : Array Param) : M Unit := ps.forM fun p => declareVar p.x p.ty partial def declareVars : FnBody → Bool → M Bool | e@(FnBody.vdecl x t _ b), d => do let ctx ← read if isTailCallTo ctx.mainFn e then pure d else declareVar x t; declareVars b true | FnBody.jdecl _ xs _ b, d => do declareParams xs; declareVars b (d || xs.size > 0) | e, d => if e.isTerminal then pure d else declareVars e.body d def emitTag (x : VarId) (xType : IRType) : M Unit := do if xType.isObj then do emit "lean_obj_tag("; emit x; emit ")" else emit x def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) := if alts.size != 2 then none else match alts[0]! with | Alt.ctor c b => some (c.cidx, b, alts[1]!.body) | _ => none def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit $ if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n") else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n") emit "("; emit x if n != 1 then emit ", "; emit n emitLn ");" def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit (if checkRef then "lean_dec" else "lean_dec_ref"); emit "("; emit x; if n != 1 then emit ", "; emit n emitLn ");" def emitDel (x : VarId) : M Unit := do emit "lean_free_object("; emit x; emitLn ");" def emitSetTag (x : VarId) (i : Nat) : M Unit := do emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");" def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" def emitOffset (n : Nat) (offset : Nat) : M Unit := do if n > 0 then emit "sizeof(void*)*"; emit n; if offset > 0 then emit " + "; emit offset else emit offset def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");" def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do match t with | IRType.float => emit "lean_ctor_set_float" | IRType.uint8 => emit "lean_ctor_set_uint8" | IRType.uint16 => emit "lean_ctor_set_uint16" | IRType.uint32 => emit "lean_ctor_set_uint32" | IRType.uint64 => emit "lean_ctor_set_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");" def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do let ps ← getJPParams j unless xs.size == ps.size do throw "invalid goto" xs.size.forM fun i => do let p := ps[i]! let x := xs[i]! emit p.x; emit " = "; emitArg x; emitLn ";" emit "goto "; emit j; emitLn ";" def emitLhs (z : VarId) : M Unit := do emit z; emit " = " def emitArgs (ys : Array Arg) : M Unit := ys.size.forM fun i => do if i > 0 then emit ", " emitArg ys[i]! def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := do if usize == 0 then emit ssize else if ssize == 0 then emit "sizeof(size_t)*"; emit usize else emit "sizeof(size_t)*"; emit usize; emit " + "; emit ssize def emitAllocCtor (c : CtorInfo) : M Unit := do emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", " emitCtorScalarSize c.usize c.ssize; emitLn ");" def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit := ys.size.forM fun i => do emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg ys[i]!; emitLn ");" def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do emitLhs z; if c.size == 0 && c.usize == 0 && c.ssize == 0 then do emit "lean_box("; emit c.cidx; emitLn ");" else do emitAllocCtor c; emitCtorSetArgs z ys def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do emit "if (lean_is_exclusive("; emit x; emitLn ")) {"; n.forM fun i => do emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");" emit " "; emitLhs z; emit x; emitLn ";"; emitLn "} else {"; emit " lean_dec_ref("; emit x; emitLn ");"; emit " "; emitLhs z; emitLn "lean_box(0);"; emitLn "}" def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do emit "if (lean_is_scalar("; emit x; emitLn ")) {"; emit " "; emitLhs z; emitAllocCtor c; emitLn "} else {"; emit " "; emitLhs z; emit x; emitLn ";"; if updtHeader then emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");" emitLn "}"; emitCtorSetArgs z ys def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");" def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");" def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.float => emit "lean_ctor_get_float" | IRType.uint8 => emit "lean_ctor_get_uint8" | IRType.uint16 => emit "lean_ctor_get_uint16" | IRType.uint32 => emit "lean_ctor_get_uint32" | IRType.uint64 => emit "lean_ctor_get_uint64" | _ => throw "invalid instruction" emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");" def toStringArgs (ys : Array Arg) : List String := ys.toList.map argToCString def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do emit f; emit "(" -- We must remove irrelevant arguments to extern calls. discard <| ys.size.foldM (fun i (first : Bool) => if ps[i]!.ty.isIrrelevant then pure first else do unless first do emit ", " emitArg ys[i]! pure false) true emitLn ");" pure () def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit := match getExternEntryFor extData `c with | some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys | some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";" | some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys | _ => throw s!"failed to emit extern application '{f}'" def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do emitLhs z let decl ← getDecl f match decl with | Decl.extern _ ps _ extData => emitExternCall f ps extData ys | _ => emitCName f if ys.size > 0 then emit "("; emitArgs ys; emit ")" emitLn ";" def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do let decl ← getDecl f let arity := decl.params.size; emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");"; ys.size.forM fun i => do let y := ys[i]! emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit := if ys.size > closureMaxArgs then do emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};"; emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }" else do emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");" def emitBoxFn (xType : IRType) : M Unit := match xType with | IRType.usize => emit "lean_box_usize" | IRType.uint32 => emit "lean_box_uint32" | IRType.uint64 => emit "lean_box_uint64" | IRType.float => emit "lean_box_float" | _ => emit "lean_box" def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");" def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do emitLhs z emit (getUnboxOpName t) emit "("; emit x; emitLn ");" def emitIsShared (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");" def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");" def toHexDigit (c : Nat) : String := String.singleton c.digitChar def quoteString (s : String) : String := let q := "\""; let q := s.foldl (fun q c => q ++ if c == '\n' then "\\n" else if c == '\r' then "\\r" else if c == '\t' then "\\t" else if c == '\\' then "\\\\" else if c == '\"' then "\\\"" else if c.toNat <= 31 then "\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16) -- TODO(Leo): we should use `\unnnn` for escaping unicode characters. else String.singleton c) q; q ++ "\"" def emitNumLit (t : IRType) (v : Nat) : M Unit := do if t.isObj then if v < UInt32.size then emit "lean_unsigned_to_nat("; emit v; emit "u)" else emit "lean_cstr_to_nat(\""; emit v; emit "\")" else emit v def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit := do emitLhs z; match v with | LitVal.num v => emitNumLit t v; emitLn ";" | LitVal.str v => emit "lean_mk_string_from_bytes("; emit (quoteString v); emit ", "; emit v.utf8ByteSize; emitLn ");" def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit := match v with | Expr.ctor c ys => emitCtor z c ys | Expr.reset n x => emitReset z n x | Expr.reuse x c u ys => emitReuse z x c u ys | Expr.proj i x => emitProj z i x | Expr.uproj i x => emitUProj z i x | Expr.sproj n o x => emitSProj z t n o x | Expr.fap c ys => emitFullApp z c ys | Expr.pap c ys => emitPartialApp z c ys | Expr.ap x ys => emitApp z x ys | Expr.box t x => emitBox z x t | Expr.unbox x => emitUnbox z t x | Expr.isShared x => emitIsShared z x | Expr.isTaggedPtr x => emitIsTaggedPtr z x | Expr.lit v => emitLit z t v def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do let ctx ← read; match v, b with | Expr.fap f _, FnBody.ret (Arg.var y) => return f == ctx.mainFn && x == y | _, _ => pure false def paramEqArg (p : Param) (x : Arg) : Bool := match x with | Arg.var x => p.x == x | _ => false /-- Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments ``` p_0 := y_0, ... p_{n-1} := y_{n-1} ``` Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`. That is, we have ``` p_i := y_i, ... p_j := p_i, -- p_i was overwritten above ``` -/ def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool := let n := ps.size; n.any fun i => let p := ps[i]! (i+1, n).anyI fun j => paramEqArg p ys[j]! def emitTailCall (v : Expr) : M Unit := match v with | Expr.fap _ ys => do let ctx ← read let ps := ctx.mainParams unless ps.size == ys.size do throw "invalid tail call" if overwriteParam ps ys then emitLn "{" ps.size.forM fun i => do let p := ps[i]! let y := ys[i]! unless paramEqArg p y do emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";" ps.size.forM fun i => do let p := ps[i]! let y := ys[i]! unless paramEqArg p y do emit p.x; emit " = _tmp_"; emit i; emitLn ";" emitLn "}" else ys.size.forM fun i => do let p := ps[i]! let y := ys[i]! unless paramEqArg p y do emit p.x; emit " = "; emitArg y; emitLn ";" emitLn "goto _start;" | _ => throw "bug at emitTailCall" mutual partial def emitIf (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")"; emitFnBody t; emitLn "else"; emitFnBody e partial def emitCase (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit := match isIf alts with | some (tag, t, e) => emitIf x xType tag t e | _ => do emit "switch ("; emitTag x xType; emitLn ") {"; let alts := ensureHasDefault alts; alts.forM fun alt => do match alt with | Alt.ctor c b => emit "case "; emit c.cidx; emitLn ":"; emitFnBody b | Alt.default b => emitLn "default: "; emitFnBody b emitLn "}" partial def emitBlock (b : FnBody) : M Unit := do match b with | FnBody.jdecl _ _ _ b => emitBlock b | d@(FnBody.vdecl x t v b) => let ctx ← read if isTailCallTo ctx.mainFn d then emitTailCall v else emitVDecl x t v emitBlock b | FnBody.inc x n c p b => unless p do emitInc x n c emitBlock b | FnBody.dec x n c p b => unless p do emitDec x n c emitBlock b | FnBody.del x b => emitDel x; emitBlock b | FnBody.setTag x i b => emitSetTag x i; emitBlock b | FnBody.set x i y b => emitSet x i y; emitBlock b | FnBody.uset x i y b => emitUSet x i y; emitBlock b | FnBody.sset x i o y t b => emitSSet x i o y t; emitBlock b | FnBody.mdata _ b => emitBlock b | FnBody.ret x => emit "return "; emitArg x; emitLn ";" | FnBody.case _ x xType alts => emitCase x xType alts | FnBody.jmp j xs => emitJmp j xs | FnBody.unreachable => emitLn "lean_internal_panic_unreachable();" partial def emitJPs : FnBody → M Unit | FnBody.jdecl j _ v b => do emit j; emitLn ":"; emitFnBody v; emitJPs b | e => do unless e.isTerminal do emitJPs e.body partial def emitFnBody (b : FnBody) : M Unit := do emitLn "{" let declared ← declareVars b false if declared then emitLn "" emitBlock b emitJPs b emitLn "}" end def emitDeclAux (d : Decl) : M Unit := do let env ← getEnv let (_, jpMap) := mkVarJPMaps d withReader (fun ctx => { ctx with jpMap := jpMap }) do unless hasInitAttr env d.name do match d with | .fdecl (f := f) (xs := xs) (type := t) (body := b) .. => let baseName ← toCName f; if xs.size == 0 then emit "static " else emit "LEAN_EXPORT " -- make symbol visible to the interpreter emit (toCType t); emit " "; if xs.size > 0 then emit baseName; emit "("; if xs.size > closureMaxArgs && isBoxedName d.name then emit "lean_object** _args" else xs.size.forM fun i => do if i > 0 then emit ", " let x := xs[i]! emit (toCType x.ty); emit " "; emit x.x emit ")" else emit ("_init_" ++ baseName ++ "()") emitLn " {"; if xs.size > closureMaxArgs && isBoxedName d.name then xs.size.forM fun i => do let x := xs[i]! emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];" emitLn "_start:"; withReader (fun ctx => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b); emitLn "}" | _ => pure () def emitDecl (d : Decl) : M Unit := do let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices try emitDeclAux d catch err => throw s!"{err}\ncompiling:\n{d}" def emitFns : M Unit := do let env ← getEnv; let decls := getDecls env; decls.reverse.forM emitDecl def emitMarkPersistent (d : Decl) (n : Name) : M Unit := do if d.resultType.isObj then emit "lean_mark_persistent(" emitCName n emitLn ");" def emitDeclInit (d : Decl) : M Unit := do let env ← getEnv let n := d.name if isIOUnitInitFn env n then emit "res = "; emitCName n; emitLn "(lean_io_mk_world());" emitLn "if (lean_io_result_is_error(res)) return res;" emitLn "lean_dec_ref(res);" else if d.params.size == 0 then match getInitFnNameFor? env d.name with | some initFn => if getBuiltinInitFnNameFor? env d.name |>.isSome then emit "if (builtin) {" emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());" emitLn "if (lean_io_result_is_error(res)) return res;" emitCName n if d.resultType.isScalar then emitLn (" = " ++ getUnboxOpName d.resultType ++ "(lean_io_result_get_value(res));") else emitLn " = lean_io_result_get_value(res);" emitMarkPersistent d n emitLn "lean_dec_ref(res);" if getBuiltinInitFnNameFor? env d.name |>.isSome then emit "}" | _ => emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n def emitInitFn : M Unit := do let env ← getEnv let modName ← getModName env.imports.forM fun imp => emitLn ("lean_object* " ++ mkModuleInitializationFunctionName imp.module ++ "(uint8_t builtin, lean_object*);") emitLns [ "static bool _G_initialized = false;", "LEAN_EXPORT lean_object* " ++ mkModuleInitializationFunctionName modName ++ "(uint8_t builtin, lean_object* w) {", "lean_object * res;", "if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));", "_G_initialized = true;" ] env.imports.forM fun imp => emitLns [ "res = " ++ mkModuleInitializationFunctionName imp.module ++ "(builtin, lean_io_mk_world());", "if (lean_io_result_is_error(res)) return res;", "lean_dec_ref(res);"] let decls := getDecls env decls.reverse.forM emitDeclInit emitLns ["return lean_io_result_mk_ok(lean_box(0));", "}"] def main : M Unit := do emitFileHeader emitFnDecls emitFns emitInitFn emitMainFnIfNeeded emitFileFooter end EmitC @[export lean_ir_emit_c] def emitC (env : Environment) (modName : Name) : Except String String := match (EmitC.main { env := env, modName := modName }).run "" with | EStateM.Result.ok _ s => Except.ok s | EStateM.Result.error err _ => Except.error err end Lean.IR
06f454ff3e6a6011d72171aa570118c508030f5d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/trunc_cases.lean
ed45218d1765de27146a4072c659563229ac1f7e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,408
lean
import tactic.trunc_cases import tactic.interactive import tactic.congr import data.quot example (t : trunc ℕ) : punit := begin trunc_cases t, exact (), -- no more goals, because `trunc_cases` used the correct `trunc.rec_on_subsingleton` recursor end example (t : trunc ℕ) : ℕ := begin trunc_cases t, guard_hyp t : ℕ, -- verify that the new hypothesis is still called `t`. exact 0, -- verify that we don't even need to use `simp`, -- because `trunc_cases` has already removed the `eq.rec`. refl, end example {α : Type} [subsingleton α] (I : trunc (has_zero α)) : α := begin trunc_cases I, exact 0, end /-- A mock typeclass, set up so that it's possible to extract data from `trunc (has_unit α)`. -/ class has_unit (α : Type) [has_one α] := (unit : α) (unit_eq_one : unit = 1) def u {α : Type} [has_one α] [has_unit α] : α := has_unit.unit attribute [simp] has_unit.unit_eq_one example {α : Type} [has_one α] (I : trunc (has_unit α)) : α := begin trunc_cases I, exact u, -- Verify that the typeclass is immediately available -- Verify that there's no `eq.rec` in the goal. (do tgt ← tactic.target, eq_rec ← tactic.mk_const `eq.rec, guard $ ¬ eq_rec.occurs tgt), simp [u], end universes v w z /-- Transport through a product is given by individually transporting each component. -/ -- It's a pity that this is no good as a `simp` lemma. -- (It seems the unification problem with `λ a, W a × Z a` is too hard.) -- (One could write a tactic to syntactically analyse `eq.rec` expressions -- and simplify more of them!) lemma eq_rec_prod {α : Sort v} (W : α → Type w) (Z : α → Type z) {a b : α} (p : W a × Z a) (h : a = b) : @eq.rec α a (λ a, W a × Z a) p b h = (@eq.rec α a W p.1 b h, @eq.rec α a Z p.2 b h) := begin cases h, simp only [prod.mk.eta], end -- This time, we make a goal that (quite artificially) depends on the `trunc`. example {α : Type} [has_one α] (I : trunc (has_unit α)) : α × plift (I = I) := begin -- This time `trunc_cases` has no choice but to use `trunc.rec_on`. trunc_cases I, { exact ⟨u, plift.up rfl⟩, }, { -- And so we get an `eq.rec` in the invariance goal. -- Since `simp` can't handle it because of the unification problem, -- for now we have to handle it by hand. convert eq_rec_prod (λ I, α) (λ I, plift (I = I)) _ _, { simp [u], }, { ext, } } end
bf77690cd5f490afefe07b56ecd4e8d20d419ab1
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/list/sigma.lean
6c24e1d90aa3627bb1012977c6241c83dce40abf
[ "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
25,163
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Sean Leather Functions on lists of sigma types. -/ import data.list.perm import data.list.range import data.sigma /-! # Utilities for lists of sigmas This file includes several ways of interacting with `list (sigma β)`, treated as a key-value store. ## Main Definitions - `list.keys` extracts the list of keys. - `list.nodupkeys` determines if the store has duplicate keys. - `list.lookup`/`lookup_all` accesses the value(s) of a particular key. - `list.kreplace` modifies a value. - `list.kerase` removes a value. - `list.kinsert` inserts a value. - `list.kunion` computes the union of two stores. -/ universes u v namespace list variables {α : Type u} {β : α → Type v} /- keys -/ /-- List of keys from a list of key-value pairs -/ def keys : list (sigma β) → list α := map sigma.fst @[simp] theorem keys_nil : @keys α β [] = [] := rfl @[simp] theorem keys_cons {s} {l : list (sigma β)} : (s :: l).keys = s.1 :: l.keys := rfl theorem mem_keys_of_mem {s : sigma β} {l : list (sigma β)} : s ∈ l → s.1 ∈ l.keys := mem_map_of_mem sigma.fst theorem exists_of_mem_keys {a} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a), sigma.mk a b ∈ l := let ⟨⟨a', b'⟩, m, e⟩ := exists_of_mem_map h in eq.rec_on e (exists.intro b' m) theorem mem_keys {a} {l : list (sigma β)} : a ∈ l.keys ↔ ∃ (b : β a), sigma.mk a b ∈ l := ⟨exists_of_mem_keys, λ ⟨b, h⟩, mem_keys_of_mem h⟩ theorem not_mem_keys {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ b : β a, sigma.mk a b ∉ l := (not_iff_not_of_iff mem_keys).trans not_exists theorem not_eq_key {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ s : sigma β, s ∈ l → a ≠ s.1 := iff.intro (λ h₁ s h₂ e, absurd (mem_keys_of_mem h₂) (by rwa e at h₁)) (λ f h₁, let ⟨b, h₂⟩ := exists_of_mem_keys h₁ in f _ h₂ rfl) /- nodupkeys -/ def nodupkeys (l : list (sigma β)) : Prop := l.keys.nodup theorem nodupkeys_iff_pairwise {l} : nodupkeys l ↔ pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := pairwise_map _ theorem nodupkeys.pairwise_ne {l} (h : nodupkeys l) : pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := nodupkeys_iff_pairwise.1 h @[simp] theorem nodupkeys_nil : @nodupkeys α β [] := pairwise.nil @[simp] theorem nodupkeys_cons {s : sigma β} {l : list (sigma β)} : nodupkeys (s::l) ↔ s.1 ∉ l.keys ∧ nodupkeys l := by simp [keys, nodupkeys] theorem nodupkeys.eq_of_fst_eq {l : list (sigma β)} (nd : nodupkeys l) {s s' : sigma β} (h : s ∈ l) (h' : s' ∈ l) : s.1 = s'.1 → s = s' := @forall_of_forall_of_pairwise _ (λ s s' : sigma β, s.1 = s'.1 → s = s') (λ s s' H h, (H h.symm).symm) _ (λ x h _, rfl) ((nodupkeys_iff_pairwise.1 nd).imp (λ s s' h h', (h h').elim)) _ h _ h' theorem nodupkeys.eq_of_mk_mem {a : α} {b b' : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) (h' : sigma.mk a b' ∈ l) : b = b' := by cases nd.eq_of_fst_eq h h' rfl; refl theorem nodupkeys_singleton (s : sigma β) : nodupkeys [s] := nodup_singleton _ theorem nodupkeys_of_sublist {l₁ l₂ : list (sigma β)} (h : l₁ <+ l₂) : nodupkeys l₂ → nodupkeys l₁ := nodup_of_sublist (h.map _) theorem nodup_of_nodupkeys {l : list (sigma β)} : nodupkeys l → nodup l := nodup_of_nodup_map _ theorem perm_nodupkeys {l₁ l₂ : list (sigma β)} (h : l₁ ~ l₂) : nodupkeys l₁ ↔ nodupkeys l₂ := (h.map _).nodup_iff theorem nodupkeys_join {L : list (list (sigma β))} : nodupkeys (join L) ↔ (∀ l ∈ L, nodupkeys l) ∧ pairwise disjoint (L.map keys) := begin rw [nodupkeys_iff_pairwise, pairwise_join, pairwise_map], refine and_congr (ball_congr $ λ l h, by simp [nodupkeys_iff_pairwise]) _, apply iff_of_eq, congr' with l₁ l₂, simp [keys, disjoint_iff_ne] end theorem nodup_enum_map_fst (l : list α) : (l.enum.map prod.fst).nodup := by simp [list.nodup_range] lemma mem_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodup) (nd₁ : l₁.nodup) (h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ := begin induction l₀ with x xs generalizing l₁; cases l₁ with y ys, { constructor }, iterate 2 { specialize h x <|> specialize h y, simp at h, cases h }, simp at nd₀ nd₁, classical, cases nd₀, cases nd₁, by_cases h' : x = y, { subst y, constructor, apply l₀_ih ‹ _ › ‹ nodup ys ›, intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro; assumption }, { simp [h'] at h, exact h } }, { transitivity x :: y :: ys.erase x, { constructor, apply l₀_ih ‹ _ ›, { simp, split, { intro, apply nd₁_left, apply mem_of_mem_erase ‹_› }, apply nodup_erase_of_nodup; assumption }, { intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro, simp [mem_erase_of_nodup,*], assumption }, { simp [h'] at h, simp [h], apply or_congr, refl, simp [mem_erase_of_ne,*] } } }, transitivity y :: x :: ys.erase x, { constructor }, { constructor, symmetry, apply perm_cons_erase, specialize h x, simp [h'] at h, exact h } } end variables [decidable_eq α] /- lookup -/ /-- `lookup a l` is the first value in `l` corresponding to the key `a`, or `none` if no such element exists. -/ def lookup (a : α) : list (sigma β) → option (β a) | [] := none | (⟨a', b⟩ :: l) := if h : a' = a then some (eq.rec_on h b) else lookup l @[simp] theorem lookup_nil (a : α) : lookup a [] = @none (β a) := rfl @[simp] theorem lookup_cons_eq (l) (a : α) (b : β a) : lookup a (⟨a, b⟩::l) = some b := dif_pos rfl @[simp] theorem lookup_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup a (s::l) = lookup a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_is_some {a : α} : ∀ {l : list (sigma β)}, (lookup a l).is_some ↔ a ∈ l.keys | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, lookup_is_some] }, end theorem lookup_eq_none {a : α} {l : list (sigma β)} : lookup a l = none ↔ a ∉ l.keys := by simp [← lookup_is_some, option.is_none_iff_eq_none] theorem of_mem_lookup {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup a l → sigma.mk a b ∈ l | (⟨a', b'⟩ :: l) H := begin by_cases h : a = a', { subst a', simp at H, simp [H] }, { simp [h] at H, exact or.inr (of_mem_lookup H) } end theorem mem_lookup {a} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) (h : sigma.mk a b ∈ l) : b ∈ lookup a l := begin cases option.is_some_iff_exists.mp (lookup_is_some.mpr (mem_keys_of_mem h)) with b' h', cases nd.eq_of_mk_mem h (of_mem_lookup h'), exact h' end theorem map_lookup_eq_find (a : α) : ∀ l : list (sigma β), (lookup a l).map (sigma.mk a) = find (λ s, a = s.1) l | [] := rfl | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, map_lookup_eq_find] } end theorem mem_lookup_iff {a : α} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) : b ∈ lookup a l ↔ sigma.mk a b ∈ l := ⟨of_mem_lookup, mem_lookup nd⟩ theorem perm_lookup (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup a l₁ = lookup a l₂ := by ext b; simp [mem_lookup_iff, nd₁, nd₂]; exact p.mem_iff lemma lookup_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodupkeys) (nd₁ : l₁.nodupkeys) (h : ∀ x y, y ∈ l₀.lookup x ↔ y ∈ l₁.lookup x) : l₀ ~ l₁ := mem_ext (nodup_of_nodupkeys nd₀) (nodup_of_nodupkeys nd₁) (λ ⟨a,b⟩, by rw [← mem_lookup_iff, ← mem_lookup_iff, h]; assumption) /- lookup_all -/ /-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/ def lookup_all (a : α) : list (sigma β) → list (β a) | [] := [] | (⟨a', b⟩ :: l) := if h : a' = a then eq.rec_on h b :: lookup_all l else lookup_all l @[simp] theorem lookup_all_nil (a : α) : lookup_all a [] = @nil (β a) := rfl @[simp] theorem lookup_all_cons_eq (l) (a : α) (b : β a) : lookup_all a (⟨a, b⟩::l) = b :: lookup_all a l := dif_pos rfl @[simp] theorem lookup_all_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup_all a (s::l) = lookup_all a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_all_eq_nil {a : α} : ∀ {l : list (sigma β)}, lookup_all a l = [] ↔ ∀ b : β a, sigma.mk a b ∉ l | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, lookup_all_eq_nil] }, end theorem head_lookup_all (a : α) : ∀ l : list (sigma β), head' (lookup_all a l) = lookup a l | [] := by simp | (⟨a', b⟩ :: l) := by by_cases h : a = a'; [{subst h, simp}, simp *] theorem mem_lookup_all {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup_all a l ↔ sigma.mk a b ∈ l | [] := by simp | (⟨a', b'⟩ :: l) := by by_cases h : a = a'; [{subst h, simp *}, simp *] theorem lookup_all_sublist (a : α) : ∀ l : list (sigma β), (lookup_all a l).map (sigma.mk a) <+ l | [] := by simp | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst h, simp, exact (lookup_all_sublist l).cons2 _ _ _ }, { simp [h], exact (lookup_all_sublist l).cons _ _ _ } end theorem lookup_all_length_le_one (a : α) {l : list (sigma β)} (h : l.nodupkeys) : length (lookup_all a l) ≤ 1 := by have := nodup_of_sublist ((lookup_all_sublist a l).map _) h; rw map_map at this; rwa [← nodup_repeat, ← map_const _ a] theorem lookup_all_eq_lookup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : lookup_all a l = (lookup a l).to_list := begin rw ← head_lookup_all, have := lookup_all_length_le_one a h, revert this, rcases lookup_all a l with _|⟨b, _|⟨c, l⟩⟩; intro; try {refl}, exact absurd this dec_trivial end theorem lookup_all_nodup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : (lookup_all a l).nodup := by rw lookup_all_eq_lookup a h; apply option.to_list_nodup theorem perm_lookup_all (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup_all a l₁ = lookup_all a l₂ := by simp [lookup_all_eq_lookup, nd₁, nd₂, perm_lookup a nd₁ nd₂ p] /- kreplace -/ def kreplace (a : α) (b : β a) : list (sigma β) → list (sigma β) := lookmap $ λ s, if h : a = s.1 then some ⟨a, b⟩ else none theorem kreplace_of_forall_not (a : α) (b : β a) {l : list (sigma β)} (H : ∀ b : β a, sigma.mk a b ∉ l) : kreplace a b l = l := lookmap_of_forall_not _ $ begin rintro ⟨a', b'⟩ h, dsimp, split_ifs, { subst a', exact H _ h }, {refl} end theorem kreplace_self {a : α} {b : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) : kreplace a b l = l := begin refine (lookmap_congr _).trans (lookmap_id' (option.guard (λ s, a = s.1)) _ _), { rintro ⟨a', b'⟩ h', dsimp [option.guard], split_ifs, { subst a', exact ⟨rfl, heq_of_eq $ nd.eq_of_mk_mem h h'⟩ }, { refl } }, { rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, dsimp [option.guard], split_ifs, { subst a₁, rintro ⟨⟩, simp }, { rintro ⟨⟩ } }, end theorem keys_kreplace (a : α) (b : β a) : ∀ l : list (sigma β), (kreplace a b l).keys = l.keys := lookmap_map_eq _ _ $ by rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩; dsimp; split_ifs; simp [h] {contextual := tt} theorem kreplace_nodupkeys (a : α) (b : β a) {l : list (sigma β)} : (kreplace a b l).nodupkeys ↔ l.nodupkeys := by simp [nodupkeys, keys_kreplace] theorem perm.kreplace {a : α} {b : β a} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kreplace a b l₁ ~ kreplace a b l₂ := perm_lookmap _ $ begin refine nd.pairwise_ne.imp _, intros x y h z h₁ w h₂, split_ifs at h₁ h₂; cases h₁; cases h₂, exact (h (h_2.symm.trans h_1)).elim end /- kerase -/ /-- Remove the first pair with the key `a`. -/ def kerase (a : α) : list (sigma β) → list (sigma β) := erasep $ λ s, a = s.1 @[simp] theorem kerase_nil {a} : @kerase _ β _ a [] = [] := rfl @[simp, priority 990] theorem kerase_cons_eq {a} {s : sigma β} {l : list (sigma β)} (h : a = s.1) : kerase a (s :: l) = l := by simp [kerase, h] @[simp, priority 990] theorem kerase_cons_ne {a} {s : sigma β} {l : list (sigma β)} (h : a ≠ s.1) : kerase a (s :: l) = s :: kerase a l := by simp [kerase, h] @[simp, priority 980] theorem kerase_of_not_mem_keys {a} {l : list (sigma β)} (h : a ∉ l.keys) : kerase a l = l := by induction l with _ _ ih; [refl, { simp [not_or_distrib] at h, simp [h.1, ih h.2] }] theorem kerase_sublist (a : α) (l : list (sigma β)) : kerase a l <+ l := erasep_sublist _ theorem kerase_keys_subset (a) (l : list (sigma β)) : (kerase a l).keys ⊆ l.keys := ((kerase_sublist a l).map _).subset theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : list (sigma β)} : a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys := @kerase_keys_subset _ _ _ _ _ _ theorem exists_of_kerase {a : α} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a) (l₁ l₂ : list (sigma β)), a ∉ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: l₂ ∧ kerase a l = l₁ ++ l₂ := begin induction l, case list.nil { cases h }, case list.cons : hd tl ih { by_cases e : a = hd.1, { subst e, exact ⟨hd.2, [], tl, by simp, by cases hd; refl, by simp⟩ }, { simp at h, cases h, case or.inl : h { exact absurd h e }, case or.inr : h { rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩, exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁, by rw h₂; refl, by simp [e, h₃]⟩ } } } end @[simp, priority 990] theorem mem_keys_kerase_of_ne {a₁ a₂} {l : list (sigma β)} (h : a₁ ≠ a₂) : a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys := iff.intro mem_keys_of_mem_keys_kerase $ λ p, if q : a₂ ∈ l.keys then match l, kerase a₂ l, exists_of_kerase q, p with | _, _, ⟨_, _, _, _, rfl, rfl⟩, p := by simpa [keys, h] using p end else by simp [q, p] theorem keys_kerase {a} {l : list (sigma β)} : (kerase a l).keys = l.keys.erase a := by rw [keys, kerase, ←erasep_map sigma.fst l, erase_eq_erasep] theorem kerase_kerase {a a'} {l : list (sigma β)} : (kerase a' l).kerase a = (kerase a l).kerase a' := begin by_cases a = a', { subst a' }, induction l with x xs, { refl }, { by_cases a' = x.1, { subst a', simp [kerase_cons_ne h,kerase_cons_eq rfl] }, by_cases h' : a = x.1, { subst a, simp [kerase_cons_eq rfl,kerase_cons_ne (ne.symm h)] }, { simp [kerase_cons_ne,*] } } end theorem kerase_nodupkeys (a : α) {l : list (sigma β)} : nodupkeys l → (kerase a l).nodupkeys := nodupkeys_of_sublist $ kerase_sublist _ _ theorem perm.kerase {a : α} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ := perm.erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $ by rintro x y h rfl; exact h @[simp] theorem not_mem_keys_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : a ∉ (kerase a l).keys := begin induction l, case list.nil { simp }, case list.cons : hd tl ih { simp at nd, by_cases h : a = hd.1, { subst h, simp [nd.1] }, { simp [h, ih nd.2] } } end @[simp] theorem lookup_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : lookup a (kerase a l) = none := lookup_eq_none.mpr (not_mem_keys_kerase a nd) @[simp] theorem lookup_kerase_ne {a a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kerase a' l) = lookup a l := begin induction l, case list.nil { refl }, case list.cons : hd tl ih { cases hd with ah bh, by_cases h₁ : a = ah; by_cases h₂ : a' = ah, { substs h₁ h₂, cases ne.irrefl h }, { subst h₁, simp [h₂] }, { subst h₂, simp [h] }, { simp [h₁, h₂, ih] } } end theorem kerase_append_left {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂ | [] _ h := by cases h | (s :: l₁) l₂ h₁ := if h₂ : a = s.1 then by simp [h₂] else by simp at h₁; cases h₁; [exact absurd h₁ h₂, simp [h₂, kerase_append_left h₁]] theorem kerase_append_right {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂ | [] _ h := rfl | (_ :: l₁) l₂ h := by simp [not_or_distrib] at h; simp [h.1, kerase_append_right h.2] theorem kerase_comm (a₁ a₂) (l : list (sigma β)) : kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) := if h : a₁ = a₂ then by simp [h] else if ha₁ : a₁ ∈ l.keys then if ha₂ : a₂ ∈ l.keys then match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with | _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, a₂_in_l₁_app_l₂ := if h' : a₂ ∈ l₁.keys then by simp [kerase_append_left h', kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)] else by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁, @kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (ne.symm h)] end else by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂] else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁] lemma sizeof_kerase {α} {β : α → Type*} [decidable_eq α] [has_sizeof (sigma β)] (x : α) (xs : list (sigma β)) : sizeof (list.kerase x xs) ≤ sizeof xs := begin unfold_wf, induction xs with y ys, { simp }, { by_cases x = y.1; simp [*, list.sizeof] }, end /- kinsert -/ /-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/ def kinsert (a : α) (b : β a) (l : list (sigma β)) : list (sigma β) := ⟨a, b⟩ :: kerase a l @[simp] theorem kinsert_def {a} {b : β a} {l : list (sigma β)} : kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl theorem mem_keys_kinsert {a a'} {b' : β a'} {l : list (sigma β)} : a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a'; simp [h] theorem kinsert_nodupkeys (a) (b : β a) {l : list (sigma β)} (nd : l.nodupkeys) : (kinsert a b l).nodupkeys := nodupkeys_cons.mpr ⟨not_mem_keys_kerase a nd, kerase_nodupkeys a nd⟩ theorem perm.kinsert {a} {b : β a} {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (p : l₁ ~ l₂) : kinsert a b l₁ ~ kinsert a b l₂ := (p.kerase nd₁).cons _ theorem lookup_kinsert {a} {b : β a} (l : list (sigma β)) : lookup a (kinsert a b l) = some b := by simp only [kinsert, lookup_cons_eq] theorem lookup_kinsert_ne {a a'} {b' : β a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kinsert a' b' l) = lookup a l := by simp [h] /- kextract -/ def kextract (a : α) : list (sigma β) → option (β a) × list (sigma β) | [] := (none, []) | (s::l) := if h : s.1 = a then (some (eq.rec_on h s.2), l) else let (b', l') := kextract l in (b', s :: l') @[simp] theorem kextract_eq_lookup_kerase (a : α) : ∀ l : list (sigma β), kextract a l = (lookup a l, kerase a l) | [] := rfl | (⟨a', b⟩::l) := begin simp [kextract], dsimp, split_ifs, { subst a', simp [kerase] }, { simp [kextract, ne.symm h, kextract_eq_lookup_kerase l, kerase] } end /- erase_dupkeys -/ /-- Remove entries with duplicate keys from `l : list (sigma β)`. -/ def erase_dupkeys : list (sigma β) → list (sigma β) := list.foldr (λ x, kinsert x.1 x.2) [] lemma erase_dupkeys_cons {x : sigma β} (l : list (sigma β)) : erase_dupkeys (x :: l) = kinsert x.1 x.2 (erase_dupkeys l) := rfl lemma nodupkeys_erase_dupkeys (l : list (sigma β)) : nodupkeys (erase_dupkeys l) := begin dsimp [erase_dupkeys], generalize hl : nil = l', have : nodupkeys l', { rw ← hl, apply nodup_nil }, clear hl, induction l with x xs, { apply this }, { cases x, simp [erase_dupkeys], split, { simp [keys_kerase], apply mem_erase_of_nodup l_ih }, apply kerase_nodupkeys _ l_ih, } end lemma lookup_erase_dupkeys (a : α) (l : list (sigma β)) : lookup a (erase_dupkeys l) = lookup a l := begin induction l, refl, cases l_hd with a' b, by_cases a = a', { subst a', rw [erase_dupkeys_cons,lookup_kinsert,lookup_cons_eq] }, { rw [erase_dupkeys_cons,lookup_kinsert_ne h,l_ih,lookup_cons_ne], exact h }, end lemma sizeof_erase_dupkeys {α} {β : α → Type*} [decidable_eq α] [has_sizeof (sigma β)] (xs : list (sigma β)) : sizeof (list.erase_dupkeys xs) ≤ sizeof xs := begin unfold_wf, induction xs with x xs, { simp [list.erase_dupkeys] }, { simp only [erase_dupkeys_cons, list.sizeof, kinsert_def, add_le_add_iff_left, sigma.eta], transitivity, apply sizeof_kerase, assumption } end /- kunion -/ /-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the first matching pair in l₂ is erased. -/ def kunion : list (sigma β) → list (sigma β) → list (sigma β) | [] l₂ := l₂ | (s :: l₁) l₂ := s :: kunion l₁ (kerase s.1 l₂) @[simp] theorem nil_kunion {l : list (sigma β)} : kunion [] l = l := rfl @[simp] theorem kunion_nil : ∀ {l : list (sigma β)}, kunion l [] = l | [] := rfl | (_ :: l) := by rw [kunion, kerase_nil, kunion_nil] @[simp] theorem kunion_cons {s} {l₁ l₂ : list (sigma β)} : kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) := rfl @[simp] theorem mem_keys_kunion {a} {l₁ l₂ : list (sigma β)} : a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s l₁ ih { by_cases h : a = s.1; [simp [h], simp [h, ih]] } end @[simp] theorem kunion_kerase {a} : ∀ {l₁ l₂ : list (sigma β)}, kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂) | [] _ := rfl | (s :: _) l := by by_cases h : a = s.1; simp [h, kerase_comm a s.1 l, kunion_kerase] theorem kunion_nodupkeys {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) : (kunion l₁ l₂).nodupkeys := begin induction l₁ generalizing l₂, case list.nil { simp only [nil_kunion, nd₂] }, case list.cons : s l₁ ih { simp at nd₁, simp [not_or_distrib, nd₁.1, nd₂, ih nd₁.2 (kerase_nodupkeys s.1 nd₂)] } end theorem perm.kunion_right {l₁ l₂ : list (sigma β)} (p : l₁ ~ l₂) (l) : kunion l₁ l ~ kunion l₂ l := begin induction p generalizing l, case list.perm.nil { refl }, case list.perm.cons : hd tl₁ tl₂ p ih { simp [ih (kerase hd.1 l), perm.cons] }, case list.perm.swap : s₁ s₂ l { simp [kerase_comm, perm.swap] }, case list.perm.trans : l₁ l₂ l₃ p₁₂ p₂₃ ih₁₂ ih₂₃ { exact perm.trans (ih₁₂ l) (ih₂₃ l) } end theorem perm.kunion_left : ∀ l {l₁ l₂ : list (sigma β)}, l₁.nodupkeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂ | [] _ _ _ p := p | (s :: l) l₁ l₂ nd₁ p := by simp [((p.kerase nd₁).kunion_left l (kerase_nodupkeys s.1 nd₁)).cons s] theorem perm.kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys) (p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ := (p₁₂.kunion_right l₃).trans (p₃₄.kunion_left l₂ nd₃) @[simp] theorem lookup_kunion_left {a} {l₁ l₂ : list (sigma β)} (h : a ∈ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₁ := begin induction l₁ with s _ ih generalizing l₂; simp at h; cases h; cases s with a', { subst h, simp }, { rw kunion_cons, by_cases h' : a = a', { subst h', simp }, { simp [h', ih h] } } end @[simp] theorem lookup_kunion_right {a} {l₁ l₂ : list (sigma β)} (h : a ∉ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : _ _ ih { simp [not_or_distrib] at h, simp [h.1, ih h.2] } end @[simp] theorem mem_lookup_kunion {a} {b : β a} {l₁ l₂ : list (sigma β)} : b ∈ lookup a (kunion l₁ l₂) ↔ b ∈ lookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s _ ih { cases s with a', by_cases h₁ : a = a', { subst h₁, simp }, { let h₂ := @ih (kerase a' l₂), simp [h₁] at h₂, simp [h₁, h₂] } } end theorem mem_lookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : list (sigma β)} (h₁ : b ∈ lookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) : b ∈ lookup a (kunion (kunion l₁ l₂) l₃) := match mem_lookup_kunion.mp h₁ with | or.inl h := mem_lookup_kunion.mpr (or.inl (mem_lookup_kunion.mpr (or.inl h))) | or.inr h := mem_lookup_kunion.mpr $ or.inr ⟨mt mem_keys_kunion.mp (not_or_distrib.mpr ⟨h.1, h₂⟩), h.2⟩ end end list
22eff7fdc3c563508c248a26f32d3b0c5245daad
c777c32c8e484e195053731103c5e52af26a25d1
/archive/imo/imo2008_q3.lean
3f8d05c99f40f9ebde794239d02a9569996929f4
[ "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
3,833
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import data.real.basic import data.real.sqrt import data.nat.prime import number_theory.primes_congruent_one import number_theory.legendre_symbol.quadratic_reciprocity import tactic.linear_combination /-! # IMO 2008 Q3 Prove that there exist infinitely many positive integers `n` such that `n^2 + 1` has a prime divisor which is greater than `2n + √(2n)`. # Solution We first prove the following lemma: for every prime `p > 20`, satisfying `p ≡ 1 [MOD 4]`, there exists `n ∈ ℕ` such that `p ∣ n^2 + 1` and `p > 2n + √(2n)`. Then the statement of the problem follows from the fact that there exist infinitely many primes `p ≡ 1 [MOD 4]`. To prove the lemma, notice that `p ≡ 1 [MOD 4]` implies `∃ n ∈ ℕ` such that `n^2 ≡ -1 [MOD p]` and we can take this `n` such that `n ≤ p/2`. Let `k = p - 2n ≥ 0`. Then we have: `k^2 + 4 = (p - 2n)^2 + 4 ≣ 4n^2 + 4 ≡ 0 [MOD p]`. Then `k^2 + 4 ≥ p` and so `k ≥ √(p - 4) > 4`. Then `p = 2n + k ≥ 2n + √(p - 4) = 2n + √(2n + k - 4) > √(2n)` and we are done. -/ open real lemma p_lemma (p : ℕ) (hpp : nat.prime p) (hp_mod_4_eq_1 : p ≡ 1 [MOD 4]) (hp_gt_20 : p > 20) : ∃ n : ℕ, p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt(2 * n) := begin haveI := fact.mk hpp, have hp_mod_4_ne_3 : p % 4 ≠ 3, { linarith [(show p % 4 = 1, by exact hp_mod_4_eq_1)] }, obtain ⟨y, hy⟩ := zmod.exists_sq_eq_neg_one_iff.mpr hp_mod_4_ne_3, let m := zmod.val_min_abs y, let n := int.nat_abs m, have hnat₁ : p ∣ n ^ 2 + 1, { refine int.coe_nat_dvd.mp _, simp only [int.nat_abs_sq, int.coe_nat_pow, int.coe_nat_succ, int.coe_nat_dvd.mp], refine (zmod.int_coe_zmod_eq_zero_iff_dvd (m ^ 2 + 1) p).mp _, simp only [int.cast_pow, int.cast_add, int.cast_one, zmod.coe_val_min_abs], rw [pow_two, ← hy], exact add_left_neg 1 }, have hnat₂ : n ≤ p / 2 := zmod.nat_abs_val_min_abs_le y, have hnat₃ : p ≥ 2 * n, { linarith [nat.div_mul_le_self p 2] }, set k : ℕ := p - 2 * n with hnat₄, have hnat₅ : p ∣ k ^ 2 + 4, { cases hnat₁ with x hx, have : (p:ℤ) ∣ k ^ 2 + 4, { use (p:ℤ) - 4 * n + 4 * x, have hcast₁ : (k:ℤ) = p - 2 * n, { assumption_mod_cast }, have hcast₂ : (n:ℤ) ^ 2 + 1 = p * x, { assumption_mod_cast }, linear_combination ((k:ℤ) + p - 2 * n)*hcast₁ + 4*hcast₂ }, assumption_mod_cast }, have hnat₆ : k ^ 2 + 4 ≥ p := nat.le_of_dvd (k ^ 2 + 3).succ_pos hnat₅, have hreal₁ : (k:ℝ) = p - 2 * n, { assumption_mod_cast }, have hreal₂ : (p:ℝ) > 20, { assumption_mod_cast }, have hreal₃ : (k:ℝ) ^ 2 + 4 ≥ p, { assumption_mod_cast }, have hreal₅ : (k:ℝ) > 4, { refine lt_of_pow_lt_pow 2 k.cast_nonneg _, linarith only [hreal₂, hreal₃] }, have hreal₆ : (k:ℝ) > sqrt (2 * n), { refine lt_of_pow_lt_pow 2 k.cast_nonneg _, rw sq_sqrt (mul_nonneg zero_le_two n.cast_nonneg), linarith only [hreal₁, hreal₃, hreal₅] }, exact ⟨n, hnat₁, by linarith only [hreal₆, hreal₁]⟩, end theorem imo2008_q3 : ∀ N : ℕ, ∃ n : ℕ, n ≥ N ∧ ∃ p : ℕ, nat.prime p ∧ p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt(2 * n) := begin intro N, obtain ⟨p, hpp, hineq₁, hpmod4⟩ := nat.exists_prime_gt_modeq_one (N ^ 2 + 20) four_ne_zero, obtain ⟨n, hnat, hreal⟩ := p_lemma p hpp hpmod4 (by linarith [hineq₁, nat.zero_le (N ^ 2)]), have hineq₂ : n ^ 2 + 1 ≥ p := nat.le_of_dvd (n ^ 2).succ_pos hnat, have hineq₃ : n * n ≥ N * N, { linarith [hineq₁, hineq₂] }, have hn_ge_N : n ≥ N := nat.mul_self_le_mul_self_iff.mpr hineq₃, exact ⟨n, hn_ge_N, p, hpp, hnat, hreal⟩, end
6917bf18a9e0f8e5e51deba0561fc21b2e7cd122
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/opposite.lean
e0a2d57bbcfe3ea8e2643c9f576895b902e40c30
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
4,011
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton, Simon Hudon, Kenny Lau Opposites. -/ import data.equiv.basic universes v u -- declare the `v` first; see `category_theory.category` for an explanation variable (α : Sort u) /-- The type of objects of the opposite of `α`; used to defined opposite category/group/... In order to avoid confusion between `α` and its opposite type, we set up the type of objects `opposite α` using the following pattern, which will be repeated later for the morphisms. 1. Define `opposite α := α`. 2. Define the isomorphisms `op : α → opposite α`, `unop : opposite α → α`. 3. Make the definition `opposite` irreducible. This has the following consequences. * `opposite α` and `α` are distinct types in the elaborator, so you must use `op` and `unop` explicitly to convert between them. * Both `unop (op X) = X` and `op (unop X) = X` are definitional equalities. Notably, every object of the opposite category is definitionally of the form `op X`, which greatly simplifies the definition of the structure of the opposite category, for example. (If Lean supported definitional eta equality for records, we could achieve the same goals using a structure with one field.) -/ def opposite : Sort u := α -- Use a high right binding power (like that of postfix ⁻¹) so that, for example, -- `presheaf Cᵒᵖ` parses as `presheaf (Cᵒᵖ)` and not `(presheaf C)ᵒᵖ`. notation α `ᵒᵖ`:std.prec.max_plus := opposite α namespace opposite variables {α} @[pp_nodot] def op : α → αᵒᵖ := id @[pp_nodot] def unop : αᵒᵖ → α := id lemma op_injective : function.injective (op : α → αᵒᵖ) := λ _ _, id lemma unop_injective : function.injective (unop : αᵒᵖ → α) := λ _ _, id @[simp] lemma op_inj_iff (x y : α) : op x = op y ↔ x = y := iff.rfl @[simp] lemma unop_inj_iff (x y : αᵒᵖ) : unop x = unop y ↔ x = y := iff.rfl @[simp] lemma op_unop (x : αᵒᵖ) : op (unop x) = x := rfl @[simp] lemma unop_op (x : α) : unop (op x) = x := rfl attribute [irreducible] opposite /-- The type-level equivalence between a type and its opposite. -/ def equiv_to_opposite : α ≃ αᵒᵖ := { to_fun := op, inv_fun := unop, left_inv := λ a, by simp, right_inv := λ a, by simp, } @[simp] lemma equiv_to_opposite_apply (a : α) : equiv_to_opposite a = op a := rfl @[simp] lemma equiv_to_opposite_symm_apply (a : αᵒᵖ) : equiv_to_opposite.symm a = unop a := rfl lemma op_eq_iff_eq_unop {x : α} {y} : op x = y ↔ x = unop y := equiv_to_opposite.apply_eq_iff_eq_symm_apply _ _ lemma unop_eq_iff_eq_op {x} {y : α} : unop x = y ↔ x = op y := equiv_to_opposite.symm.apply_eq_iff_eq_symm_apply _ _ instance [inhabited α] : inhabited αᵒᵖ := ⟨op (default _)⟩ def op_induction {F : Π (X : αᵒᵖ), Sort v} (h : Π X, F (op X)) : Π X, F X := λ X, h (unop X) end opposite namespace tactic open opposite open interactive interactive.types lean.parser tactic local postfix `?`:9001 := optional namespace op_induction meta def is_opposite (e : expr) : tactic bool := do t ← infer_type e, `(opposite _) ← whnf t | return ff, return tt meta def find_opposite_hyp : tactic name := do lc ← local_context, h :: _ ← lc.mfilter $ is_opposite | fail "No hypotheses of the form Xᵒᵖ", return h.local_pp_name end op_induction open op_induction meta def op_induction (h : option name) : tactic unit := do h ← match h with | (some h) := pure h | none := find_opposite_hyp end, h' ← tactic.get_local h, revert_lst [h'], applyc `opposite.op_induction, tactic.intro h, skip -- For use with `local attribute [tidy] op_induction` meta def op_induction' := op_induction none namespace interactive meta def op_induction (h : parse ident?) : tactic unit := tactic.op_induction h end interactive end tactic
452e96126a3fc6b00ac31f2bd57c39543d33cd43
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/lie/skew_adjoint.lean
28e780d5660ccfd5c0a6e5fa0c1b3a72a5f3883e
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,197
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`. -/ def skew_adjoint_matrices_lie_subalgebra_equiv (P : matrix n n R) (h : invertible 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 (is_unit_of_invertible P)], end lemma skew_adjoint_matrices_lie_subalgebra_equiv_apply (P : matrix n n R) (h : invertible 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 • J) ↔ A ∈ skew_adjoint_matrices_lie_subalgebra J := begin change A ∈ skew_adjoint_matrices_submodule (u • 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⁻¹ • B) h, }, { simp [h], }, end end skew_adjoint_matrices
861f6e0c3c551d22c54d6c845088a463b420fe80
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/matrix/spectrum.lean
2029a46c5de7bc2b7eb8fb7c4ae43dcad2a8fc92
[ "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
3,468
lean
/- Copyright (c) 2022 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import analysis.inner_product_space.spectrum import linear_algebra.matrix.hermitian /-! # Spectral theory of hermitian matrices This file proves the spectral theorem for matrices. The proof of the spectral theorem is based on the spectral theorem for linear maps (`diagonalization_basis_apply_self_apply`). ## Tags spectral theorem, diagonalization theorem -/ namespace matrix variables {𝕜 : Type*} [is_R_or_C 𝕜] [decidable_eq 𝕜] {n : Type*} [fintype n] [decidable_eq n] variables {A : matrix n n 𝕜} open_locale matrix namespace is_hermitian variables (hA : A.is_hermitian) /-- The eigenvalues of a hermitian matrix, indexed by `fin (fintype.card n)` where `n` is the index type of the matrix. -/ noncomputable def eigenvalues₀ : fin (fintype.card n) → ℝ := (is_hermitian_iff_is_symmetric.1 hA).eigenvalues finrank_euclidean_space /-- The eigenvalues of a hermitian matrix, reusing the index `n` of the matrix entries. -/ noncomputable def eigenvalues : n → ℝ := λ i, hA.eigenvalues₀ $ (fintype.equiv_of_card_eq (fintype.card_fin _)).symm i /-- A choice of an orthonormal basis of eigenvectors of a hermitian matrix. -/ noncomputable def eigenvector_basis : orthonormal_basis n 𝕜 (euclidean_space 𝕜 n) := ((is_hermitian_iff_is_symmetric.1 hA).eigenvector_basis finrank_euclidean_space).reindex (fintype.equiv_of_card_eq (fintype.card_fin _)) /-- A matrix whose columns are an orthonormal basis of eigenvectors of a hermitian matrix. -/ noncomputable def eigenvector_matrix : matrix n n 𝕜 := (pi.basis_fun 𝕜 n).to_matrix (eigenvector_basis hA).to_basis /-- The inverse of `eigenvector_matrix` -/ noncomputable def eigenvector_matrix_inv : matrix n n 𝕜 := (eigenvector_basis hA).to_basis.to_matrix (pi.basis_fun 𝕜 n) lemma eigenvector_matrix_mul_inv : hA.eigenvector_matrix ⬝ hA.eigenvector_matrix_inv = 1 := by apply basis.to_matrix_mul_to_matrix_flip /-- *Diagonalization theorem*, *spectral theorem* for matrices; A hermitian matrix can be diagonalized by a change of basis. For the spectral theorem on linear maps, see `diagonalization_basis_apply_self_apply`. -/ theorem spectral_theorem : hA.eigenvector_matrix_inv ⬝ A = diagonal (coe ∘ hA.eigenvalues) ⬝ hA.eigenvector_matrix_inv := begin rw [eigenvector_matrix_inv, basis_to_matrix_basis_fun_mul], ext i j, convert @linear_map.is_symmetric.diagonalization_basis_apply_self_apply 𝕜 _ _ (pi_Lp 2 (λ (_ : n), 𝕜)) _ A.to_lin' (is_hermitian_iff_is_symmetric.1 hA) _ (fintype.card n) finrank_euclidean_space (euclidean_space.single j 1) ((fintype.equiv_of_card_eq (fintype.card_fin _)).symm i), { rw [eigenvector_basis, to_lin'_apply], simp only [basis.to_matrix, basis.coe_to_orthonormal_basis_repr, basis.equiv_fun_apply], simp_rw [orthonormal_basis.coe_to_basis_repr_apply, orthonormal_basis.reindex_repr, euclidean_space.single, pi_Lp.equiv_symm_apply', mul_vec_single, mul_one], refl }, { simp only [diagonal_mul, (∘), eigenvalues, eigenvector_basis], rw [basis.to_matrix_apply, orthonormal_basis.coe_to_basis_repr_apply, orthonormal_basis.reindex_repr, pi.basis_fun_apply, eigenvalues₀, linear_map.coe_std_basis, euclidean_space.single, pi_Lp.equiv_symm_apply'] } end end is_hermitian end matrix
c4cc7a732ab43b1c2bf02b3cc747a1c9df6aedee
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/artinian.lean
1681526123d6a0625a5c23a371ee4aa0ef59992e
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
17,670
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import linear_algebra.basic import linear_algebra.prod import linear_algebra.pi import data.set_like.fintype import linear_algebra.linear_independent import tactic.linarith import algebra.algebra.basic import ring_theory.noetherian import ring_theory.jacobson_ideal import ring_theory.nilpotent import ring_theory.nakayama /-! # Artinian rings and modules A module satisfying these equivalent conditions is said to be an *Artinian* R-module if every decreasing chain of submodules is eventually constant, or equivalently, if the relation `<` on submodules is well founded. A ring is said to be left (or right) Artinian if it is Artinian as a left (or right) module over itself, or simply Artinian if it is both left and right Artinian. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `is_artinian R M` is the proposition that `M` is a Artinian `R`-module. It is a class, implemented as the predicate that the `<` relation on submodules is well founded. * `is_artinian_ring R` is the proposition that `R` is a left Artinian ring. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Artinian, artinian, Artinian ring, Artinian module, artinian ring, artinian module -/ open set open_locale big_operators pointwise /-- `is_artinian R M` is the proposition that `M` is an Artinian `R`-module, implemented as the well-foundedness of submodule inclusion. -/ class is_artinian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (well_founded_submodule_lt [] : well_founded ((<) : submodule R M → submodule R M → Prop)) section variables {R : Type*} {M : Type*} {P : Type*} {N : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] [add_comm_group N] variables [module R M] [module R P] [module R N] open is_artinian include R theorem is_artinian_of_injective (f : M →ₗ[R] P) (h : function.injective f) [is_artinian R P] : is_artinian R M := ⟨subrelation.wf (λ A B hAB, show A.map f < B.map f, from submodule.map_strict_mono_of_injective h hAB) (inv_image.wf (submodule.map f) (is_artinian.well_founded_submodule_lt R P))⟩ instance is_artinian_submodule' [is_artinian R M] (N : submodule R M) : is_artinian R N := is_artinian_of_injective N.subtype subtype.val_injective lemma is_artinian_of_le {s t : submodule R M} [ht : is_artinian R t] (h : s ≤ t) : is_artinian R s := is_artinian_of_injective (submodule.of_le h) (submodule.of_le_injective h) variable (M) theorem is_artinian_of_surjective (f : M →ₗ[R] P) (hf : function.surjective f) [is_artinian R M] : is_artinian R P := ⟨subrelation.wf (λ A B hAB, show A.comap f < B.comap f, from submodule.comap_strict_mono_of_surjective hf hAB) (inv_image.wf (submodule.comap f) (is_artinian.well_founded_submodule_lt _ _))⟩ variable {M} theorem is_artinian_of_linear_equiv (f : M ≃ₗ[R] P) [is_artinian R M] : is_artinian R P := is_artinian_of_surjective _ f.to_linear_map f.to_equiv.surjective theorem is_artinian_of_range_eq_ker [is_artinian R M] [is_artinian R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf : function.injective f) (hg : function.surjective g) (h : f.range = g.ker) : is_artinian R N := ⟨well_founded_lt_exact_sequence (is_artinian.well_founded_submodule_lt _ _) (is_artinian.well_founded_submodule_lt _ _) f.range (submodule.map f) (submodule.comap f) (submodule.comap g) (submodule.map g) (submodule.gci_map_comap hf) (submodule.gi_map_comap hg) (by simp [submodule.map_comap_eq, inf_comm]) (by simp [submodule.comap_map_eq, h])⟩ instance is_artinian_prod [is_artinian R M] [is_artinian R P] : is_artinian R (M × P) := is_artinian_of_range_eq_ker (linear_map.inl R M P) (linear_map.snd R M P) linear_map.inl_injective linear_map.snd_surjective (linear_map.range_inl R M P) @[instance, priority 100] lemma is_artinian_of_fintype [fintype M] : is_artinian R M := ⟨fintype.well_founded_of_trans_of_irrefl _⟩ local attribute [elab_as_eliminator] fintype.induction_empty_option instance is_artinian_pi {R ι : Type*} [fintype ι] : Π {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)], by exactI Π [Π i, module R (M i)], by exactI Π [∀ i, is_artinian R (M i)], is_artinian R (Π i, M i) := fintype.induction_empty_option (begin introsI α β e hα M _ _ _ _, exact is_artinian_of_linear_equiv (linear_equiv.Pi_congr_left R M e) end) (by { introsI M _ _ _ _, apply_instance }) (begin introsI α _ ih M _ _ _ _, exact is_artinian_of_linear_equiv (linear_equiv.pi_option_equiv_prod R).symm, end) ι /-- A version of `is_artinian_pi` for non-dependent functions. We need this instance because sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to prove that `ι → ℝ` is finite dimensional over `ℝ`). -/ instance is_artinian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι] [is_artinian R M] : is_artinian R (ι → M) := is_artinian_pi end open is_artinian submodule function section variables {R M : Type*} [ring R] [add_comm_group M] [module R M] theorem is_artinian_iff_well_founded : is_artinian R M ↔ well_founded ((<) : submodule R M → submodule R M → Prop) := ⟨λ h, h.1, is_artinian.mk⟩ variables {R M} lemma is_artinian.finite_of_linear_independent [nontrivial R] [is_artinian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_lt R M)).elim' _), have f : ℕ ↪ s, from set.infinite.nat_embedding s hf, have : ∀ n, (coe ∘ f) '' {m | n ≤ m} ⊆ s, { rintros n x ⟨y, hy₁, rfl⟩, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | b ≤ m}) ≤ span R ((coe ∘ f) '' {m | a ≤ m}), { assume a b, rw [span_le_span_iff hs (this b) (this a), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], simp only [set.mem_set_of_eq], exact ⟨λ hab x, le_trans hab, λ h, (h _ le_rfl)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | n ≤ m}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, begin intros a b, conv_rhs { rw [gt, lt_iff_le_not_le, this, this, ← lt_iff_le_not_le] }, simp end⟩ end /-- A module is Artinian iff every nonempty set of submodules has a minimal submodule among them. -/ theorem set_has_minimal_iff_artinian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M') ↔ is_artinian R M := by rw [is_artinian_iff_well_founded, well_founded.well_founded_iff_has_min'] theorem is_artinian.set_has_minimal [is_artinian R M] (a : set $ submodule R M) (ha : a.nonempty) : ∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M' := set_has_minimal_iff_artinian.mpr ‹_› a ha /-- A module is Artinian iff every decreasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_artinian : (∀ (f : ℕ →o (submodule R M)ᵒᵈ), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_artinian R M := by { rw is_artinian_iff_well_founded, exact well_founded.monotone_chain_condition.symm } theorem is_artinian.monotone_stabilizes [is_artinian R M] (f : ℕ →o (submodule R M)ᵒᵈ) : ∃ n, ∀ m, n ≤ m → f n = f m := monotone_stabilizes_iff_artinian.mpr ‹_› f /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_artinian.induction [is_artinian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J < I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_lt R M) I hgt /-- For any endomorphism of a Artinian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem is_artinian.exists_endomorphism_iterate_ker_sup_range_eq_top [I : is_artinian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊔ (f ^ n).range = ⊤ := begin obtain ⟨n, w⟩ := monotone_stabilizes_iff_artinian.mpr I (f.iterate_range.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w ((n + 1) + n) (by linarith), dsimp at w, refine ⟨n + 1, nat.succ_ne_zero _, _⟩, simp_rw [eq_top_iff', mem_sup], intro x, have : (f^(n + 1)) x ∈ (f ^ ((n + 1) + n + 1)).range, { rw ← w, exact mem_range_self _ }, rcases this with ⟨y, hy⟩, use x - (f ^ (n+1)) y, split, { rw [linear_map.mem_ker, linear_map.map_sub, ← hy, sub_eq_zero, pow_add], simp [iterate_add_apply], }, { use (f^ (n+1)) y, simp } end /-- Any injective endomorphism of an Artinian module is surjective. -/ theorem is_artinian.surjective_of_injective_endomorphism [is_artinian R M] (f : M →ₗ[R] M) (s : injective f) : surjective f := begin obtain ⟨n, ne, w⟩ := is_artinian.exists_endomorphism_iterate_ker_sup_range_eq_top f, rw [linear_map.ker_eq_bot.mpr (linear_map.iterate_injective s n), bot_sup_eq, linear_map.range_eq_top] at w, exact linear_map.surjective_of_iterate_surjective ne w, end /-- Any injective endomorphism of an Artinian module is bijective. -/ theorem is_artinian.bijective_of_injective_endomorphism [is_artinian R M] (f : M →ₗ[R] M) (s : injective f) : bijective f := ⟨s, is_artinian.surjective_of_injective_endomorphism f s⟩ /-- A sequence `f` of submodules of a artinian module, with the supremum `f (n+1)` and the infinum of `f 0`, ..., `f n` being ⊤, is eventually ⊤. -/ lemma is_artinian.disjoint_partial_infs_eventually_top [I : is_artinian R M] (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups (order_dual.to_dual ∘ f) n) (order_dual.to_dual (f (n+1)))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊤ := begin -- A little off-by-one cleanup first: suffices t : ∃ n : ℕ, ∀ m, n ≤ m → order_dual.to_dual f (m+1) = ⊤, { obtain ⟨n, w⟩ := t, use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes_iff_artinian.mpr I (partial_sups (order_dual.to_dual ∘ f)), exact ⟨n, λ m p, (h m).eq_bot_of_ge $ sup_eq_left.1 $ (w (m + 1) $ le_add_right p).symm.trans $ w m p⟩ end universe w variables {N : Type w} [add_comm_group N] [module R N] -- TODO: Prove this for artinian modules -- /-- -- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -- -/ -- noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] -- (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := -- begin -- apply nonempty.some, -- obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) -- (f.tailings_disjoint_tailing i), -- specialize w n (le_refl n), -- apply nonempty.intro, -- refine (f.tailing_linear_equiv i n).symm.trans _, -- rw w, -- exact submodule.bot_equiv_punit, -- end end /-- A ring is Artinian if it is Artinian as a module over itself. Strictly speaking, this should be called `is_left_artinian_ring` but we omit the `left_` for convenience in the commutative case. For a right Artinian ring, use `is_artinian Rᵐᵒᵖ R`. -/ class is_artinian_ring (R) [ring R] extends is_artinian R R : Prop theorem is_artinian_ring_iff {R} [ring R] : is_artinian_ring R ↔ is_artinian R R := ⟨λ h, h.1, @is_artinian_ring.mk _ _⟩ theorem ring.is_artinian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_artinian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); split; apply_instance theorem is_artinian_of_submodule_of_artinian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_artinian R M) : is_artinian R N := by apply_instance theorem is_artinian_of_quotient_of_artinian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_artinian R M) : is_artinian R (M ⧸ N) := is_artinian_of_surjective M (submodule.mkq N) (submodule.quotient.mk_surjective N) /-- If `M / S / R` is a scalar tower, and `M / R` is Artinian, then `M / S` is also Artinian. -/ theorem is_artinian_of_tower (R) {S M} [comm_ring R] [ring S] [add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M] (h : is_artinian R M) : is_artinian S M := begin rw is_artinian_iff_well_founded at h ⊢, refine (submodule.restrict_scalars_embedding R S M).well_founded h end theorem is_artinian_of_fg_of_artinian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_artinian_ring R] (hN : N.fg) : is_artinian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_artinian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_artinian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_artinian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_artinian_of_fg_of_artinian' {R M} [ring R] [add_comm_group M] [module R M] [is_artinian_ring R] (h : (⊤ : submodule R M).fg) : is_artinian R M := have is_artinian R (⊤ : submodule R M), from is_artinian_of_fg_of_artinian _ h, by exactI is_artinian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a artinian ring, the submodule generated by finitely many vectors is artinian. -/ theorem is_artinian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_artinian_ring R] {A : set M} (hA : A.finite) : is_artinian R (submodule.span R A) := is_artinian_of_fg_of_artinian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_artinian_ring_of_surjective (R) [ring R] (S) [ring S] (f : R →+* S) (hf : function.surjective f) [H : is_artinian_ring R] : is_artinian_ring S := begin rw [is_artinian_ring_iff, is_artinian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf) H, end instance is_artinian_ring_range {R} [ring R] {S} [ring S] (f : R →+* S) [is_artinian_ring R] : is_artinian_ring f.range := is_artinian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_artinian_ring_of_ring_equiv (R) [ring R] {S} [ring S] (f : R ≃+* S) [is_artinian_ring R] : is_artinian_ring S := is_artinian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_artinian_ring open is_artinian variables {R : Type*} [comm_ring R] [is_artinian_ring R] lemma is_nilpotent_jacobson_bot : is_nilpotent (ideal.jacobson (⊥ : ideal R)) := begin let Jac := ideal.jacobson (⊥ : ideal R), let f : ℕ →o (ideal R)ᵒᵈ := ⟨λ n, Jac ^ n, λ _ _ h, ideal.pow_le_pow h⟩, obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → Jac ^ n = Jac ^ m := is_artinian.monotone_stabilizes f, refine ⟨n, _⟩, let J : ideal R := annihilator (Jac ^ n), suffices : J = ⊤, { have hJ : J • Jac ^ n = ⊥ := annihilator_smul (Jac ^ n), simpa only [this, top_smul, ideal.zero_eq_bot] using hJ }, by_contradiction hJ, change J ≠ ⊤ at hJ, rcases is_artinian.set_has_minimal {J' : ideal R | J < J'} ⟨⊤, hJ.lt_top⟩ with ⟨J', hJJ' : J < J', hJ' : ∀ I, J < I → I ≤ J' → I = J'⟩, rcases set_like.exists_of_lt hJJ' with ⟨x, hxJ', hxJ⟩, obtain rfl : J ⊔ ideal.span {x} = J', { refine hJ' (J ⊔ ideal.span {x}) _ _, { rw set_like.lt_iff_le_and_exists, exact ⟨le_sup_left, ⟨x, mem_sup_right (mem_span_singleton_self x), hxJ⟩⟩ }, { exact (sup_le hJJ'.le (span_le.2 (singleton_subset_iff.2 hxJ'))) } }, have : J ⊔ Jac • ideal.span {x} ≤ J ⊔ ideal.span {x}, from sup_le_sup_left (smul_le.2 (λ _ _ _, submodule.smul_mem _ _)) _, have : Jac * ideal.span {x} ≤ J, --Need version 4 of Nakayamas lemma on Stacks { classical, by_contradiction H, refine H (smul_sup_le_of_le_smul_of_le_jacobson_bot (fg_span_singleton _) le_rfl (hJ' _ _ this).ge), exact lt_of_le_of_ne le_sup_left (λ h, H $ h.symm ▸ le_sup_right) }, have : ideal.span {x} * Jac ^ (n + 1) ≤ ⊥, calc ideal.span {x} * Jac ^ (n + 1) = ideal.span {x} * Jac * Jac ^ n : by rw [pow_succ, ← mul_assoc] ... ≤ J * Jac ^ n : mul_le_mul (by rwa mul_comm) le_rfl ... = ⊥ : by simp [J], refine hxJ (mem_annihilator.2 (λ y hy, (mem_bot R).1 _)), refine this (mul_mem_mul (mem_span_singleton_self x) _), rwa [← hn (n + 1) (nat.le_succ _)] end end is_artinian_ring
9ba30daa54f4a354bc3cdd8683431002f7ad4d44
367134ba5a65885e863bdc4507601606690974c1
/src/testing/slim_check/sampleable.lean
82871d0b21455d25d4f5b15da22c95f0d2858dc5
[ "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
31,388
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import data.lazy_list.basic import data.tree import data.int.basic import control.bifunctor import tactic.linarith import testing.slim_check.gen /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v w namespace slim_check variables (α : Type u) local infix ` ≺ `:50 := has_well_founded.r /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ @[reducible] def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x } /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable := [wf : has_sizeof α] (sample [] : gen α) (shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil) attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof attribute [instance, priority 200] sampleable.wf /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [functor F] := [wf : Π α [has_sizeof α], has_sizeof (F α)] (sample [] : ∀ {α}, gen α → gen (F α)) (shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α)) (p_repr : ∀ α, has_repr α → has_repr (F α)) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] := [wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)] (sample [] : ∀ {α β}, gen α → gen β → gen (F α β)) (shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β)) (p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β)) export sampleable (sample shrink) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ meta def sampleable.mk_trivial_interp : tactic unit := tactic.refine ``(id) /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) := (proxy_repr : Type v) [wf : has_sizeof proxy_repr] (interp [] : proxy_repr → α . sampleable.mk_trivial_interp) [p_repr : has_repr proxy_repr] (sample [] : gen proxy_repr) (shrink : shrink_fn proxy_repr) attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf open nat lazy_list section prio open sampleable_ext set_option default_priority 50 instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α := { proxy_repr := α, sample := sampleable.sample α, shrink := shrink } instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := { wf := _, sample := sampleable_functor.sample F (sampleable.sample α), shrink := sampleable_functor.shrink α sampleable.shrink } instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := { wf := _, sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β), shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink } set_option default_priority 100 instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := { wf := _, proxy_repr := F (proxy_repr α), interp := functor.map (interp _), sample := sampleable_functor.sample F (sampleable_ext.sample α), shrink := sampleable_functor.shrink _ sampleable_ext.shrink, p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr } instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := { wf := _, proxy_repr := F (proxy_repr α) (proxy_repr β), interp := bifunctor.bimap (interp _) (interp _), sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β), shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink, p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr } end prio /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k → list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k } | n hn ls := if h : n ≤ 1 then ls.reverse else have h₂ : 0 < n, by linarith, have 1 * n / 2 < n, from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂), have n / 2 < n, by simpa, let m := n / 2 in have h₀ : m ≤ k, from le_trans (le_of_lt this) hn, have h₃ : 0 < m, by simp only [m, lt_iff_add_one_le, zero_add]; rw [le_div_iff_mul_le]; linarith, have h₁ : k - m < k, from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃, nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls) /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } := if h : n > 0 then have ∀ k, 1 < k → n / k < n, from λ k hk, nat.div_lt_of_lt_mul (suffices 1 * n < k * n, by simpa, nat.mul_lt_mul_of_pos_right hk h), ⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n (le_refl _) [] else [] open gen /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := { wf := ⟨ sizeof ∘ g ⟩, sample := f <$> sample α, shrink := λ x, have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x), by introv h'; solve_by_elim [lt_of_le_of_lt], subtype.map f this <$> shrink (g x) } instance nat.sampleable : sampleable ℕ := { sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))), (3, coe <$> choose_any (fin $ succ sz))] dec_trivial, shrink := λ x, lazy_list.of_list $ nat.shrink x } /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → option α := well_founded.fix has_well_founded.wf $ λ x f_rec, do trace sformat!"{x} : {(shrink x).to_list}" $ pure (), y ← (shrink x).find (λ a, p a), f_rec y y.property <|> some y.val . instance fin.sampleable {n} [fact $ 0 < n] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' subtype.val $ λ i, (mod_le _ _ : i % n ≤ i) @[priority 100] instance fin.sampleable' {n} : sampleable (fin (succ n)) := sampleable.lift ℕ fin.of_nat subtype.val $ λ i, (mod_le _ _ : i % succ n ≤ i) instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a, by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, nat.sub_zero, succ_sub_succ_eq_sub] /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩ local attribute [instance, priority 2000] int.has_sizeof instance int.sampleable : sampleable ℤ := { wf := _, sample := sized $ λ sz, freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)), (3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))] dec_trivial, shrink := λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $ λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] } instance bool.sampleable : sampleable bool := { wf := ⟨ λ b, if b then 1 else 0 ⟩, sample := do { x ← choose_any bool, return x }, shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩ else lazy_list.nil } /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α β} [has_sizeof α] [has_sizeof β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) | ⟨x₀,x₁⟩ := let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_a x₀).map $ subtype.map (λ a, (a, x₁)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h), xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_b x₁).map $ subtype.map (λ a, (x₀, a)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in xs₀.append xs₁ instance prod.sampleable : sampleable_bifunctor.{u v} prod := { wf := _, sample := λ α β sama samb, do { ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)), ⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)), pure (x,y) }, shrink := @prod.shrink, p_repr := @prod.has_repr } instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) := sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_refl _ /-- shrinking function for sum types -/ def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) | (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim | (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim instance sum.sampleable : sampleable_bifunctor.{u v} sum := { wf := _, sample := λ (α : Type u) (β : Type v) sam_α sam_β, (@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|> @uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β), shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β, p_repr := @sum.has_repr } instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $ begin intro i, rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf; dsimp [rat.mk_pnat], mono*, { rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs], apply int.abs_div_le_abs }, { change _ - 1 ≤ y-1, apply nat.sub_le_sub_right, apply nat.div_le_of_le_mul, suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa }, apply nat.mul_le_mul_right, apply gcd_pos_of_pos_right _ hy } end /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : nat) (characters : string) : sampleable char := { sample := do { x ← choose_nat 0 length dec_trivial, if x.val = 0 then do n ← sample ℕ, pure $ char.of_nat n else do i ← choose_nat 0 (characters.length - 1) dec_trivial, pure (characters.mk_iterator.nextn i).curr }, shrink := λ _, lazy_list.nil } instance char.sampleable : sampleable char := sampleable_char 3 " 0123abcABC:,;`\\/" variables {α} section list_shrink variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x }) lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k} (hk : 0 < k) (hk' : k < xs.length) : sizeof (list.drop k xs) < sizeof xs := begin induction xs with x xs generalizing k, { cases hk' }, cases k, { cases hk }, have : sizeof xs < sizeof (x :: xs), { unfold_wf, linarith }, cases k, { simp only [this, list.drop] }, { simp only [list.drop], transitivity, { solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] }, { assumption } } end lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := by unfold_wf; assumption lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := by unfold_wf; assumption lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := begin induction xs, { apply h }, { unfold_wf, simp only [list.sizeof, add_lt_add_iff_left], exact xs_ih } end lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs := by cases xs; unfold_wf; [refl, linarith] /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n, n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs } | xs n hn := if hkn : k > n then lazy_list.nil else if hkn' : k = n then have 1 < xs.sizeof, by { subst_vars, cases xs, { contradiction }, unfold_wf, apply lt_of_lt_of_le, show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith }, { mono, apply list.one_le_sizeof, } }, lazy_list.singleton ⟨[], this ⟩ else have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn', match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with | ⟨xs₁,xs₂⟩, h := have h₄ : xs₁ = xs.take k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have h₃ : xs₂ = xs.drop k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have sizeof xs₂ < sizeof xs, by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length], have h₁ : n - k = xs₂.length, by simp only [h₃, ←hn, list.length_drop], have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs, by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄]; solve_by_elim [list.sizeof_append_lt_left], lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁ end /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one : shrink_fn (list α) | [] := lazy_list.nil | (x :: xs) := lazy_list.append (subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x) (subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs) /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with (xs : list α) : lazy_list { ys : list α // sizeof_lt ys xs } := let n := xs.length in lazy_list.append ((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k, if hk : 0 < k then list.shrink_removes k hk xs n rfl else lazy_list.nil )) (list.shrink_one shr _) end list_shrink instance list.sampleable : sampleable_functor list.{u} := { wf := _, sample := λ α sam_α, list_of sam_α, shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α, p_repr := @list.has_repr } instance prop.sampleable_ext : sampleable_ext Prop := { proxy_repr := bool, interp := coe, sample := choose_any bool, shrink := λ _, lazy_list.nil } /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type*) := α instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) := ⟨ (default α : α) ⟩ /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α} (x : no_shrink α) : α := x instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) := { sample := no_shrink.mk <$> sample α } instance string.sampleable : sampleable string := { sample := do { x ← list_of (sample char), pure x.as_string }, .. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_refl _ } /-- implementation of `sampleable (tree α)` -/ def tree.sample (sample : gen α) : ℕ → gen (tree α) | n := if h : n > 0 then have n / 2 < n, from div_lt_self h (by norm_num), tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2) else pure tree.nil /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type*} [has_sizeof α] (t : α) (sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) : shrink_fn { t' : α // sizeof_lt t' t } | ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' }, ⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht' lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t := by cases t; unfold_wf; linarith instance : functor tree := { map := @tree.map } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) : shrink_fn α := well_founded.fix (sizeof_measure_wf _) $ λ t f_rec, lazy_list.join (lazy_list.of_list $ shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _) lemma rec_shrink_with_eq [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) := begin conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], }, congr, ext ⟨y, h⟩, refl end /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with $ λ t, match t with | tree.nil := λ f_rec, [] | (tree.node x t₀ t₁) := λ f_rec, have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁), by clear _match; have := tree.one_le_sizeof t₀; dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *; unfold_wf; linarith, have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, [lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩], (prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map $ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁, by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩] end instance sampleable_tree : sampleable_functor tree := { wf := _, sample := λ α sam_α, sized $ tree.sample sam_α, shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α, p_repr := @tree.has_repr } /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type*) := α /-- Add the `small` type tag -/ def small.mk {α} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type*) := α /-- Add the `large` type tag -/ def large.mk {α} (x : α) : large α := x instance small.functor : functor small := id.monad.to_functor instance large.functor : functor large := id.monad.to_functor instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default α : α) ⟩ instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default α : α) ⟩ instance small.sampleable_functor : sampleable_functor small := { wf := _, sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance large.sampleable_functor : sampleable_functor large := { wf := _, sample := λ α samp, gen.resize (λ n, n * 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance ulift.sampleable_functor : sampleable_functor ulift.{u v} := { wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩, sample := λ α samp, uliftable.up_map ulift.up $ samp, shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)), p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ } /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } := { sample := do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial, pure ⟨x, h.2⟩}, shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $ λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x } instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y, by norm_num⟩ }, shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) }, subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, nat.add_lt_of_lt_sub_left h'⟩) <$> shrink (y - x) } /- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` -/ instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y+1, by linarith⟩ }, shrink := λ x, shrink _ } /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { x : α // x ≤ y } := { sample := do { x ← sample α, pure ⟨y - abs x, sub_le_self _ (abs_nonneg _) ⟩ }, shrink := λ _, lazy_list.nil } instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { y : α // x ≤ y } := { sample := do { y ← sample α, pure ⟨x + abs y, by norm_num [abs_nonneg]⟩ }, shrink := λ _, lazy_list.nil } /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs) (λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring) instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs) (λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring) instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $ by linarith [int.coe_nat_nonneg n]⟩) (λ ⟨i, h⟩, (y - i - 1).nat_abs) (λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring) instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs) (λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring) /-! ### Subtypes of any `list` -/ instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } := { sample := permutation_of xs, shrink := λ _, lazy_list.nil } instance perm'.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm ys xs } := { sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs, shrink := λ _, lazy_list.nil } setup_tactic_parser open tactic /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do xs ← io.run_rand $ uliftable.down $ do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up, pure ⟨xs.map repr⟩ }, xs.mmap' io.put_str_ln /-- Create a `gen α` expression from the argument of `#sample` -/ meta def mk_generator (e : expr) : tactic (expr × expr) := do t ← infer_type e, match t with | `(gen %%t) := do repr_inst ← mk_app ``has_repr [t] >>= mk_instance, pure (repr_inst, e) | _ := do samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance, repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst], gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst], pure (repr_inst, gen) end /-- `#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random values of type `my_type` of using an increasing size parameter. ```lean #sample nat -- prints -- 0 -- 0 -- 2 -- 24 -- 64 -- 76 -- 5 -- 132 -- 8 -- 449 -- or some other sequence of numbers #sample list int -- prints -- [] -- [1, 1] -- [-7, 9, -6] -- [36] -- [-500, 105, 260] -- [-290] -- [17, 156] -- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968] -- [-643] -- [11892, 16329, -15095, -15461] -- or whatever ``` -/ @[user_command] meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit := do e ← texpr, of_tactic $ do e ← i_to_expr e, (repr_inst, gen) ← mk_generator e, print_samples ← mk_mapp ``print_samples [none, repr_inst, gen], sample ← eval_expr (io unit) print_samples, unsafe_run_io sample end slim_check
9eda0b3bfe81aa119e6a6b4ae3a20791d46fc4ac
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/matrix/determinant.lean
fd0e426dc7da5b1aeefeef808f1b3d86750efe4e
[ "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
31,771
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Tim Baanen -/ import data.matrix.pequiv import data.matrix.block import data.matrix.notation import data.fintype.card import group_theory.perm.fin import group_theory.perm.sign import algebra.algebra.basic import tactic.ring import linear_algebra.alternating import linear_algebra.pi /-! # Determinant of a matrix This file defines the determinant of a matrix, `matrix.det`, and its essential properties. ## Main definitions - `matrix.det`: the determinant of a square matrix, as a sum over permutations - `matrix.det_row_alternating`: the determinant, as an `alternating_map` in the rows of the matrix ## Main results - `det_mul`: the determinant of `A ⬝ B` is the product of determinants - `det_zero_of_row_eq`: the determinant is zero if there is a repeated row - `det_block_diagonal`: the determinant of a block diagonal matrix is a product of the blocks' determinants ## Implementation notes It is possible to configure `simp` to compute determinants. See the file `test/matrix.lean` for some examples. -/ universes u v w z open equiv equiv.perm finset function namespace matrix open_locale matrix big_operators variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) /-- `det` is an `alternating_map` in the rows of the matrix. -/ def det_row_alternating : alternating_map R (n → R) R n := ((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization /-- The determinant of a matrix given by the Leibniz formula. -/ abbreviation det (M : matrix n n R) : R := det_row_alternating M lemma det_apply (M : matrix n n R) : M.det = ∑ σ : perm n, σ.sign • ∏ i, M (σ i) i := multilinear_map.alternatization_apply _ M -- This is what the old definition was. We use it to avoid having to change the old proofs below lemma det_apply' (M : matrix n n R) : M.det = ∑ σ : perm n, ε σ * ∏ i, M (σ i) i := by simp [det_apply, units.smul_def] @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i := begin rw det_apply', refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt equiv.ext h2) with x h3, convert mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := (det_row_alternating : alternating_map R (n → R) R n).map_zero @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] lemma det_is_empty [is_empty n] {A : matrix n n R} : det A = 1 := by simp [det_apply] @[simp] lemma coe_det_is_empty [is_empty n] : (det : matrix n n R → R) = function.const _ 1 := by { ext, exact det_is_empty, } lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := begin haveI : is_empty n := fintype.card_eq_zero_iff.mp h, exact det_is_empty, end /-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element. Although `unique` implies `decidable_eq` and `fintype`, the instances might not be syntactically equal. Thus, we need to fill in the args explicitly. -/ @[simp] lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) : det A = A default default := by simp [det_apply, univ_unique] lemma det_eq_elem_of_subsingleton [subsingleton n] (A : matrix n n R) (k : n) : det A = A k k := begin convert det_unique _, exact unique_of_subsingleton k end lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) : det A = A k k := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, exact det_eq_elem_of_subsingleton _ _ end lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : ∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 := begin obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j, { rw [← finite.injective_iff_bijective, injective] at H, push_neg at H, exact H }, exact sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x), from fintype.prod_equiv (swap i j) _ _ (by simp [apply_swap_eq_self hpij]), by simp [this, sign_swap hij, prod_mul_distrib]) (λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij) (λ _ _, mem_univ _) (λ σ _, mul_swap_involutive i j σ) end @[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N := calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum, fintype.pi_finset_univ]; rw [finset.sum_comm] ... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : eq.symm $ sum_subset (filter_subset _ _) (λ f _ hbij, det_mul_aux $ by simpa only [true_and, mem_filter, mem_univ] using hbij) ... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) : sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩) ... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) : by simp only [mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) : sum_congr rfl (λ σ _, fintype.sum_equiv (equiv.mul_right σ⁻¹) _ _ (λ τ, have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j, by { rw ← (σ⁻¹ : _ ≃ _).prod_comp, simp only [equiv.perm.coe_mul, apply_inv_self] }, have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by { rw [mul_comm, sign_mul (τ * σ⁻¹)], simp only [int.cast_mul, units.coe_mul] } ... = ε τ : by simp only [inv_mul_cancel_right], by { simp_rw [equiv.coe_mul_right, h], simp only [this] })) ... = det M * det N : by simp only [det_apply', finset.mul_sum, mul_comm, mul_left_comm] /-- The determinant of a matrix, as a monoid homomorphism. -/ def det_monoid_hom : matrix n n R →* R := { to_fun := det, map_one' := det_one, map_mul' := det_mul } @[simp] lemma coe_det_monoid_hom : (det_monoid_hom : matrix n n R → R) = det := rfl /-- On square matrices, `mul_comm` applies under `det`. -/ lemma det_mul_comm (M N : matrix m m R) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- On square matrices, `mul_left_comm` applies under `det`. -/ lemma det_mul_left_comm (M N P : matrix m m R) : det (M ⬝ (N ⬝ P)) = det (N ⬝ (M ⬝ P)) := by rw [←matrix.mul_assoc, ←matrix.mul_assoc, det_mul, det_mul_comm M N, ←det_mul] /-- On square matrices, `mul_right_comm` applies under `det`. -/ lemma det_mul_right_comm (M N P : matrix m m R) : det (M ⬝ N ⬝ P) = det (M ⬝ P ⬝ N) := by rw [matrix.mul_assoc, matrix.mul_assoc, det_mul, det_mul_comm N P, ←det_mul] lemma det_units_conj (M : (matrix m m R)ˣ) (N : matrix m m R) : det (↑M ⬝ N ⬝ ↑M⁻¹ : matrix m m R) = det N := by rw [det_mul_right_comm, ←mul_eq_mul, ←mul_eq_mul, units.mul_inv, one_mul] lemma det_units_conj' (M : (matrix m m R)ˣ) (N : matrix m m R) : det (↑M⁻¹ ⬝ N ⬝ ↑M : matrix m m R) = det N := det_units_conj M⁻¹ N /-- Transposing a matrix preserves the determinant. -/ @[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det := begin rw [det_apply', det_apply'], refine fintype.sum_bijective _ inv_involutive.bijective _ _ _, intros σ, rw sign_inv, congr' 1, apply fintype.prod_equiv σ, intros, simp end /-- Permuting the columns changes the sign of the determinant. -/ lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det := ((det_row_alternating : alternating_map R (n → R) R n).map_perm M σ).trans (by simp [units.smul_def]) /-- Permuting rows and columns with the same equivalence has no effect. -/ @[simp] lemma det_submatrix_equiv_self (e : n ≃ m) (A : matrix m m R) : det (A.submatrix e e) = det A := begin rw [det_apply', det_apply'], apply fintype.sum_equiv (equiv.perm_congr e), intro σ, rw equiv.perm.sign_perm_congr e σ, congr' 1, apply fintype.prod_equiv e, intro i, rw [equiv.perm_congr_apply, equiv.symm_apply_apply, submatrix_apply], end /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_submatrix_equiv_self`; this one is unsuitable because `matrix.reindex_apply` unfolds `reindex` first. -/ lemma det_reindex_self (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A := det_submatrix_equiv_self e.symm A /-- The determinant of a permutation matrix equals its sign. -/ @[simp] lemma det_permutation (σ : perm n) : matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign := by rw [←matrix.mul_one (σ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix, det_permute, det_one, mul_one] lemma det_smul (A : matrix n n R) (c : R) : det (c • A) = c ^ fintype.card n * det A := calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul] ... = det (diagonal (λ _, c)) * det A : det_mul _ _ ... = c ^ fintype.card n * det A : by simp [card_univ] @[simp] lemma det_smul_of_tower {α} [monoid α] [distrib_mul_action α R] [is_scalar_tower α R R] [smul_comm_class α R R] (c : α) (A : matrix n n R) : det (c • A) = c ^ fintype.card n • det A := by rw [←smul_one_smul R c A, det_smul, smul_pow, one_pow, smul_mul_assoc, one_mul] lemma det_neg (A : matrix n n R) : det (-A) = (-1) ^ fintype.card n * det A := by rw [←det_smul, neg_one_smul] /-- A variant of `matrix.det_neg` with scalar multiplication by `units ℤ` instead of multiplication by `R`. -/ lemma det_neg_eq_smul (A : matrix n n R) : det (-A) = (-1 : units ℤ) ^ fintype.card n • det A := by rw [←det_smul_of_tower, units.neg_smul, one_smul] /-- Multiplying each row by a fixed `v i` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_row (v : n → R) (A : matrix n n R) : det (of $ λ i j, v j * A i j) = (∏ i, v i) * det A := calc det (of $ λ i j, v j * A i j) = det (A ⬝ diagonal v) : congr_arg det $ by { ext, simp [mul_comm] } ... = (∏ i, v i) * det A : by rw [det_mul, det_diagonal, mul_comm] /-- Multiplying each column by a fixed `v j` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_column (v : n → R) (A : matrix n n R) : det (of $ λ i j, v i * A i j) = (∏ i, v i) * det A := multilinear_map.map_smul_univ _ v A @[simp] lemma det_pow (M : matrix m m R) (n : ℕ) : det (M ^ n) = (det M) ^ n := (det_monoid_hom : matrix m m R →* R).map_pow M n section hom_map variables {S : Type w} [comm_ring S] lemma _root_.ring_hom.map_det (f : R →+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := by simp [matrix.det_apply', f.map_sum, f.map_prod] lemma _root_.ring_equiv.map_det (f : R ≃+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S →ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det (f.map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_equiv.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S ≃ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det (f.map_matrix M) := f.to_alg_hom.map_det _ end hom_map @[simp] lemma det_conj_transpose [star_ring R] (M : matrix m m R) : det (Mᴴ) = star (det M) := ((star_ring_end R).map_det _).symm.trans $ congr_arg star M.det_transpose section det_zero /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 := (det_row_alternating : alternating_map R (n → R) R n).map_coord_zero i (funext h) lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 := by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, } variables {M : matrix n n R} {i j : n} /-- If a matrix has a repeated row, the determinant will be zero. -/ theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 := (det_row_alternating : alternating_map R (n → R) R n).map_eq_zero_of_eq M hij i_ne_j /-- If a matrix has a repeated column, the determinant will be zero. -/ theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : ∀ k, M k i = M k j) : M.det = 0 := by { rw [← det_transpose, det_zero_of_row_eq i_ne_j], exact funext hij } end det_zero lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) := (det_row_alternating : alternating_map R (n → R) R n).map_add M j u v lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_add], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row M j $ s • u) = s * det (update_row M j u) := (det_row_alternating : alternating_map R (n → R) R n).map_smul M j s u lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column M j $ s • u) = s * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_smul], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row (s • M) j u) = s ^ (fintype.card n - 1) * det (update_row M j u) := multilinear_map.map_update_smul _ M j s u lemma det_update_column_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column (s • M) j u) = s ^ (fintype.card n - 1) * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, transpose_smul, det_update_row_smul'], simp [update_row_transpose, det_transpose] end section det_eq /-! ### `det_eq` section Lemmas showing the determinant is invariant under a variety of operations. -/ lemma det_eq_of_eq_mul_det_one {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = B ⬝ C) : det A = det B := calc det A = det (B ⬝ C) : congr_arg _ hA ... = det B * det C : det_mul _ _ ... = det B : by rw [hC, mul_one] lemma det_eq_of_eq_det_one_mul {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = C ⬝ B) : det A = det B := calc det A = det (C ⬝ B) : congr_arg _ hA ... = det C * det B : det_mul _ _ ... = det B : by rw [hC, one_mul] lemma det_update_row_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) : det (update_row A i (A i + A j)) = det A := by simp [det_update_row_add, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) : det (update_column A i (λ k, A k i + A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_self Aᵀ hij } lemma det_update_row_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) : det (update_row A i (A i + c • A j)) = det A := by simp [det_update_row_add, det_update_row_smul, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) : det (update_column A i (λ k, A k i + c • A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_smul_self Aᵀ hij c } lemma det_eq_of_forall_row_eq_smul_add_const_aux {A B : matrix n n R} {s : finset n} : ∀ (c : n → R) (hs : ∀ i, i ∉ s → c i = 0) (k : n) (hk : k ∉ s) (A_eq : ∀ i j, A i j = B i j + c i * B k j), det A = det B := begin revert B, refine s.induction_on _ _, { intros A c hs k hk A_eq, have : ∀ i, c i = 0, { intros i, specialize hs i, contrapose! hs, simp [hs] }, congr, ext i j, rw [A_eq, this, zero_mul, add_zero], }, { intros i s hi ih B c hs k hk A_eq, have hAi : A i = B i + c i • B k := funext (A_eq i), rw [@ih (update_row B i (A i)) (function.update c i 0), hAi, det_update_row_add_smul_self], { exact mt (λ h, show k ∈ insert i s, from h ▸ finset.mem_insert_self _ _) hk }, { intros i' hi', rw function.update_apply, split_ifs with hi'i, { refl }, { exact hs i' (λ h, hi' ((finset.mem_insert.mp h).resolve_left hi'i)) } }, { exact λ h, hk (finset.mem_insert_of_mem h) }, { intros i' j', rw [update_row_apply, function.update_apply], split_ifs with hi'i, { simp [hi'i] }, rw [A_eq, update_row_ne (λ (h : k = i), hk $ h ▸ finset.mem_insert_self k s)] } } end /-- If you add multiples of row `B k` to other rows, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_const {A B : matrix n n R} (c : n → R) (k : n) (hk : c k = 0) (A_eq : ∀ i j, A i j = B i j + c i * B k j) : det A = det B := det_eq_of_forall_row_eq_smul_add_const_aux c (λ i, not_imp_comm.mp $ λ hi, finset.mem_erase.mpr ⟨mt (λ (h : i = k), show c i = 0, from h.symm ▸ hk) hi, finset.mem_univ i⟩) k (finset.not_mem_erase k finset.univ) A_eq lemma det_eq_of_forall_row_eq_smul_add_pred_aux {n : ℕ} (k : fin (n + 1)) : ∀ (c : fin n → R) (hc : ∀ (i : fin n), k < i.succ → c i = 0) {M N : matrix (fin n.succ) (fin n.succ) R} (h0 : ∀ j, M 0 j = N 0 j) (hsucc : ∀ (i : fin n) j, M i.succ j = N i.succ j + c i * M i.cast_succ j), det M = det N := begin refine fin.induction _ (λ k ih, _) k; intros c hc M N h0 hsucc, { congr, ext i j, refine fin.cases (h0 j) (λ i, _) i, rw [hsucc, hc i (fin.succ_pos _), zero_mul, add_zero] }, set M' := update_row M k.succ (N k.succ) with hM', have hM : M = update_row M' k.succ (M' k.succ + c k • M k.cast_succ), { ext i j, by_cases hi : i = k.succ, { simp [hi, hM', hsucc, update_row_self] }, rw [update_row_ne hi, hM', update_row_ne hi] }, have k_ne_succ : k.cast_succ ≠ k.succ := (fin.cast_succ_lt_succ k).ne, have M_k : M k.cast_succ = M' k.cast_succ := (update_row_ne k_ne_succ).symm, rw [hM, M_k, det_update_row_add_smul_self M' k_ne_succ.symm, ih (function.update c k 0)], { intros i hi, rw [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff] at hi, rw function.update_apply, split_ifs with hik, { refl }, exact hc _ (fin.succ_lt_succ_iff.mpr (lt_of_le_of_ne hi (ne.symm hik))) }, { rwa [hM', update_row_ne (fin.succ_ne_zero _).symm] }, intros i j, rw function.update_apply, split_ifs with hik, { rw [zero_mul, add_zero, hM', hik, update_row_self] }, rw [hM', update_row_ne ((fin.succ_injective _).ne hik), hsucc], by_cases hik2 : k < i, { simp [hc i (fin.succ_lt_succ_iff.mpr hik2)] }, rw update_row_ne, apply ne_of_lt, rwa [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff, ← not_lt] end /-- If you add multiples of previous rows to the next row, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_pred {n : ℕ} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R) (A_zero : ∀ j, A 0 j = B 0 j) (A_succ : ∀ (i : fin n) j, A i.succ j = B i.succ j + c i * A i.cast_succ j) : det A = det B := det_eq_of_forall_row_eq_smul_add_pred_aux (fin.last _) c (λ i hi, absurd hi (not_lt_of_ge (fin.le_last _))) A_zero A_succ /-- If you add multiples of previous columns to the next columns, the determinant doesn't change. -/ lemma det_eq_of_forall_col_eq_smul_add_pred {n : ℕ} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R) (A_zero : ∀ i, A i 0 = B i 0) (A_succ : ∀ i (j : fin n), A i j.succ = B i j.succ + c j * A i j.cast_succ) : det A = det B := by { rw [← det_transpose A, ← det_transpose B], exact det_eq_of_forall_row_eq_smul_add_pred c A_zero (λ i j, A_succ j i) } end det_eq @[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) : (block_diagonal M).det = ∏ k, (M k).det := begin -- Rewrite the determinants as a sum over permutations. simp_rw [det_apply'], -- The right hand side is a product of sums, rewrite it as a sum of products. rw finset.prod_sum, simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ], -- We claim that the only permutations contributing to the sum are those that -- preserve their second component. let preserving_snd : finset (equiv.perm (n × o)) := finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd), have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)}, σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd := λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩, rw ← finset.sum_subset (finset.subset_univ preserving_snd) _, -- And that these are in bijection with `o → equiv.perm m`. rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _, prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm, { intros σ _, rw mem_preserving_snd, rintros ⟨k, x⟩, simp only [prod_congr_left_apply] }, { intros σ _, rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product_right], simp only [sign_prod_congr_left, units.coe_prod, int.cast_prod, block_diagonal_apply_eq, prod_congr_left_apply] }, { intros σ σ' _ _ eq, ext x hx k, simp only at eq, have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) = prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) := λ k x, by rw eq, simp only [prod_congr_left_apply, prod.mk.inj_iff] at this, exact (this k x).1 }, { intros σ hσ, rw mem_preserving_snd at hσ, have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd, { intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } }, have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k), { intros k x, ext, { simp only}, { simp only [hσ] } }, have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k), { intros k x, conv_lhs { rw ← perm.apply_inv_self σ (x, k) }, ext, { simp only [apply_inv_self] }, { simp only [hσ'] } }, refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩, { intro x, simp only [mk_apply_eq, inv_apply_self] }, { intro x, simp only [mk_inv_apply_eq, apply_inv_self] }, { apply finset.mem_univ }, { ext ⟨k, x⟩, { simp only [coe_fn_mk, prod_congr_left_apply] }, { simp only [prod_congr_left_apply, hσ] } } }, { intros σ _ hσ, rw mem_preserving_snd at hσ, obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ, rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero], rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne], exact hkx } end /-- The determinant of a 2×2 block matrix with the lower-left block equal to zero is the product of the determinants of the diagonal blocks. For the generalization to any number of blocks, see `matrix.det_of_upper_triangular`. -/ @[simp] lemma det_from_blocks_zero₂₁ (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : (matrix.from_blocks A B 0 D).det = A.det * D.det := begin classical, simp_rw det_apply', convert (sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m ⊕ n))).to_finset) _).symm, rw sum_mul_sum, simp_rw univ_product_univ, rw (sum_bij (λ (σ : perm m × perm n) _, equiv.sum_congr σ.fst σ.snd) _ _ _ _).symm, { intros σ₁₂ h, simp only [], erw [set.mem_to_finset, monoid_hom.mem_range], use σ₁₂, simp only [sum_congr_hom_apply] }, { simp only [forall_prop_of_true, prod.forall, mem_univ], intros σ₁ σ₂, rw fintype.prod_sum_type, simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁, from_blocks_apply₂₂], rw mul_mul_mul_comm, congr, rw [sign_sum_congr, units.coe_mul, int.cast_mul] }, { intros σ₁ σ₂ h₁ h₂, dsimp only [], intro h, have h2 : ∀ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr σ₂.fst σ₂.snd x, { intro x, exact congr_fun (congr_arg to_fun h) x }, simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2, ext, { exact h2.left x }, { exact h2.right x }}, { intros σ hσ, erw [set.mem_to_finset, monoid_hom.mem_range] at hσ, obtain ⟨σ₁₂, hσ₁₂⟩ := hσ, use σ₁₂, rw ←hσ₁₂, simp }, { intros σ hσ hσn, have h1 : ¬ (∀ x, ∃ y, sum.inl y = σ (sum.inl x)), { by_contradiction, rw set.mem_to_finset at hσn, apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hσn, rintros x ⟨a, ha⟩, rw [←ha], exact h a }, obtain ⟨a, ha⟩ := not_forall.mp h1, cases hx : σ (sum.inl a) with a2 b, { have hn := (not_exists.mp ha) a2, exact absurd hx.symm hn }, { rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero], rw [hx, from_blocks_apply₂₁], refl }} end /-- The determinant of a 2×2 block matrix with the upper-right block equal to zero is the product of the determinants of the diagonal blocks. For the generalization to any number of blocks, see `matrix.det_of_lower_triangular`. -/ @[simp] lemma det_from_blocks_zero₁₂ (A : matrix m m R) (C : matrix n m R) (D : matrix n n R) : (matrix.from_blocks A 0 C D).det = A.det * D.det := by rw [←det_transpose, from_blocks_transpose, transpose_zero, det_from_blocks_zero₂₁, det_transpose, det_transpose] /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column 0. -/ lemma det_succ_column_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) : det A = ∑ i : fin n.succ, (-1) ^ (i : ℕ) * A i 0 * det (A.submatrix i.succ_above fin.succ) := begin rw [matrix.det_apply, finset.univ_perm_fin_succ, ← finset.univ_product_univ], simp only [finset.sum_map, equiv.to_embedding_apply, finset.sum_product, matrix.submatrix], refine finset.sum_congr rfl (λ i _, fin.cases _ (λ i, _) i), { simp only [fin.prod_univ_succ, matrix.det_apply, finset.mul_sum, equiv.perm.decompose_fin_symm_apply_zero, fin.coe_zero, one_mul, equiv.perm.decompose_fin.symm_sign, equiv.swap_self, if_true, id.def, eq_self_iff_true, equiv.perm.decompose_fin_symm_apply_succ, fin.succ_above_zero, equiv.coe_refl, pow_zero, mul_smul_comm, of_apply] }, -- `univ_perm_fin_succ` gives a different embedding of `perm (fin n)` into -- `perm (fin n.succ)` than the determinant of the submatrix we want, -- permute `A` so that we get the correct one. have : (-1 : R) ^ (i : ℕ) = i.cycle_range.sign, { simp [fin.sign_cycle_range] }, rw [fin.coe_succ, pow_succ, this, mul_assoc, mul_assoc, mul_left_comm ↑(equiv.perm.sign _), ← det_permute, matrix.det_apply, finset.mul_sum, finset.mul_sum], -- now we just need to move the corresponding parts to the same place refine finset.sum_congr rfl (λ σ _, _), rw [equiv.perm.decompose_fin.symm_sign, if_neg (fin.succ_ne_zero i)], calc ((-1) * σ.sign : ℤ) • ∏ i', A (equiv.perm.decompose_fin.symm (fin.succ i, σ) i') i' = ((-1) * σ.sign : ℤ) • (A (fin.succ i) 0 * ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) : by simp only [fin.prod_univ_succ, fin.succ_above_cycle_range, equiv.perm.decompose_fin_symm_apply_zero, equiv.perm.decompose_fin_symm_apply_succ] ... = (-1) * (A (fin.succ i) 0 * (σ.sign : ℤ) • ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) : by simp only [mul_assoc, mul_comm, _root_.neg_mul, one_mul, zsmul_eq_mul, neg_inj, neg_smul, fin.succ_above_cycle_range], end /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row 0. -/ lemma det_succ_row_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) : det A = ∑ j : fin n.succ, (-1) ^ (j : ℕ) * A 0 j * det (A.submatrix fin.succ j.succ_above) := by { rw [← det_transpose A, det_succ_column_zero], refine finset.sum_congr rfl (λ i _, _), rw [← det_transpose], simp only [transpose_apply, transpose_submatrix, transpose_transpose] } /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row `i`. -/ lemma det_succ_row {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (i : fin n.succ) : det A = ∑ j : fin n.succ, (-1) ^ (i + j : ℕ) * A i j * det (A.submatrix i.succ_above j.succ_above) := begin simp_rw [pow_add, mul_assoc, ← mul_sum], have : det A = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A, { calc det A = ↑((-1 : ℤˣ) ^ (i : ℕ) * (-1 : ℤˣ) ^ (i : ℕ) : ℤˣ) * det A : by simp ... = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A : by simp [-int.units_mul_self] }, rw [this, mul_assoc], congr, rw [← det_permute, det_succ_row_zero], refine finset.sum_congr rfl (λ j _, _), rw [mul_assoc, matrix.submatrix, matrix.submatrix], congr, { rw [equiv.perm.inv_def, fin.cycle_range_symm_zero] }, { ext i' j', rw [equiv.perm.inv_def, fin.cycle_range_symm_succ] }, end /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column `j`. -/ lemma det_succ_column {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (j : fin n.succ) : det A = ∑ i : fin n.succ, (-1) ^ (i + j : ℕ) * A i j * det (A.submatrix i.succ_above j.succ_above) := by { rw [← det_transpose, det_succ_row _ j], refine finset.sum_congr rfl (λ i _, _), rw [add_comm, ← det_transpose, transpose_apply, transpose_submatrix, transpose_transpose] } /-- Determinant of 0x0 matrix -/ @[simp] lemma det_fin_zero {A : matrix (fin 0) (fin 0) R} : det A = 1 := det_is_empty /-- Determinant of 1x1 matrix -/ lemma det_fin_one (A : matrix (fin 1) (fin 1) R) : det A = A 0 0 := det_unique A lemma det_fin_one_of (a : R) : det !![a] = a := det_fin_one _ /-- Determinant of 2x2 matrix -/ lemma det_fin_two (A : matrix (fin 2) (fin 2) R) : det A = A 0 0 * A 1 1 - A 0 1 * A 1 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end @[simp] lemma det_fin_two_of (a b c d : R) : matrix.det !![a, b; c, d] = a * d - b * c := det_fin_two _ /-- Determinant of 3x3 matrix -/ lemma det_fin_three (A : matrix (fin 3) (fin 3) R) : det A = A 0 0 * A 1 1 * A 2 2 - A 0 0 * A 1 2 * A 2 1 - A 0 1 * A 1 0 * A 2 2 + A 0 1 * A 1 2 * A 2 0 + A 0 2 * A 1 0 * A 2 1 - A 0 2 * A 1 1 * A 2 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end end matrix
1d3d17fd1c9fc4d219acdc7ac705fa08cb3aa32d
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/coinductive_predicates.lean
dade07968b75b6f687eff870101bae6ce9d48720
[ "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
23,188
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl (CMU) -/ prelude import init.meta.expr init.meta.tactic init.meta.constructor_tactic init.meta.attribute import init.meta.interactive namespace name def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace expr open expr meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none meta def local_binder_info : expr → binder_info | (local_const x n bi t) := bi | e := binder_info.default meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] end expr namespace tactic open level expr tactic meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ const n $ ls.map param meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) meta def elim_gen_prod : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h, h'], _)] ← induction e [], elim_gen_prod n h' (hs ++ [h]) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h], _), ([h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] end tactic section universe u @[user_attribute] meta def monotonicity := { user_attribute . name := `monotonicity, descr := "Monotonicity rules for predicates" } lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := assume h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := assume h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, eapplyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← whnf p, (expr.pi qn qbi qd qb) ← whnf q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, eapply $ (const `monotonicity.pi [u] : expr) pd p' q') <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, eapply $ (const `monotonicity.imp []: expr) pd p' qd q'))) <|> first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip), all_goals mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ private meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← mk_local_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← mk_local_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binder_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all}, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, econstructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h) ← elim_gen_prod pds.length h [], (hs, h) ← elim_gen_prod pds.length h [], eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do eapply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, eapply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ eapply $ pd.destruct.app_of_list ps)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, eapply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, eapply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [], if n_eqs > 0 then do (eqs, eq') ← elim_gen_prod (n_eqs - 1) h [], (eqs ++ [eq']).mmap' subst else skip, eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs), repeat assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, eapply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework open lean.parser open interactive @[user_command] meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do decl ← inductive_decl.parse meta_info, add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros), decl.decls.mmap' $ λ d, do { get_env >>= λ env, set_env $ env.add_namespace d.name, meta_info.attrs.apply d.name, d.attrs.apply d.name, some doc_string ← pure meta_info.doc_string | skip, add_doc_string d.name doc_string } /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules (i.e. only a since C -/ meta def coinduction (rule : expr) : tactic unit := focus1 $ do ctxts' ← intros, -- TODO: why do we need to fix the type here? ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binder_info <$> infer_type v), mvars ← apply_core rule {approx := ff, new_goals := new_goals.all}, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v ≠ g), tgt ← target, (is, ty) ← mk_local_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars), rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, repeat econstructor), -- clean up remaining coinduction steps all_goals (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [], (match eqs with | [] := clear h | (e::eqs) := do (hs, h) ← elim_gen_prod eqs.length h [], (h::(hs.reverse)).mmap' subst end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule, skip end interactive end tactic
24da8b0065769c4b357496b04cddf6d30c1c54c0
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/factorial/basic.lean
9e577b6247914c9b38bd5591910a6073ad4d4c7a
[ "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
14,786
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn, Yaël Dillies -/ import data.nat.basic import data.nat.pow /-! # Factorial and variants This file defines the factorial, along with the ascending and descending variants. ## Main declarations * `nat.factorial`: The factorial. * `nat.asc_factorial`: The ascending factorial. Note that it runs from `n + 1` to `n + k` and *not* from `n` to `n + k - 1`. We might want to change that in the future. * `nat.desc_factorial`: The descending factorial. It runs from `n - k` to `n`. -/ namespace nat /-- `nat.factorial n` is the factorial of `n`. -/ @[simp] def factorial : ℕ → ℕ | 0 := 1 | (succ n) := succ n * factorial n localized "notation n `!`:10000 := nat.factorial n" in nat section factorial variables {m n : ℕ} @[simp] theorem factorial_zero : 0! = 1 := rfl @[simp] theorem factorial_succ (n : ℕ) : n.succ! = (n + 1) * n! := rfl @[simp] theorem factorial_one : 1! = 1 := rfl @[simp] theorem factorial_two : 2! = 2 := rfl theorem mul_factorial_pred (hn : 0 < n) : n * (n - 1)! = n! := tsub_add_cancel_of_le (nat.succ_le_of_lt hn) ▸ rfl theorem factorial_pos : ∀ n, 0 < n! | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (factorial_pos n) theorem factorial_ne_zero (n : ℕ) : n! ≠ 0 := ne_of_gt (factorial_pos _) theorem factorial_dvd_factorial {m n} (h : m ≤ n) : m! ∣ n! := begin induction n with n IH, { simp [nat.eq_zero_of_le_zero h] }, obtain rfl | hl := h.eq_or_lt, { simp }, exact (IH (le_of_lt_succ hl)).mul_left _, end theorem dvd_factorial : ∀ {m n}, 0 < m → m ≤ n → m ∣ n! | (succ m) n _ h := dvd_of_mul_right_dvd (factorial_dvd_factorial h) @[mono] theorem factorial_le {m n} (h : m ≤ n) : m! ≤ n! := le_of_dvd (factorial_pos _) (factorial_dvd_factorial h) lemma factorial_mul_pow_le_factorial : ∀ {m n : ℕ}, m! * m.succ ^ n ≤ (m + n)! | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.factorial_succ, mul_comm (nat.succ _), pow_succ', ← mul_assoc]; exact mul_le_mul factorial_mul_pow_le_factorial (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_factorial : monotone factorial := λ n m, factorial_le lemma factorial_lt (hn : 0 < n) : n! < m! ↔ n < m := begin refine ⟨λ h, not_le.mp $ λ hmn, not_le_of_lt h (factorial_le hmn), λ h, _⟩, have : ∀ {n}, 0 < n → n! < n.succ!, { intros k hk, rw [factorial_succ, succ_mul, lt_add_iff_pos_left], exact mul_pos hk k.factorial_pos }, induction h with k hnk ih generalizing hn, { exact this hn, }, { exact (ih hn).trans (this $ hn.trans $ lt_of_succ_le hnk) } end lemma one_lt_factorial : 1 < n! ↔ 1 < n := factorial_lt one_pos lemma factorial_eq_one : n! = 1 ↔ n ≤ 1 := begin refine ⟨λ h, _, by rintro (_ | ⟨_, _ | _⟩); refl⟩, rw [← not_lt, ← one_lt_factorial, h], apply lt_irrefl end lemma factorial_inj (hn : 1 < n!) : n! = m! ↔ n = m := begin refine ⟨λ h, _, congr_arg _⟩, obtain hnm | rfl | hnm := lt_trichotomy n m, { rw [← factorial_lt $ pos_of_gt $ one_lt_factorial.mp hn, h] at hnm, cases lt_irrefl _ hnm }, { refl }, rw [h, one_lt_factorial] at hn, rw [←factorial_lt (lt_trans one_pos hn), h] at hnm, cases lt_irrefl _ hnm end lemma self_le_factorial : ∀ n : ℕ, n ≤ n! | 0 := zero_le_one | (k + 1) := le_mul_of_one_le_right k.zero_lt_succ.le (nat.one_le_of_lt $ nat.factorial_pos _) lemma lt_factorial_self {n : ℕ} (hi : 3 ≤ n) : n < n! := begin rw [← succ_pred_eq_of_pos ((zero_lt_two.trans (lt.base 2)).trans_le hi), factorial_succ], exact lt_mul_of_one_lt_right ((pred n).succ_pos) ((one_lt_two.trans_le (le_pred_of_lt (succ_le_iff.mp hi))).trans_le (self_le_factorial _)), end lemma add_factorial_succ_lt_factorial_add_succ {i : ℕ} (n : ℕ) (hi : 2 ≤ i) : i + (n + 1)! < (i + n + 1)! := begin rw [factorial_succ (i + _), add_mul, one_mul], have : i ≤ i + n := le.intro rfl, exact add_lt_add_of_lt_of_le (this.trans_lt ((lt_mul_iff_one_lt_right (zero_lt_two.trans_le (hi.trans this))).mpr (lt_iff_le_and_ne.mpr ⟨(i + n).factorial_pos, λ g, nat.not_succ_le_self 1 ((hi.trans this).trans (factorial_eq_one.mp g.symm))⟩))) (factorial_le ((le_of_eq (add_comm n 1)).trans ((add_le_add_iff_right n).mpr (one_le_two.trans hi)))), end lemma add_factorial_lt_factorial_add {i n : ℕ} (hi : 2 ≤ i) (hn : 1 ≤ n) : i + n! < (i + n)! := begin cases hn, { rw factorial_one, exact lt_factorial_self (succ_le_succ hi) }, exact add_factorial_succ_lt_factorial_add_succ _ hi, end lemma add_factorial_succ_le_factorial_add_succ (i : ℕ) (n : ℕ) : i + (n + 1)! ≤ (i + (n + 1))! := begin obtain i2 | (_ | ⟨_, i0⟩) := le_or_lt 2 i, { exact (n.add_factorial_succ_lt_factorial_add_succ i2).le }, { rw [←add_assoc, factorial_succ (1 + n), add_mul, one_mul, add_comm 1 n], exact (add_le_add_iff_right _).mpr (one_le_mul (nat.le_add_left 1 n) (n + 1).factorial_pos) }, rw [nat.le_zero_iff.mp (nat.succ_le_succ_iff.mp i0), zero_add, zero_add] end lemma add_factorial_le_factorial_add (i : ℕ) {n : ℕ} (n1 : 1 ≤ n) : i + n! ≤ (i + n)! := begin cases n1 with h, { exact self_le_factorial _ }, exact add_factorial_succ_le_factorial_add_succ i h, end lemma factorial_mul_pow_sub_le_factorial {n m : ℕ} (hnm : n ≤ m) : n! * n ^ (m - n) ≤ m! := begin suffices : n! * (n + 1) ^ (m - n) ≤ m!, { apply trans _ this, rw mul_le_mul_left, apply pow_le_pow_of_le_left (zero_le n) (le_succ n), exact factorial_pos n }, convert nat.factorial_mul_pow_le_factorial, exact (add_tsub_cancel_of_le hnm).symm, end end factorial /-! ### Ascending and descending factorials -/ section asc_factorial /-- `n.asc_factorial k = (n + k)! / n!` (as seen in `nat.asc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def asc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n + k + 1) * asc_factorial k @[simp] lemma asc_factorial_zero (n : ℕ) : n.asc_factorial 0 = 1 := rfl @[simp] lemma zero_asc_factorial (k : ℕ) : (0 : ℕ).asc_factorial k = k! := begin induction k with t ht, { refl }, rw [asc_factorial, ht, zero_add, nat.factorial_succ], end lemma asc_factorial_succ {n k : ℕ} : n.asc_factorial k.succ = (n + k + 1) * n.asc_factorial k := rfl lemma succ_asc_factorial (n : ℕ) : ∀ k, (n + 1) * n.succ.asc_factorial k = (n + k + 1) * n.asc_factorial k | 0 := by rw [add_zero, asc_factorial_zero, asc_factorial_zero] | (k + 1) := by rw [asc_factorial, mul_left_comm, succ_asc_factorial, asc_factorial, succ_add, ←add_assoc] /-- `n.asc_factorial k = (n + k)! / n!` but without ℕ-division. See `nat.asc_factorial_eq_div` for the version with ℕ-division. -/ theorem factorial_mul_asc_factorial (n : ℕ) : ∀ k, n! * n.asc_factorial k = (n + k)! | 0 := by rw [asc_factorial, add_zero, mul_one] | (k + 1) := by rw [asc_factorial_succ, mul_left_comm, factorial_mul_asc_factorial, ← add_assoc, factorial] /-- Avoid in favor of `nat.factorial_mul_asc_factorial` if you can. ℕ-division isn't worth it. -/ lemma asc_factorial_eq_div (n k : ℕ) : n.asc_factorial k = (n + k)! / n! := begin apply mul_left_cancel₀ n.factorial_ne_zero, rw factorial_mul_asc_factorial, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ le.intro rfl).symm end lemma asc_factorial_of_sub {n k : ℕ} (h : k < n) : (n - k) * (n - k).asc_factorial k = (n - (k + 1)).asc_factorial (k + 1) := begin set t := n - k.succ with ht, suffices h' : n - k = t.succ, by rw [←ht, h', succ_asc_factorial, asc_factorial_succ], rw [ht, succ_eq_add_one, ←tsub_tsub_assoc (succ_le_of_lt h) (succ_pos _), succ_sub_one], end lemma pow_succ_le_asc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1)^k ≤ n.asc_factorial k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw pow_succ, exact nat.mul_le_mul (nat.add_le_add_right le_self_add _) (pow_succ_le_asc_factorial k), end lemma pow_lt_asc_factorial' (n k : ℕ) : (n + 1)^(k + 2) < n.asc_factorial (k + 2) := begin rw pow_succ, exact nat.mul_lt_mul (nat.add_lt_add_right (nat.lt_add_of_pos_right succ_pos') 1) (pow_succ_le_asc_factorial n _) (pow_pos succ_pos' _), end lemma pow_lt_asc_factorial (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → (n + 1)^k < n.asc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, pow_lt_asc_factorial' n k lemma asc_factorial_le_pow_add (n : ℕ) : ∀ (k : ℕ), n.asc_factorial k ≤ (n + k)^k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw [asc_factorial_succ, pow_succ], exact nat.mul_le_mul_of_nonneg_left ((asc_factorial_le_pow_add k).trans (nat.pow_le_pow_of_le_left (le_succ _) _)), end lemma asc_factorial_lt_pow_add (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → n.asc_factorial k < (n + k)^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, begin rw [asc_factorial_succ, pow_succ], refine nat.mul_lt_mul' le_rfl ((asc_factorial_le_pow_add n _).trans_lt (pow_lt_pow_of_lt_left (lt_add_one _) (succ_pos _))) (succ_pos _), end lemma asc_factorial_pos (n k : ℕ) : 0 < n.asc_factorial k := (pow_pos (succ_pos n) k).trans_le (pow_succ_le_asc_factorial n k) end asc_factorial section desc_factorial /-- `n.desc_factorial k = n! / (n - k)!` (as seen in `nat.desc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def desc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n - k) * desc_factorial k @[simp] lemma desc_factorial_zero (n : ℕ) : n.desc_factorial 0 = 1 := rfl @[simp] lemma desc_factorial_succ (n k : ℕ) : n.desc_factorial k.succ = (n - k) * n.desc_factorial k := rfl lemma zero_desc_factorial_succ (k : ℕ) : (0 : ℕ).desc_factorial k.succ = 0 := by rw [desc_factorial_succ, zero_tsub, zero_mul] @[simp] lemma desc_factorial_one (n : ℕ) : n.desc_factorial 1 = n := by rw [desc_factorial_succ, desc_factorial_zero, mul_one, tsub_zero] @[simp] lemma succ_desc_factorial_succ (n : ℕ) : ∀ k : ℕ, (n + 1).desc_factorial (k + 1) = (n + 1) * n.desc_factorial k | 0 := by rw [desc_factorial_zero, desc_factorial_one, mul_one] | (succ k) := by rw [desc_factorial_succ, succ_desc_factorial_succ, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma succ_desc_factorial (n : ℕ) : ∀ k, (n + 1 - k) * (n + 1).desc_factorial k = (n + 1) * n.desc_factorial k | 0 := by rw [tsub_zero, desc_factorial_zero, desc_factorial_zero] | (k + 1) := by rw [desc_factorial, succ_desc_factorial, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma desc_factorial_self : ∀ n : ℕ, n.desc_factorial n = n! | 0 := by rw [desc_factorial_zero, factorial_zero] | (succ n) := by rw [succ_desc_factorial_succ, desc_factorial_self, factorial_succ] @[simp] lemma desc_factorial_eq_zero_iff_lt {n : ℕ} : ∀ {k : ℕ}, n.desc_factorial k = 0 ↔ n < k | 0 := by simp only [desc_factorial_zero, nat.one_ne_zero, nat.not_lt_zero] | (succ k) := begin rw [desc_factorial_succ, mul_eq_zero, desc_factorial_eq_zero_iff_lt, lt_succ_iff, tsub_eq_zero_iff_le, lt_iff_le_and_ne, or_iff_left_iff_imp, and_imp], exact λ h _, h, end alias nat.desc_factorial_eq_zero_iff_lt ↔ _ nat.desc_factorial_of_lt lemma add_desc_factorial_eq_asc_factorial (n : ℕ) : ∀ k : ℕ, (n + k).desc_factorial k = n.asc_factorial k | 0 := by rw [asc_factorial_zero, desc_factorial_zero] | (succ k) := by rw [nat.add_succ, succ_desc_factorial_succ, asc_factorial_succ, add_desc_factorial_eq_asc_factorial] /-- `n.desc_factorial k = n! / (n - k)!` but without ℕ-division. See `nat.desc_factorial_eq_div` for the version using ℕ-division. -/ theorem factorial_mul_desc_factorial : ∀ {n k : ℕ}, k ≤ n → (n - k)! * n.desc_factorial k = n! | n 0 := λ _, by rw [desc_factorial_zero, mul_one, tsub_zero] | 0 (succ k) := λ h, by { exfalso, exact not_succ_le_zero k h } | (succ n) (succ k) := λ h, by rw [succ_desc_factorial_succ, succ_sub_succ, ←mul_assoc, mul_comm (n - k)!, mul_assoc, factorial_mul_desc_factorial (nat.succ_le_succ_iff.1 h), factorial_succ] /-- Avoid in favor of `nat.factorial_mul_desc_factorial` if you can. ℕ-division isn't worth it. -/ lemma desc_factorial_eq_div {n k : ℕ} (h : k ≤ n) : n.desc_factorial k = n! / (n - k)! := begin apply mul_left_cancel₀ (factorial_ne_zero (n - k)), rw factorial_mul_desc_factorial h, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ nat.sub_le n k).symm, end lemma pow_sub_le_desc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1 - k)^k ≤ n.desc_factorial k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ, succ_sub_succ], exact nat.mul_le_mul_of_nonneg_left (le_trans (nat.pow_le_pow_of_le_left (tsub_le_tsub_right (le_succ _) _) k) (pow_sub_le_desc_factorial k)), end lemma pow_sub_lt_desc_factorial' {n : ℕ} : ∀ {k : ℕ}, k + 2 ≤ n → (n - (k + 1))^(k + 2) < n.desc_factorial (k + 2) | 0 := λ h, begin rw [desc_factorial_succ, pow_succ, pow_one, desc_factorial_one], exact nat.mul_lt_mul_of_pos_left (tsub_lt_self (lt_of_lt_of_le zero_lt_two h) zero_lt_one) (tsub_pos_of_lt h), end | (k + 1) := λ h, begin rw [desc_factorial_succ, pow_succ], refine nat.mul_lt_mul_of_pos_left ((nat.pow_le_pow_of_le_left (tsub_le_tsub_right (le_succ n) _) _).trans_lt _) (tsub_pos_of_lt h), rw succ_sub_succ, exact (pow_sub_lt_desc_factorial' ((le_succ _).trans h)), end lemma pow_sub_lt_desc_factorial {n : ℕ} : ∀ {k : ℕ}, 2 ≤ k → k ≤ n → (n + 1 - k)^k < n.desc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _ h, by { rw succ_sub_succ, exact pow_sub_lt_desc_factorial' h } lemma desc_factorial_le_pow (n : ℕ) : ∀ (k : ℕ), n.desc_factorial k ≤ n^k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ], exact nat.mul_le_mul (nat.sub_le _ _) (desc_factorial_le_pow k), end lemma desc_factorial_lt_pow {n : ℕ} (hn : 1 ≤ n) : ∀ {k : ℕ}, 2 ≤ k → n.desc_factorial k < n^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, begin rw [desc_factorial_succ, pow_succ', mul_comm], exact nat.mul_lt_mul' (desc_factorial_le_pow _ _) (tsub_lt_self hn k.zero_lt_succ) (pow_pos hn _), end end desc_factorial end nat
93734c951e8c264958cf831008189e10d3869480
ee128d773bb25d84d8de87a8dbea4fb24735aa8b
/src/Init/Lean/Elab/App.lean
4d744ff6846b1afdea8f50c29ad822adf09a2f58
[ "Apache-2.0" ]
permissive
zeta1999/lean4
98872239fa5698a2c5d3707d3f33bfdd6520d532
aa4fc12dfff2ead4d33d32136f50115f9a6c941c
refs/heads/master
1,649,991,244,528
1,585,328,478,000
1,586,975,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,203
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Util.FindMVar import Init.Lean.Elab.Term import Init.Lean.Elab.Binders namespace Lean namespace Elab namespace Term /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg | stx (val : Syntax) | expr (val : Expr) instance Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩ instance Arg.hasToString : HasToString Arg := ⟨fun arg => match arg with | Arg.stx val => toString val | Arg.expr val => toString val⟩ /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg := (name : Name) (val : Arg) instance NamedArg.hasToString : HasToString NamedArg := ⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩ instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩ /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (ref : Syntax) (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $ throwError ref ("argument '" ++ toString namedArg.name ++ "' was already set"); pure $ namedArgs.push namedArg def synthesizeAppInstMVars (ref : Syntax) (instMVars : Array MVarId) : TermElabM Unit := instMVars.forM $ fun mvarId => unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass private def ensureArgType (ref : Syntax) (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do argType ← inferType ref arg; ensureHasTypeAux ref expectedType argType arg f private def elabArg (ref : Syntax) (f : Expr) (arg : Arg) (expectedType : Expr) : TermElabM Expr := match arg with | Arg.expr val => ensureArgType ref f val expectedType | Arg.stx val => do val ← elabTerm val expectedType; ensureArgType ref f val expectedType private def mkArrow (d b : Expr) : TermElabM Expr := do n ← mkFreshAnonymousName; pure $ Lean.mkForall n BinderInfo.default d b /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do v ← mkFreshLevelMVar ref; type ← mkArrow α (mkSort v); γ ← mkFreshExprMVar ref type; u ← getLevel ref α; let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ]; mvar ← mkFreshExprMVar ref coeFunInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; synthesized ← catch (withoutMacroStackAtErr $ synthesizeInstMVarCore ref mvarId) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwError ref ("function expected" ++ Format.line ++ errMsg.data) | _ => throwError ref "function expected"); if synthesized then pure $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar] else throwError ref "function expected" /-- Auxiliary structure used to elaborate function application arguments. -/ structure ElabAppArgsCtx := (ref : Syntax) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) -- if true, all arguments are treated as explicit (argIdx : Nat := 0) -- position of next explicit argument to be processed (namedArgs : Array NamedArg) -- remaining named arguments to be processed (instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed (typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed (foundExplicit : Bool := false) -- true if an explicit argument has already been processed /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. -/ private partial def getForallBody : Nat → Array NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => getForallBody i (namedArgs.eraseIdx idx) b | none => if !c.binderInfo.isExplicit then getForallBody i namedArgs b else if i > 0 then getForallBody (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody i namedArgs b else some type | i, namedArgs, type => if i == 0 && namedArgs.isEmpty then some type else none private def hasTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => ctx.typeMVars.contains mvarId)).isSome private def hasOnlyTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => !ctx.typeMVars.contains mvarId)).isNone /- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean HasAdd.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`) 2- The resultant type does not contain any type metavariable. 3- The resultant type contains a nontype metavariable. We added conditions 2&3 to be able to restrict this method to simple functions that are "morally" in the Hindley&Milner fragment. For example, consider the following definitions ``` def foo {n m : Nat} (a : bv n) (b : bv m) : bv (n - m) ``` Now, consider ``` def test (x1 : bv 32) (x2 : bv 31) (y1 : bv 64) (y2 : bv 63) : bv 1 := foo x1 x2 = foo y1 y2 ``` When the elaborator reaches the term `foo y1 y2`, the expected type is `bv (32-31)`. If we apply this method, we would solve the unification problem `bv (?n - ?m) =?= bv (32 - 31)`, by assigning `?n := 32` and `?m := 31`. Then, the elaborator fails elaborating `y1` since `bv 64` is **not** definitionally equal to `bv 32`. -/ private def propagateExpectedType (ctx : ElabAppArgsCtx) (eType : Expr) : TermElabM Unit := unless (ctx.explicit || ctx.foundExplicit || ctx.typeMVars.isEmpty) $ do match ctx.expectedType? with | none => pure () | some expectedType => let numRemainingArgs := ctx.args.size - ctx.argIdx; match getForallBody numRemainingArgs ctx.namedArgs eType with | none => pure () | some eTypeBody => unless eTypeBody.hasLooseBVars $ when (hasTypeMVar ctx eTypeBody && hasOnlyTypeMVar ctx eTypeBody) $ do isDefEq ctx.ref expectedType eTypeBody; pure () private def nextArgIsHole (ctx : ElabAppArgsCtx) : Bool := if h : ctx.argIdx < ctx.args.size then match ctx.args.get ⟨ctx.argIdx, h⟩ with | Arg.stx (Syntax.node `Lean.Parser.Term.hole _) => true | _ => false else false /- Elaborate function application arguments. -/ private partial def elabAppArgsAux : ElabAppArgsCtx → Expr → Expr → TermElabM Expr | ctx, e, eType => do let finalize : Unit → TermElabM Expr := fun _ => do { -- all user explicit arguments have been consumed trace `Elab.app.finalize ctx.ref $ fun _ => e; match ctx.expectedType? with | none => pure () | some expectedType => do { -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. isDefEq ctx.ref expectedType eType; pure () }; synthesizeAppInstMVars ctx.ref ctx.instMVars; pure e }; eType ← whnfForall ctx.ref eType; match eType with | Expr.forallE n d b c => match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let arg := ctx.namedArgs.get! idx; let namedArgs := ctx.namedArgs.eraseIdx idx; argElab ← elabArg ctx.ref e arg.val d; propagateExpectedType ctx eType; elabAppArgsAux { foundExplicit := true, namedArgs := namedArgs, .. ctx } (mkApp e argElab) (b.instantiate1 argElab) | none => let processExplictArg : Unit → TermElabM Expr := fun _ => do { propagateExpectedType ctx eType; let ctx := { foundExplicit := true, .. ctx }; if h : ctx.argIdx < ctx.args.size then do argElab ← elabArg ctx.ref e (ctx.args.get ⟨ctx.argIdx, h⟩) d; elabAppArgsAux { argIdx := ctx.argIdx + 1, .. ctx } (mkApp e argElab) (b.instantiate1 argElab) else match ctx.explicit, d.getOptParamDefault?, d.getAutoParamTactic? with | false, some defVal, _ => elabAppArgsAux ctx (mkApp e defVal) (b.instantiate1 defVal) | false, _, some (Expr.const tacticDecl _ _) => do env ← getEnv; match evalSyntaxConstant env tacticDecl with | Except.error err => throwError ctx.ref err | Except.ok tacticSyntax => do tacticBlock ← `(begin $(tacticSyntax.getArgs)* end); -- tacticBlock does not have any position information -- use ctx.ref.getHeadInfo if available let tacticBlock := match ctx.ref.getHeadInfo with | some info => tacticBlock.replaceInfo info | _ => tacticBlock; let d := d.getArg! 0; -- `autoParam type := by tactic` ==> `type` argElab ← elabArg ctx.ref e (Arg.stx tacticBlock) d; elabAppArgsAux ctx (mkApp e argElab) (b.instantiate1 argElab) | false, _, some _ => throwError ctx.ref "invalid autoParam, argument must be a constant" | _, _, _ => if ctx.namedArgs.isEmpty then finalize () else throwError ctx.ref ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name)) }; match c.binderInfo with | BinderInfo.implicit => if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d; typeMVars ← condM (isTypeFormer ctx.ref a) (pure $ ctx.typeMVars.push a.mvarId!) (pure ctx.typeMVars); elabAppArgsAux { typeMVars := typeMVars, .. ctx } (mkApp e a) (b.instantiate1 a) | BinderInfo.instImplicit => if ctx.explicit && nextArgIsHole ctx then do /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { argIdx := ctx.argIdx + 1, instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a) else if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a) | _ => processExplictArg () | _ => if ctx.namedArgs.isEmpty && ctx.argIdx == ctx.args.size then finalize () else do e ← tryCoeFun ctx.ref eType e; eType ← inferType ctx.ref e; elabAppArgsAux ctx e eType private def elabAppArgs (ref : Syntax) (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do fType ← inferType ref f; fType ← instantiateMVars ref fType; trace `Elab.app.args ref $ fun _ => "explicit: " ++ toString explicit ++ ", " ++ f ++ " : " ++ fType; unless (namedArgs.isEmpty && args.isEmpty) $ tryPostponeIfMVar fType; elabAppArgsAux {ref := ref, args := args, expectedType? := expectedType?, explicit := explicit, namedArgs := namedArgs } f fType /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (ref : Syntax) (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError ref $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType private def resolveLValAux (ref : Syntax) (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := match eType.getAppFn, lval with | Expr.const structName _ _, LVal.fieldIdx idx => do when (idx == 0) $ throwError ref "invalid projection, index must be greater than 0"; env ← getEnv; unless (isStructureLike env structName) $ throwLValError ref e eType "invalid projection, structure expected"; let fieldNames := getStructureFields env structName; if h : idx - 1 < fieldNames.size then if isStructure env structName then pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩) else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ pure $ LValResolution.projIdx structName (idx - 1) else throwLValError ref e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)") | Expr.const structName _ _, LVal.fieldName fieldName => do env ← getEnv; let searchEnv (fullName : Name) : TermElabM LValResolution := do { match env.find? fullName with | some _ => pure $ LValResolution.const structName fullName | none => let fullNamePrv := mkPrivateName env fullName; match env.find? fullNamePrv with | some _ => pure $ LValResolution.const structName fullNamePrv | none => throwLValError ref e eType $ "invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ fullName ++ "'" }; -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do { let fullName := structName ++ fieldName; currNamespace ← getCurrNamespace; let localName := fullName.replacePrefix currNamespace Name.anonymous; lctx ← getLCtx; match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv fullName | none => searchEnv fullName }; if isStructure env structName then match findField? env structName fieldName with | some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName | none => searchCtx () else searchCtx () | Expr.const structName _ _, LVal.getOp idx => do env ← getEnv; let fullName := mkNameStr structName "getOp"; match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError ref e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'" | _, LVal.getOp idx => throwLValError ref e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError ref e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private partial def resolveLValLoop (ref : Syntax) (e : Expr) (lval : LVal) : Expr → Array Message → TermElabM LValResolution | eType, previousExceptions => do eType ← whnfCore ref eType; tryPostponeIfMVar eType; catch (resolveLValAux ref e eType lval) (fun ex => match ex with | Exception.postpone => throw ex | Exception.ex Elab.Exception.unsupportedSyntax => throw ex | Exception.ex (Elab.Exception.error errMsg) => do eType? ← unfoldDefinition? ref eType; match eType? with | some eType => resolveLValLoop eType (previousExceptions.push errMsg) | none => do previousExceptions.forM $ fun ex => logMessage errMsg; throw (Exception.ex (Elab.Exception.error errMsg))) private def resolveLVal (ref : Syntax) (e : Expr) (lval : LVal) : TermElabM LValResolution := do eType ← inferType ref e; resolveLValLoop ref e lval eType #[] private partial def mkBaseProjections (ref : Syntax) (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do env ← getEnv; match getPathToBaseStructure? env baseStructName structName with | none => throwError ref "failed to access field in parent structure" | some path => path.foldlM (fun e projFunName => do projFn ← mkConst ref projFunName; elabAppArgs ref projFn #[{ name := `self, val := Arg.expr e }] #[] none false) e /- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter which takes an element of type `(C ...)` where `C` is `baseName`. `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (ref : Syntax) (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg) | i, namedArgs, Expr.forallE n d b c => if !c.binderInfo.isExplicit then addLValArg i namedArgs b else /- If there is named argument with name `n`, then we should skip. -/ match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let namedArgs := namedArgs.eraseIdx idx; addLValArg i namedArgs b | none => do if d.consumeMData.isAppOf baseName then pure $ args.insertAt i (Arg.expr e) else if i < args.size then addLValArg (i+1) namedArgs b else throwError ref $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'" | _, _, fType => throwError ref $ "invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)" private def elabAppLValsAux (ref : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs ref f namedArgs args expectedType? explicit | f, lval::lvals => do lvalRes ← resolveLVal ref f lval; match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f; elabAppLValsAux f lvals | LValResolution.projFn baseStructName structName fieldName => do f ← mkBaseProjections ref baseStructName structName f; projFn ← mkConst ref (baseStructName ++ fieldName); if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[{ name := `self, val := Arg.expr f }] #[] none false; elabAppLValsAux f lvals | LValResolution.const baseName constName => do projFn ← mkConst ref constName; if lvals.isEmpty then do projFnType ← inferType ref projFn; args ← addLValArg ref baseName constName f args 0 namedArgs projFnType; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.localRec baseName fullName fvar => if lvals.isEmpty then do fvarType ← inferType ref fvar; args ← addLValArg ref baseName fullName f args 0 namedArgs fvarType; elabAppArgs ref fvar namedArgs args expectedType? explicit else do f ← elabAppArgs ref fvar #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.getOp fullName idx => do getOpFn ← mkConst ref fullName; if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; namedArgs ← addNamedArg ref namedArgs { name := `idx, val := Arg.stx idx }; elabAppArgs ref getOpFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false; elabAppLValsAux f lvals private def elabAppLVals (ref : Syntax) (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do when (!lvals.isEmpty && explicit) $ throwError ref "invalid use of field notation with `@` modifier"; elabAppLValsAux ref namedArgs args expectedType? explicit f lvals def elabExplicitUniv (stx : Syntax) : TermElabM (List Level) := do let lvls := stx.getArg 1; lvls.foldSepRevArgsM (fun stx lvls => do lvl ← elabLevel stx; pure (lvl::lvls)) [] private partial def elabAppFnId (ref : Syntax) (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) (acc : Array TermElabResult) : TermElabM (Array TermElabResult) := match fIdent with | Syntax.ident _ _ n preresolved => do funLVals ← resolveName fIdent n preresolved fExplicitUnivs; funLVals.foldlM (fun acc ⟨f, fields⟩ => do let lvals' := fields.map LVal.fieldName; s ← observing $ elabAppLVals ref f (lvals' ++ lvals) namedArgs args expectedType? explicit; pure $ acc.push s) acc | _ => throwUnsupportedSyntax private partial def elabAppFn (ref : Syntax) : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult) | f, lvals, namedArgs, args, expectedType?, explicit, acc => if f.isIdent then -- A raw identifier is not a valid Term. Recall that `Term.id` is defined as `parser! ident >> optional (explicitUniv <|> namedPattern)` -- We handle it here to make macro development more comfortable. elabAppFnId ref f [] lvals namedArgs args expectedType? explicit acc else if f.getKind == choiceKind then f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit acc) acc else match_syntax f with | `($(e).$idx:fieldIdx) => let idx := idx.isFieldIdx?.get!; elabAppFn e (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit acc | `($(e).$field:ident) => let newLVals := field.getId.eraseMacroScopes.components.map (fun n => LVal.fieldName (toString n)); elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit acc | `($e[$idx]) => elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc | `($id:ident$us:explicitUniv*) => do -- Remark: `id.<namedPattern>` should already have been expanded us ← if us.isEmpty then pure [] else elabExplicitUniv (us.get! 0); elabAppFnId ref id us lvals namedArgs args expectedType? explicit acc | `(@$id:id) => elabAppFn id lvals namedArgs args expectedType? true acc | `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@` | _ => do s ← observing $ do { f ← elabTerm f none; elabAppLVals ref f lvals namedArgs args expectedType? explicit }; pure $ acc.push s private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult := candidates.filter $ fun c => match c with | EStateM.Result.ok _ _ => true | _ => false private def toMessageData (msg : Message) (stx : Syntax) : TermElabM MessageData := do strPos ← getPos stx; pos ← getPosition strPos; if pos == msg.pos then pure msg.data else pure $ toString msg.pos.line ++ ":" ++ toString msg.pos.column ++ " " ++ msg.data private def mergeFailures {α} (failures : Array TermElabResult) (stx : Syntax) : TermElabM α := do msgs ← failures.mapM $ fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error errMsg s => toMessageData errMsg stx; throwError stx ("overloaded, errors " ++ MessageData.ofArray msgs) private def elabAppAux (ref : Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do /- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we should postpone until `?m` is assigned. Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`. We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/ candidates ← elabAppFn ref f [] namedArgs args expectedType? false #[]; if candidates.size == 1 then applyResult $ candidates.get! 0 else let successes := getSuccess candidates; if successes.size == 1 then applyResult $ successes.get! 0 else if successes.size > 1 then do lctx ← getLCtx; opts ← getOptions; let msgs : Array MessageData := successes.map $ fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.env, mctx := s.mctx, lctx := lctx, opts := opts } e | _ => unreachable!; throwError f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs) else mergeFailures candidates f private partial def expandApp (stx : Syntax) : TermElabM (Syntax × Array NamedArg × Array Arg) := do let f := stx.getArg 0; (namedArgs, args) ← (stx.getArg 1).getArgs.foldlM (fun (acc : Array NamedArg × Array Arg) (stx : Syntax) => do let (namedArgs, args) := acc; if stx.getKind == `Lean.Parser.Term.namedArgument then do -- tparser! try ("(" >> ident >> " := ") >> termParser >> ")" let name := (stx.getArg 1).getId.eraseMacroScopes; let val := stx.getArg 3; namedArgs ← addNamedArg stx namedArgs { name := name, val := Arg.stx val }; pure (namedArgs, args) else pure (namedArgs, args.push $ Arg.stx stx)) (#[], #[]); pure (f, namedArgs, args) @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => do (f, namedArgs, args) ← expandApp stx; elabAppAux stx f namedArgs args expectedType? def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx stx #[] #[] expectedType? @[builtinTermElab «id»] def elabId : TermElab := elabAtom @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match_syntax stx with | `(@$id:id) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@($t)) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom /- A raw identiier is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. -/ @[builtinTermElab ident] def elabRawIdent : TermElab := elabAtom @[builtinTermElab sortApp] def elabSortApp : TermElab := fun stx _ => do u ← elabLevel (stx.getArg 1); if (stx.getArg 0).getKind == `Lean.Parser.Term.sort then do pure $ mkSort u else pure $ mkSort (mkLevelSucc u) @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.app; pure () end Term end Elab end Lean
3c4125b364bda35cf83a2d49731e5e02e658b121
46125763b4dbf50619e8846a1371029346f4c3db
/src/category_theory/limits/shapes/equalizers.lean
da020e836d07f228278230cd73e468d6c870b367
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
18,078
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import data.fintype import category_theory.limits.limits import category_theory.limits.shapes.finite_limits /-! # Equalizers and coequalizers This file defines (co)equalizers as special cases of (co)limits. An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`. A coequalizer is the dual concept. ## Main definitions * `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams * `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`. * a `fork` is a cone over a parallel pair. * there is really only one interesting morphism in a fork: the arrow from the vertex of the fork to the domain of f and g. It is called `fork.ι`. * an `equalizer` is now just a `limit (parallel_pair f g)` Each of these has a dual. ## Main statements * `equalizer.ι_mono` states that every equalizer map is a monomorphism * `is_limit_cone_parallel_pair_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ open category_theory namespace category_theory.limits local attribute [tidy] tactic.case_bash universes v u /-- The type of objects for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq] inductive walking_parallel_pair : Type v | zero | one instance fintype_walking_parallel_pair : fintype walking_parallel_pair := { elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset, complete := λ x, by { cases x; simp } } open walking_parallel_pair /-- The type family of morphisms for the diagram indexing a (co)equalizer. -/ @[derive _root_.decidable_eq] inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type v | left : walking_parallel_pair_hom zero one | right : walking_parallel_pair_hom zero one | id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X open walking_parallel_pair_hom instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') := { elems := walking_parallel_pair.rec_on j (walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset [left, right].to_finset) (walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset), complete := by tidy } def walking_parallel_pair_hom.comp : Π (X Y Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z), walking_parallel_pair_hom X Z | _ _ _ (id _) h := h | _ _ _ left (id one) := left | _ _ _ right (id one) := right . instance walking_parallel_pair_hom_category : small_category.{v} walking_parallel_pair := { hom := walking_parallel_pair_hom, id := walking_parallel_pair_hom.id, comp := walking_parallel_pair_hom.comp } instance : fin_category.{v} walking_parallel_pair.{v} := { } lemma walking_parallel_pair_hom_id (X : walking_parallel_pair.{v}) : walking_parallel_pair_hom.id X = 𝟙 X := rfl variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables {X Y : C} def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C := { obj := λ x, match x with | zero := X | one := Y end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, left := f | _, _, right := g end }. @[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl @[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl @[simp] lemma parallel_pair_functor_obj {F : walking_parallel_pair.{v} ⥤ C} (j : walking_parallel_pair.{v}) : (parallel_pair (F.map left) (F.map right)).obj j = F.obj j := begin cases j; refl end abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g) abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g) variables {f g : X ⟶ Y} @[simp] lemma cone_parallel_pair_left (s : cone (parallel_pair f g)) : (s.π).app zero ≫ f = (s.π).app one := by { conv_lhs { congr, skip, rw ←parallel_pair_map_left f g }, rw s.w } @[simp] lemma cone_parallel_pair_right (s : cone (parallel_pair f g)) : (s.π).app zero ≫ g = (s.π).app one := by { conv_lhs { congr, skip, rw ←parallel_pair_map_right f g }, rw s.w } @[simp] lemma cocone_parallel_pair_left (s : cocone (parallel_pair f g)) : f ≫ (s.ι).app one = (s.ι).app zero := by { conv_lhs { congr, rw ←parallel_pair_map_left f g }, rw s.w } @[simp] lemma cocone_parallel_pair_right (s : cocone (parallel_pair f g)) : g ≫ (s.ι).app one = (s.ι).app zero := by { conv_lhs { congr, rw ←parallel_pair_map_right f g }, rw s.w } /-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the first map -/ lemma cone_parallel_pair_ext (s : cone (parallel_pair f g)) {W : C} {k l : W ⟶ s.X} (h : k ≫ s.π.app zero = l ≫ s.π.app zero) : ∀ (j : walking_parallel_pair), k ≫ s.π.app j = l ≫ s.π.app j | zero := h | one := by { rw [←cone_parallel_pair_left, ←category.assoc, ←category.assoc], congr, exact h } /-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for the second map -/ lemma cocone_parallel_pair_ext (s : cocone (parallel_pair f g)) {W : C} {k l : s.X ⟶ W} (h : s.ι.app one ≫ k = s.ι.app one ≫ l) : ∀ (j : walking_parallel_pair), s.ι.app j ≫ k = s.ι.app j ≫ l | zero := by { rw [←cocone_parallel_pair_right, category.assoc, category.assoc], congr, exact h } | one := h attribute [simp] walking_parallel_pair_hom_id def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g := { X := P, π := { app := λ X, begin cases X, exact ι, exact ι ≫ f, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, exact w end } } def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g := { X := P, ι := { app := λ X, begin cases X, exact f ≫ π, exact π, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, exact eq.symm w end } } @[simp] lemma fork.of_ι_app_zero {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app zero = ι := rfl @[simp] lemma fork.of_ι_app_one {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app one = ι ≫ f := rfl @[simp] lemma cofork.of_π_app_zero {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).ι.app zero = f ≫ π := rfl @[simp] lemma cofork.of_π_app_one {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).ι.app one = π := rfl def fork.ι (t : fork f g) := t.π.app zero def cofork.π (t : cofork f g) := t.ι.app one lemma fork.condition (t : fork f g) : (fork.ι t) ≫ f = (fork.ι t) ≫ g := begin erw [t.w left, ← t.w right], refl end lemma cofork.condition (t : cofork f g) : f ≫ (cofork.π t) = g ≫ (cofork.π t) := begin erw [t.w left, ← t.w right], refl end section local attribute [ext] cone /-- The fork induced by the ι map of some fork `t` is the same as `t` -/ lemma fork.eq_of_ι_ι (t : fork f g) : t = fork.of_ι (fork.ι t) (fork.condition t) := begin have h : t.π = (fork.of_ι (fork.ι t) (fork.condition t)).π, { ext j, cases j, { refl }, { rw ←cone_parallel_pair_left, refl } }, tidy end end def cone.of_fork {F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } section local attribute [ext] cocone /-- The cofork induced by the π map of some fork `t` is the same as `t` -/ lemma cofork.eq_of_π_π (t : cofork f g) : t = cofork.of_π (cofork.π t) (cofork.condition t) := begin have h : t.ι = (cofork.of_π (cofork.π t) (cofork.condition t)).ι, { ext j, cases j, { rw ←cocone_parallel_pair_left, refl }, { refl } }, tidy end end def cocone.of_cofork {F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } @[simp] lemma cone.of_fork_π {F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) (j) : (cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cofork_ι {F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) (j) : (cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl def fork.of_cone {F : walking_parallel_pair.{v} ⥤ C} (t : cone F) : fork (F.map left) (F.map right) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } def cofork.of_cocone {F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma fork.of_cone_π {F : walking_parallel_pair.{v} ⥤ C} (t : cone F) (j) : (fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) (j) : (cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl variables (f g) section variables [has_limit (parallel_pair f g)] abbreviation equalizer := limit (parallel_pair f g) abbreviation equalizer.ι : equalizer f g ⟶ X := limit.π (parallel_pair f g) zero @[simp] lemma equalizer.ι.fork : fork.ι (limit.cone (parallel_pair f g)) = equalizer.ι f g := rfl @[simp] lemma equalizer.ι.eq_app_zero : (limit.cone (parallel_pair f g)).π.app zero = equalizer.ι f g := rfl @[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g := fork.condition $ limit.cone $ parallel_pair f g abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g := limit.lift (parallel_pair f g) (fork.of_ι k h) /-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer map. -/ @[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g} (h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l := limit.hom_ext $ cone_parallel_pair_ext _ h /-- An equalizer morphism is a monomorphism -/ instance equalizer.ι_mono : mono (equalizer.ι f g) := { right_cancellation := λ Z h k w, equalizer.hom_ext _ _ w } end section /-- The identity determines a cone on the equalizer diagram of f and f -/ def cone_parallel_pair_self : cone (parallel_pair f f) := { X := X, π := { app := λ j, match j with | zero := 𝟙 X | one := f end } } @[simp] lemma cone_parallel_pair_self_π_app_zero : (cone_parallel_pair_self f).π.app zero = 𝟙 X := rfl @[simp] lemma cone_parallel_pair_self_X : (cone_parallel_pair_self f).X = X := rfl /-- The identity on X is an equalizer of (f, f) -/ def is_limit_cone_parallel_pair_self : is_limit (cone_parallel_pair_self f) := { lift := λ s, s.π.app zero, fac' := λ s j, match j with | zero := by erw category.comp_id | one := by erw cone_parallel_pair_left end, uniq' := λ s m w, by { convert w zero, erw category.comp_id } } /-- Every equalizer of (f, f) is an isomorphism -/ def limit_cone_parallel_pair_self_is_iso (c : cone (parallel_pair f f)) (h : is_limit c) : is_iso (c.π.app zero) := let c' := cone_parallel_pair_self f, z : c ≅ c' := is_limit.unique_up_to_iso h (is_limit_cone_parallel_pair_self f) in is_iso.of_iso (functor.map_iso (cones.forget _) z) /-- The equalizer of (f, f) is an isomorphism -/ def equalizer.ι_of_self [has_limit (parallel_pair f f)] : is_iso (equalizer.ι f f) := limit_cone_parallel_pair_self_is_iso _ _ $ limit.is_limit _ /-- Every equalizer of (f, g), where f = g, is an isomorphism -/ def limit_cone_parallel_pair_self_is_iso' (c : cone (parallel_pair f g)) (h₀ : is_limit c) (h₁ : f = g) : is_iso (c.π.app zero) := begin rw fork.eq_of_ι_ι c at *, have h₂ : is_limit (fork.of_ι (c.π.app zero) rfl : fork f f), by convert h₀, exact limit_cone_parallel_pair_self_is_iso f (fork.of_ι (c.π.app zero) rfl) h₂ end /-- The equalizer of (f, g), where f = g, is an isomorphism -/ def equalizer.ι_of_self' [has_limit (parallel_pair f g)] (h : f = g) : is_iso (equalizer.ι f g) := limit_cone_parallel_pair_self_is_iso' _ _ _ (limit.is_limit _) h /-- An equalizer that is an epimorphism is an isomorphism -/ def epi_limit_cone_parallel_pair_is_iso (c : cone (parallel_pair f g)) (h : is_limit c) [epi (c.π.app zero)] : is_iso (c.π.app zero) := limit_cone_parallel_pair_self_is_iso' f g c h $ (cancel_epi (c.π.app zero)).1 (fork.condition c) end section variables [has_colimit (parallel_pair f g)] abbreviation coequalizer := colimit (parallel_pair f g) abbreviation coequalizer.π : Y ⟶ coequalizer f g := colimit.ι (parallel_pair f g) one @[simp] lemma coequalizer.π.cofork : cofork.π (colimit.cocone (parallel_pair f g)) = coequalizer.π f g := rfl @[simp] lemma coequalizer.π.eq_app_one : (colimit.cocone (parallel_pair f g)).ι.app one = coequalizer.π f g := rfl @[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g := cofork.condition $ colimit.cocone $ parallel_pair f g abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W := colimit.desc (parallel_pair f g) (cofork.of_π k h) /-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer map -/ @[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W} (h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l := colimit.hom_ext $ cocone_parallel_pair_ext _ h /-- A coequalizer morphism is an epimorphism -/ instance coequalizer.π_epi : epi (coequalizer.π f g) := { left_cancellation := λ Z h k w, coequalizer.hom_ext _ _ w } end section /-- The identity determines a cocone on the coequalizer diagram of f and f -/ def cocone_parallel_pair_self : cocone (parallel_pair f f) := { X := Y, ι := { app := λ j, match j with | zero := f | one := 𝟙 Y end, naturality' := λ j j' g, begin cases g, { refl }, { erw category.comp_id _ f }, { dsimp, simp } end } } @[simp] lemma cocone_parallel_pair_self_ι_app_one : (cocone_parallel_pair_self f).ι.app one = 𝟙 Y := rfl @[simp] lemma cocone_parallel_pair_self_X : (cocone_parallel_pair_self f).X = Y := rfl /-- The identity on Y is a colimit of (f, f) -/ def is_colimit_cocone_parallel_pair_self : is_colimit (cocone_parallel_pair_self f) := { desc := λ s, s.ι.app one, fac' := λ s j, match j with | zero := by erw cocone_parallel_pair_right | one := by erw category.id_comp end, uniq' := λ s m w, by { convert w one, erw category.id_comp } } /-- Every coequalizer of (f, f) is an isomorphism -/ def colimit_cocone_parallel_pair_self_is_iso (c : cocone (parallel_pair f f)) (h : is_colimit c) : is_iso (c.ι.app one) := let c' := cocone_parallel_pair_self f, z : c' ≅ c := is_colimit.unique_up_to_iso (is_colimit_cocone_parallel_pair_self f) h in is_iso.of_iso $ functor.map_iso (cocones.forget _) z /-- The coequalizer of (f, f) is an isomorphism -/ def coequalizer.π_of_self [has_colimit (parallel_pair f f)] : is_iso (coequalizer.π f f) := colimit_cocone_parallel_pair_self_is_iso _ _ $ colimit.is_colimit _ /-- Every coequalizer of (f, g), where f = g, is an isomorphism -/ def colimit_cocone_parallel_pair_self_is_iso' (c : cocone (parallel_pair f g)) (h₀ : is_colimit c) (h₁ : f = g) : is_iso (c.ι.app one) := begin rw cofork.eq_of_π_π c at *, have h₂ : is_colimit (cofork.of_π (c.ι.app one) rfl : cofork f f), by convert h₀, exact colimit_cocone_parallel_pair_self_is_iso f (cofork.of_π (c.ι.app one) rfl) h₂ end /-- The coequalizer of (f, g), where f = g, is an isomorphism -/ def coequalizer.π_of_self' [has_colimit (parallel_pair f g)] (h : f = g) : is_iso (coequalizer.π f g) := colimit_cocone_parallel_pair_self_is_iso' _ _ _ (colimit.is_colimit _) h /-- A coequalizer that is a monomorphism is an isomorphism -/ def mono_limit_cocone_parallel_pair_is_iso (c : cocone (parallel_pair f g)) (h : is_colimit c) [mono (c.ι.app one)] : is_iso (c.ι.app one) := colimit_cocone_parallel_pair_self_is_iso' f g c h $ (cancel_mono (c.ι.app one)).1 (cofork.condition c) end variables (C) /-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/ class has_equalizers := (has_limits_of_shape : has_limits_of_shape.{v} walking_parallel_pair C) /-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/ class has_coequalizers := (has_colimits_of_shape : has_colimits_of_shape.{v} walking_parallel_pair C) attribute [instance] has_equalizers.has_limits_of_shape has_coequalizers.has_colimits_of_shape /-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/ def has_equalizers_of_has_finite_limits [has_finite_limits.{v} C] : has_equalizers.{v} C := { has_limits_of_shape := infer_instance } /-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all coequalizers -/ def has_coequalizers_of_has_finite_colimits [has_finite_colimits.{v} C] : has_coequalizers.{v} C := { has_colimits_of_shape := infer_instance } end category_theory.limits
9d0c06d150c53f418566719ff2612994e3356ed4
a3d3bdc686e1395146a6eecc22431ac7fafb6bc7
/src/net/default.lean
9ea94e124c4c9e3e33ae426a9935784b141b2c1f
[ "Apache-2.0" ]
permissive
jroesch/net
c66581150cad7fc8f10fe1b5fecdae2912211f75
218eac82ea4a4956f63a01e88dc3d2fbbad406c8
refs/heads/master
1,606,948,723,891
1,499,287,492,000
1,499,287,492,000
96,160,509
0
0
null
null
null
null
UTF-8
Lean
false
false
1,026
lean
import system.io import system.ffi open io.ffi @[reducible] def tcp_listener : ffi.type := ffi.type.struct ffi.struct_body.empty @[reducible] def tcp_stream : ffi.type := ffi.type.struct ffi.struct_body.empty def tcp_listener.bind [io.interface] : string → nat → io (ref tcp_listener) := foreign "liblean_net.dylib" "tcp_listener_bind" tcp_listener [ffi.base_type.string, ffi.base_type.int] def tcp_listener.accept [io.interface] : ref tcp_listener → io (ref tcp_stream) := foreign "liblean_net.dylib" "tcp_listener_accept" tcp_stream [tcp_listener] def tcp_stream.write [io.interface] : ref tcp_stream → string → io nat := foreign "liblean_net.dylib" "tcp_stream_write" ffi.base_type.int [tcp_stream, ffi.base_type.string] def tcp_stream.read [io.interface] : ref tcp_stream → string → io nat := foreign "liblean_net.dylib" "tcp_stream_write" ffi.base_type.int [tcp_stream, ffi.base_type.string] def fork_io [io.interface] : io unit → io unit := foreign "liblean_net.dylib" "fork_io" (unit) [io unit]
dc5853852a72006101a303aaabb02507734256d8
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/set/countable.lean
51cbd298c7757c540a56cd0ef5a2f2da27d9feaa
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
8,388
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import data.equiv.list import data.set.finite /-! # Countable sets -/ noncomputable theory open function set encodable open classical (hiding some) open_locale classical universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace set /-- A set is countable if there exists an encoding of the set into the natural numbers. An encoding is an injection with a partial inverse, which can be viewed as a constructive analogue of countability. (For the most part, theorems about `countable` will be classical and `encodable` will be constructive.) -/ def countable (s : set α) : Prop := nonempty (encodable s) lemma countable_iff_exists_injective {s : set α} : countable s ↔ ∃f:s → ℕ, injective f := ⟨λ ⟨h⟩, by exactI ⟨encode, encode_injective⟩, λ ⟨f, h⟩, ⟨⟨f, partial_inv f, partial_inv_left h⟩⟩⟩ lemma countable_iff_exists_inj_on {s : set α} : countable s ↔ ∃ f : α → ℕ, inj_on f s := countable_iff_exists_injective.trans ⟨λ ⟨f, hf⟩, ⟨λ a, if h : a ∈ s then f ⟨a, h⟩ else 0, λ a b as bs h, congr_arg subtype.val $ hf $ by simpa [as, bs] using h⟩, λ ⟨f, hf⟩, ⟨_, inj_on_iff_injective.1 hf⟩⟩ lemma countable_iff_exists_surjective [ne : nonempty α] {s : set α} : countable s ↔ ∃f:ℕ → α, s ⊆ range f := ⟨λ ⟨h⟩, by inhabit α; exactI ⟨λ n, ((decode s n).map subtype.val).iget, λ a as, ⟨encode (⟨a, as⟩ : s), by simp [encodek]⟩⟩, λ ⟨f, hf⟩, ⟨⟨ λ x, inv_fun f x.1, λ n, if h : f n ∈ s then some ⟨f n, h⟩ else none, λ ⟨x, hx⟩, begin have := inv_fun_eq (hf hx), dsimp at this ⊢, simp [this, hx] end⟩⟩⟩ /-- A non-empty set is countable iff there exists a surjection from the natural numbers onto the subtype induced by the set. -/ lemma countable_iff_exists_surjective_to_subtype {s : set α} (hs : s.nonempty) : countable s ↔ ∃ f : ℕ → s, surjective f := have inhabited s, from ⟨classical.choice hs.to_subtype⟩, have countable s → ∃ f : ℕ → s, surjective f, from assume ⟨h⟩, by exactI ⟨λ n, (decode s n).iget, λ a, ⟨encode a, by simp [encodek]⟩⟩, have (∃ f : ℕ → s, surjective f) → countable s, from assume ⟨f, fsurj⟩, ⟨⟨inv_fun f, option.some ∘ f, by intro h; simp [(inv_fun_eq (fsurj h) : f (inv_fun f h) = h)]⟩⟩, by split; assumption /-- Convert `countable s` to `encodable s` (noncomputable). -/ def countable.to_encodable {s : set α} : countable s → encodable s := classical.choice lemma countable_encodable' (s : set α) [H : encodable s] : countable s := ⟨H⟩ lemma countable_encodable [encodable α] (s : set α) : countable s := ⟨by apply_instance⟩ /-- If `s : set α` is a nonempty countable set, then there exists a map `f : ℕ → α` such that `s = range f`. -/ lemma countable.exists_surjective {s : set α} (hc : countable s) (hs : s.nonempty) : ∃f:ℕ → α, s = range f := begin rcases hs with ⟨x, hx⟩, letI : encodable s := countable.to_encodable hc, letI : inhabited s := ⟨⟨x, hx⟩⟩, have : countable (univ : set s) := countable_encodable _, rcases countable_iff_exists_surjective.1 this with ⟨g, hg⟩, have : range g = univ := univ_subset_iff.1 hg, use coe ∘ g, rw [range_comp, this], simp only [image_univ, subtype.range_coe, mem_def] end @[simp] lemma countable_empty : countable (∅ : set α) := ⟨⟨λ x, x.2.elim, λ n, none, λ x, x.2.elim⟩⟩ @[simp] lemma countable_singleton (a : α) : countable ({a} : set α) := ⟨of_equiv _ (equiv.set.singleton a)⟩ lemma countable.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) : countable s₂ → countable s₁ | ⟨H⟩ := ⟨@of_inj _ _ H _ (embedding_of_subset _ _ h).2⟩ lemma countable.image {s : set α} (hs : countable s) (f : α → β) : countable (f '' s) := let f' : s → f '' s := λ⟨a, ha⟩, ⟨f a, mem_image_of_mem f ha⟩ in have hf' : surjective f', from assume ⟨b, a, ha, hab⟩, ⟨⟨a, ha⟩, subtype.eq hab⟩, ⟨@encodable.of_inj _ _ hs.to_encodable (surj_inv hf') (injective_surj_inv hf')⟩ lemma countable_range [encodable α] (f : α → β) : countable (range f) := by rw ← image_univ; exact (countable_encodable _).image _ lemma countable_of_injective_of_countable_image {s : set α} {f : α → β} (hf : inj_on f s) (hs : countable (f '' s)) : countable s := let ⟨g, hg⟩ := countable_iff_exists_inj_on.1 hs in countable_iff_exists_inj_on.2 ⟨g ∘ f, hg.comp hf (maps_to_image _ _)⟩ lemma countable_Union {t : α → set β} [encodable α] (ht : ∀a, countable (t a)) : countable (⋃a, t a) := by haveI := (λ a, (ht a).to_encodable); rw Union_eq_range_sigma; apply countable_range lemma countable.bUnion {s : set α} {t : Π x ∈ s, set β} (hs : countable s) (ht : ∀a∈s, countable (t a ‹_›)) : countable (⋃a∈s, t a ‹_›) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact countable_Union (by simpa using ht) end lemma countable.sUnion {s : set (set α)} (hs : countable s) (h : ∀a∈s, countable a) : countable (⋃₀ s) := by rw sUnion_eq_bUnion; exact hs.bUnion h lemma countable_Union_Prop {p : Prop} {t : p → set β} (ht : ∀h:p, countable (t h)) : countable (⋃h:p, t h) := by by_cases p; simp [h, ht] lemma countable.union {s₁ s₂ : set α} (h₁ : countable s₁) (h₂ : countable s₂) : countable (s₁ ∪ s₂) := by rw union_eq_Union; exact countable_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma countable.insert {s : set α} (a : α) (h : countable s) : countable (insert a s) := by { rw [set.insert_eq], exact (countable_singleton _).union h } lemma finite.countable {s : set α} : finite s → countable s | ⟨h⟩ := nonempty_of_trunc (by exactI trunc_encodable_of_fintype s) /-- The set of finite subsets of a countable set is countable. -/ lemma countable_set_of_finite_subset {s : set α} : countable s → countable {t | finite t ∧ t ⊆ s} | ⟨h⟩ := begin resetI, refine countable.mono _ (countable_range (λ t : finset s, {a | ∃ h:a ∈ s, subtype.mk a h ∈ t})), rintro t ⟨⟨ht⟩, ts⟩, resetI, refine ⟨finset.univ.map (embedding_of_subset _ _ ts), set.ext $ λ a, _⟩, suffices : a ∈ s ∧ a ∈ t ↔ a ∈ t, by simpa, exact ⟨and.right, λ h, ⟨ts h, h⟩⟩ end lemma countable_pi {π : α → Type*} [fintype α] {s : Πa, set (π a)} (hs : ∀a, countable (s a)) : countable {f : Πa, π a | ∀a, f a ∈ s a} := countable.mono (show {f : Πa, π a | ∀a, f a ∈ s a} ⊆ range (λf : Πa, s a, λa, (f a).1), from assume f hf, ⟨λa, ⟨f a, hf a⟩, funext $ assume a, rfl⟩) $ have trunc (encodable (Π (a : α), s a)), from @encodable.fintype_pi α _ _ _ (assume a, (hs a).to_encodable), trunc.induction_on this $ assume h, @countable_range _ _ h _ lemma countable_prod {s : set α} {t : set β} (hs : countable s) (ht : countable t) : countable (set.prod s t) := begin haveI : encodable s := hs.to_encodable, haveI : encodable t := ht.to_encodable, haveI : encodable (s × t) := by apply_instance, have : range (λp, ⟨p.1, p.2⟩ : s × t → α × β) = set.prod s t, { ext ⟨x, y⟩, simp only [exists_prop, set.mem_range, set_coe.exists, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, subtype.coe_mk, prod.exists], split, { rintros ⟨x', x's, y', y't, x'x, y'y⟩, simp [x'x.symm, y'y.symm, x's, y't] }, { rintros ⟨xs, yt⟩, exact ⟨x, xs, y, yt, rfl, rfl⟩ }}, rw ← this, exact countable_range _ end section enumerate /-- Enumerate elements in a countable set.-/ def enumerate_countable {s : set α} (h : countable s) (default : α) : ℕ → α := assume n, match @encodable.decode s (h.to_encodable) n with | (some y) := y | (none) := default end lemma subset_range_enumerate {s : set α} (h : countable s) (default : α) : s ⊆ range (enumerate_countable h default) := assume x hx, ⟨@encodable.encode s h.to_encodable ⟨x, hx⟩, by simp [enumerate_countable, encodable.encodek]⟩ end enumerate end set lemma finset.countable_to_set (s : finset α) : set.countable (↑s : set α) := s.finite_to_set.countable
53c1a64f4d958cc1026716ae641b69ac6a05e8ac
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/interactive/t7.lean
266750d1047781a71f416e6071655e282b0b9954
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
236
lean
import Int. (* import("tactic.lua") *) variable q : Int -> Int -> Bool. variable p : Int -> Bool. axiom Ax (a b : Int) (H : q a b) : p b. variable a : Int. theorem T (x : Int) : (q a x) → (p x). apply (Ax a). exact. done.
7324359fbe55460c7993edf0f7c8d8c605f569c4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/DSL/DeclUtil.lean
ae11f9733ab2307f745a80708a0edcd2d8b16e03
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,627
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Util.Binder import Lean.Parser.Command namespace Lake.DSL open Lean Parser Command abbrev DocComment := TSyntax ``docComment abbrev Attributes := TSyntax ``Term.attributes abbrev AttrInstance := TSyntax ``Term.attrInstance abbrev WhereDecls := TSyntax ``Term.whereDecls --- def expandAttrs (attrs? : Option Attributes) : Array AttrInstance := if let some attrs := attrs? then match attrs with | `(Term.attributes| @[$attrs,*]) => attrs | _ => #[] else #[] syntax structVal := "{" manyIndent(group(Term.structInstField ", "?)) "}" syntax declValDo := ppSpace Term.do (Term.whereDecls)? syntax declValStruct := ppSpace structVal (Term.whereDecls)? syntax declValTyped := Term.typeSpec declValSimple syntax declValOptTyped := (Term.typeSpec)? declValSimple syntax simpleDeclSig := ident Term.typeSpec declValSimple syntax structDeclSig := ident (Command.whereStructInst <|> declValOptTyped <|> declValStruct)? syntax bracketedSimpleBinder := "(" ident (" : " term)? ")" syntax simpleBinder := ident <|> bracketedSimpleBinder abbrev SimpleBinder := TSyntax ``simpleBinder open Lean.Parser.Term in def expandOptSimpleBinder (stx? : Option SimpleBinder) : MacroM FunBinder := do match stx? with | some stx => match stx with | `(simpleBinder| $id:ident) => `(funBinder| $id) | `(simpleBinder| ($id $[: $ty?]?)) => let ty := ty?.getD (← `(_)) `(funBinder| ($id : $ty)) | _ => `(funBinder| _) | none => `(funBinder| _) def fixName (id : Ident) : Option Name → Ident | some n => mkIdentFrom id n | none => id def mkConfigStructDecl (name? : Option Name) (doc? : Option DocComment) (attrs : Array AttrInstance) (ty : Term) : (spec : Syntax) → MacroM Syntax.Command | `(structDeclSig| $id:ident) => `($[$doc?]? @[$attrs,*] abbrev $(fixName id name?) : $ty := {name := $(quote id.getId)}) | `(structDeclSig| $id:ident where $ds;* $[$wds?]?) => `($[$doc?]? @[$attrs,*] abbrev $(fixName id name?) : $ty where name := $(quote id.getId); $ds;* $[$wds?]?) | `(structDeclSig| $id:ident $[: $ty?]? := $defn $[$wds?]?) => `($[$doc?]? @[$attrs,*] abbrev $(fixName id name?) : $(ty?.getD ty) := $defn $[$wds?]?) | `(structDeclSig| $id:ident { $[$fs $[,]?]* } $[$wds?]?) => do let defn ← `({ name := $(quote id.getId), $fs,* }) `($[$doc?]? @[$attrs,*] abbrev $(fixName id name?) : $ty := $defn $[$wds?]?) | stx => Macro.throwErrorAt stx "ill-formed configuration syntax"
38157fa5eb389d4dcfd490a84842eb951b9add85
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/data/equiv/mul_add.lean
a49c171e484056d4919174a25033f73650dafb4f
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,495
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, Callum Sutton, Yury Kudryashov -/ import algebra.group.hom import algebra.group.type_tags import algebra.group.units_hom import algebra.group_with_zero /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. ## Notations * ``infix ` ≃* `:25 := mul_equiv`` * ``infix ` ≃+ `:25 := add_equiv`` The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. ## Tags equiv, mul_equiv, add_equiv -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {G : Type*} {H : Type*} /-- Makes a multiplicative inverse from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive inverse from a bijection which preserves addition."] def mul_hom.inverse [has_mul M] [has_mul N] (f : mul_hom M N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : mul_hom N M := { to_fun := g, map_mul' := λ x y, calc g (x * y) = g (f (g x) * f (g y)) : by rw [h₂ x, h₂ y] ... = g (f (g x * g y)) : by rw f.map_mul ... = g x * g y : h₁ _, } /-- The inverse of a bijective `monoid_hom` is a `monoid_hom`. -/ @[to_additive "The inverse of a bijective `add_monoid_hom` is an `add_monoid_hom`.", simps] def monoid_hom.inverse {A B : Type*} [monoid A] [monoid B] (f : A →* B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : B →* A := { to_fun := g, map_one' := by rw [← f.map_one, h₁], .. (f : mul_hom A B).inverse g h₁ h₂, } set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ @[ancestor equiv add_hom] structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- The `add_hom` underlying a `add_equiv`. -/ add_decl_doc add_equiv.to_add_hom /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[ancestor equiv mul_hom, to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv /-- The `mul_hom` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_mul_hom infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] [has_mul Q] @[simp, to_additive] lemma to_fun_eq_coe {f : M ≃* N} : f.to_fun = f := rfl @[simp, to_additive] lemma coe_to_equiv {f : M ≃* N} : ⇑f.to_equiv = f := rfl @[simp, to_additive] lemma coe_to_mul_hom {f : M ≃* N} : ⇑f.to_mul_hom = f := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} @[to_additive] instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := (h.to_mul_hom.inverse h.to_equiv.symm h.left_inv h.right_inv).map_mul, .. h.to_equiv.symm} /-- See Note [custom simps projection] -/ -- we don't hyperlink the note in the additive version, since that breaks syntax highlighting -- in the whole file. @[to_additive "See Note custom simps projection"] def simps.symm_apply (e : M ≃* N) : N → M := e.symm initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply) initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] lemma symm_symm : ∀ (f : M ≃* N), f.symm.symm = f | ⟨f, g, h₁, h₂, h₃⟩ := rfl @[to_additive] lemma symm_bijective : function.bijective (symm : (M ≃* N) → (N ≃* M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp, to_additive] theorem symm_mk (f : M → N) (g h₁ h₂ h₃) : (mul_equiv.mk f g h₁ h₂ h₃).symm = { to_fun := g, inv_fun := f, ..(mul_equiv.mk f g h₁ h₂ h₃).symm} := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem symm_comp_self (e : M ≃* N) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp, to_additive] theorem self_comp_symm (e : M ≃* N) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp, to_additive] theorem coe_refl : ⇑(refl M) = id := rfl @[to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem coe_trans (e₁ : M ≃* N) (e₂ : N ≃* P) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end attribute [ext] add_equiv.ext @[to_additive] lemma ext_iff {f g : mul_equiv M N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ @[simp, to_additive] lemma mk_coe (e : M ≃* N) (e' h₁ h₂ h₃) : (⟨e, e', h₁, h₂, h₃⟩ : M ≃* N) = e := ext $ λ _, rfl @[simp, to_additive] lemma mk_coe' (e : M ≃* N) (f h₁ h₂ h₃) : (mul_equiv.mk f ⇑e h₁ h₂ h₃ : N ≃* M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[to_additive] protected lemma congr_arg {f : mul_equiv M N} : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl @[to_additive] protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := h ▸ rfl /-- The `mul_equiv` between two monoids with a unique element. -/ @[to_additive "The `add_equiv` between two add_monoids with a unique element."] def mul_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_mul M] [has_mul N] : M ≃* N := { map_mul' := λ _ _, subsingleton.elim _ _, ..equiv_of_unique_of_unique } /-- There is a unique monoid homomorphism between two monoids with a unique element. -/ @[to_additive] instance {M N} [unique M] [unique N] [has_mul M] [has_mul N] : unique (M ≃* N) := { default := mul_equiv_of_unique_of_unique , uniq := λ _, ext $ λ x, subsingleton.elim _ _} /-! ## Monoids -/ /-- A multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism). -/ @[simp, to_additive] lemma map_one {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq @[to_additive] lemma map_ne_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [mul_one_class M] [mul_one_class N] (f : M →* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma coe_to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (e : M ≃* N) : ⇑e.to_monoid_hom = e := rfl @[to_additive] lemma to_monoid_hom_injective {M N} [mul_one_class M] [mul_one_class N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) := λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h) /-- A multiplicative analogue of `equiv.arrow_congr`, where the equivalence between the targets is multiplicative. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, where the equivalence between the targets is additive.", simps apply] def arrow_congr {M N P Q : Type*} [mul_one_class P] [mul_one_class Q] (f : M ≃ N) (g : P ≃* Q) : (M → P) ≃* (N → Q) := { to_fun := λ h n, g (h (f.symm n)), inv_fun := λ k m, g.symm (k (f m)), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A multiplicative analogue of `equiv.arrow_congr`, for multiplicative maps from a monoid to a commutative monoid. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, for additive maps from an additive monoid to a commutative additive monoid.", simps apply] def monoid_hom_congr {M N P Q} [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q] (f : M ≃* N) (g : P ≃* Q) : (M →* P) ≃* (N →* Q) := { to_fun := λ h, g.to_monoid_hom.comp (h.comp f.symm.to_monoid_hom), inv_fun := λ k, g.symm.to_monoid_hom.comp (k.comp f.to_monoid_hom), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A family of multiplicative equivalences `Π j, (Ms j ≃* Ns j)` generates a multiplicative equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `mul_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `mul_equiv.arrow_congr`. -/ @[to_additive add_equiv.Pi_congr_right "A family of additive equivalences `Π j, (Ms j ≃+ Ns j)` generates an additive equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `add_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `add_equiv.arrow_congr`.", simps apply] def Pi_congr_right {η : Type*} {Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Π j, Ms j) ≃* (Π j, Ns j) := { to_fun := λ x j, es j (x j), inv_fun := λ x j, (es j).symm (x j), map_mul' := λ x y, funext $ λ j, (es j).map_mul (x j) (y j), .. equiv.Pi_congr_right (λ j, (es j).to_equiv) } @[simp] lemma Pi_congr_right_refl {η : Type*} {Ms : η → Type*} [Π j, mul_one_class (Ms j)] : Pi_congr_right (λ j, mul_equiv.refl (Ms j)) = mul_equiv.refl _ := rfl @[simp] lemma Pi_congr_right_symm {η : Type*} {Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Pi_congr_right es).symm = (Pi_congr_right $ λ i, (es i).symm) := rfl @[simp] lemma Pi_congr_right_trans {η : Type*} {Ms Ns Ps : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] [Π j, mul_one_class (Ps j)] (es : ∀ j, Ms j ≃* Ns j) (fs : ∀ j, Ns j ≃* Ps j) : (Pi_congr_right es).trans (Pi_congr_right fs) = (Pi_congr_right $ λ i, (es i).trans (fs i)) := rfl /-! # Groups -/ /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x end mul_equiv -- We don't use `to_additive` to generate definition because it fails to tell Lean about -- equational lemmas /-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive monoid homomorphisms. -/ def add_monoid_hom.to_add_equiv [add_zero_class M] [add_zero_class N] (f : M →+ N) (g : N →+ M) (h₁ : g.comp f = add_monoid_hom.id _) (h₂ : f.comp g = add_monoid_hom.id _) : M ≃+ N := { to_fun := f, inv_fun := g, left_inv := add_monoid_hom.congr_fun h₁, right_inv := add_monoid_hom.congr_fun h₂, map_add' := f.map_add } /-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/ @[to_additive, simps {fully_applied := ff}] def monoid_hom.to_mul_equiv [mul_one_class M] [mul_one_class N] (f : M →* N) (g : N →* M) (h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) : M ≃* N := { to_fun := f, inv_fun := g, left_inv := monoid_hom.congr_fun h₁, right_inv := monoid_hom.congr_fun h₂, map_mul' := f.map_mul } /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } @[simp, to_additive coe_to_add_units] lemma coe_to_units [group G] (g : G) : (to_units g : G) = g := rfl protected lemma group.is_unit {G} [group G] (x : G) : is_unit x := (to_units x).is_unit namespace units @[simp, to_additive] lemma coe_inv [group G] (u : units G) : ↑u⁻¹ = (u⁻¹ : G) := to_units.symm.map_inv u variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_left (u : units M) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_right (u : units M) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G → G) = (*) a⁻¹ := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G → G) = λ x, x * a⁻¹ := rfl attribute [nolint simp_nf] add_left_symm_apply add_right_symm_apply variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type.", simps apply {fully_applied := ff}] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end group section group_with_zero variables [group_with_zero G] /-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_left' (a : G) (ha : a ≠ 0) : perm G := { to_fun := λ x, a * x, inv_fun := λ x, a⁻¹ * x, left_inv := λ x, by { dsimp, rw [← mul_assoc, inv_mul_cancel ha, one_mul] }, right_inv := λ x, by { dsimp, rw [← mul_assoc, mul_inv_cancel ha, one_mul] } } /-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_right' (a : G) (ha : a ≠ 0) : perm G := { to_fun := λ x, x * a, inv_fun := λ x, x * a⁻¹, left_inv := λ x, by { dsimp, rw [mul_assoc, mul_inv_cancel ha, mul_one] }, right_inv := λ x, by { dsimp, rw [mul_assoc, inv_mul_cancel ha, mul_one] } } end group_with_zero end equiv /-- When the group is commutative, `equiv.inv` is a `mul_equiv`. There is a variant of this `mul_equiv.inv' G : G ≃* Gᵒᵖ` for the non-commutative case. -/ @[to_additive "When the `add_group` is commutative, `equiv.neg` is an `add_equiv`."] def mul_equiv.inv (G : Type*) [comm_group G] : G ≃* G := { to_fun := has_inv.inv, inv_fun := has_inv.inv, map_mul' := mul_inv, ..equiv.inv G} section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_zero_class G] [add_zero_class H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [mul_one_class G] [mul_one_class H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [mul_one_class G] [add_zero_class H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [mul_one_class G] [add_zero_class H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_zero_class G] [mul_one_class H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_zero_class G] [mul_one_class H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags
6f9e0aea9b598e93339d0cbb7e7171afc3768f2c
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/tactic/omega/int/main.lean
bb682d46ca650e3f83ad2c0723df281cd4404a61
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
2,441
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Main procedure for linear integer arithmetic. -/ import tactic.omega.prove_unsats import tactic.omega.int.dnf open tactic namespace omega namespace int open_locale omega.int run_cmd mk_simp_attr `sugar attribute [sugar] ne not_le not_lt int.lt_iff_add_one_le or_false false_or and_true true_and ge gt mul_add add_mul one_mul mul_one mul_comm sub_eq_add_neg classical.imp_iff_not_or classical.iff_iff_not_or_and_or_not meta def desugar := `[try {simp only with sugar}] lemma univ_close_of_unsat_clausify (m : nat) (p : form) : clauses.unsat (dnf (¬* p)) → univ_close p (λ x, 0) m | h1 := begin apply univ_close_of_valid, apply valid_of_unsat_not, apply unsat_of_clauses_unsat, exact h1 end /- Given a (p : form), return the expr of a (t : univ_close m p) -/ meta def prove_univ_close (m : nat) (p : form) : tactic expr := do x ← prove_unsats (dnf (¬*p)), return `(univ_close_of_unsat_clausify %%`(m) %%`(p) %%x) meta def to_preterm : expr → tactic preterm | (expr.var k) := return (preterm.var 1 k) | `(-%%(expr.var k)) := return (preterm.var (-1 : int) k) | `(%%(expr.var k) * %%zx) := do z ← eval_expr int zx, return (preterm.var z k) | `(%%t1x + %%t2x) := do t1 ← to_preterm t1x, t2 ← to_preterm t2x, return (preterm.add t1 t2) | zx := do z ← eval_expr int zx, return (preterm.cst z) meta def to_form_core : expr → tactic form | `(%%tx1 = %%tx2) := do t1 ← to_preterm tx1, t2 ← to_preterm tx2, return (t1 =* t2) | `(%%tx1 ≤ %%tx2) := do t1 ← to_preterm tx1, t2 ← to_preterm tx2, return (t1 ≤* t2) | `(¬ %%px) := do p ← to_form_core px, return (¬* p) | `(%%px ∨ %%qx) := do p ← to_form_core px, q ← to_form_core qx, return (p ∨* q) | `(%%px ∧ %%qx) := do p ← to_form_core px, q ← to_form_core qx, return (p ∧* q) | x := trace "Cannot reify expr : " >> trace x >> failed meta def to_form : nat → expr → tactic (form × nat) | m `(_ → %%px) := to_form (m+1) px | m x := do p ← to_form_core x, return (p,m) meta def prove_lia : tactic expr := do (p,m) ← target >>= to_form 0, prove_univ_close m p end int end omega open omega.int meta def omega_int : tactic unit := desugar >> (done <|> (prove_lia >>= apply >> skip))
d23c4edfaad3d0ed95db1c9a6485fa6cc65d3850
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/choice_expl.lean
3675652b853f05fd43b61ba12aa0a7a2b7f3a138
[ "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
216
lean
namespace N1 definition pr {A : Type} (a b : A) := a end N1 namespace N2 definition pr {A : Type} (a b : A) := b end N2 open N1 N2 constant N : Type.{1} constants a b : N check @pr check @pr N a b check pr a b
936bdfda94c1ea2473836fa896902f925c6a6b6a
2bcbdeab635db56197a16c5be109c51449ec13f5
/graph/path.lean
f4a75d962b6218613331fdb68a8066546e7a1be9
[ "MIT" ]
permissive
tizmd/lean-graph
9c54cda519ab3132694de8706f6073c355e398cb
2acec9770ff71bb946f69e2a8f2bfa87a51f15d9
refs/heads/master
1,594,597,312,192
1,558,412,086,000
1,558,412,086,000
94,286,459
0
0
null
null
null
null
UTF-8
Lean
false
false
8,774
lean
import data.list universes u₀ u₁ variables {α : Type u₀} def {u v} source {α : Type u}{R : α → α → Type v} {x y}: R x y → α := λ _, x def {u v} target {α : Type u}{R : α → α → Type v} {x y}: R x y → α := λ _, y inductive path (R : α → α → Sort u₁) : α → α → Type (max u₀ u₁) | nil {} : Π {x}, path x x | cons : Π {x y z}, R x y → path y z → path x z namespace path variables {R : α → α → Sort u₁} def singleton {x y} : R x y → path R x y := λ e, cons e nil def length : Π{x y}, path R x y → ℕ | _ _ nil := 0 | _ _ (cons _ p) := 1 + length p def append : Π {x y z}, path R x y → path R y z → path R x z | _ _ _ nil p := p | _ _ _ (cons e p₁) p₂ := cons e (append p₁ p₂) lemma nil_append {x y}{p : path R x y} : append nil p = p := rfl @[simp] lemma append_nil : Π {x y}{p : path R x y}, append p nil = p | _ ._ nil := rfl | _ _ (cons _ p) := congr_arg (cons _) append_nil @[simp] lemma append_assoc : Π {w x y z}{p₁ : path R w x}{p₂ : path R x y}{p₃ : path R y z}, append (append p₁ p₂) p₃ = append p₁ (append p₂ p₃) | _ ._ _ _ nil p₂ p₃ := rfl | _ _ _ _ (cons e p₁) p₂ p₃ := begin simp [append], apply append_assoc end @[simp] lemma length_append : Π {x y z}{p₁ : path R x y}{p₂ : path R y z}, length (append p₁ p₂) = p₁.length + p₂.length | _ ._ _ nil _ := by simp [append, length] | _ _ _ (cons e p₁) p₂ := begin simp [append, length], rw length_append, cc end def concat : Π {x y z}, path R x y → R y z → path R x z | _ .(_) _ nil e := singleton e | _ _ _ (cons e₁ p) e₂ := cons e₁ (concat p e₂) lemma concat_append : Π {w x y z}{p₁ : path R w x}{p₂ : path R x y}{e : R y z}, concat (append p₁ p₂) e = append p₁ (concat p₂ e) | _ ._ _ _ nil p₂ _ := rfl | _ _ _ _ (cons e₁ p₁) p₂ e₂ := begin simp [append, concat], rw concat_append end @[reducible] def targets : Π {x y}, path R x y → list α | .(_) _ nil := [] | _ _ (@cons _ _ _ x _ _ p) := x :: targets p @[reducible] def sources : Π {x y}, path R x y → list α | .(_) _ nil := [] | x _ (cons _ p) := x :: sources p @[reducible,inline] def occurrences {x y} : path R x y → list α := λ p, x :: targets p lemma source_mem_occurrences {x y}(p : path R x y) : x ∈ occurrences p := list.mem_cons_self _ _ lemma target_mem_occurrences : Π{x y}(p : path R x y), y ∈ occurrences p | _ ._ nil := list.mem_cons_self _ _ | _ _ (cons e p) := list.mem_cons_of_mem _ (target_mem_occurrences _) lemma occurrences_eq_concat_sources : Π {x y}(p : path R x y), occurrences p = list.concat (sources p) y | _ ._ nil := rfl | x _ (cons e p) := congr_arg (λ xs, x :: xs) (occurrences_eq_concat_sources p) @[simp] lemma occurrences_cons {x y z}(e : R x y)(p : path R y z) : occurrences (cons e p) = x :: occurrences p := rfl lemma occurrences_concat : Π {x y z}(p : path R x y)(e : R y z), occurrences (concat p e) = list.concat (occurrences p) z | x ._ z nil e := rfl | x _ z (cons e₁ p) e₂ := congr_arg (λ xs, x :: xs) (occurrences_concat p e₂) lemma length_occurrences : Π{x y}(p : path R x y), p.occurrences.length = 1 + p.length | _ _ nil := by trivial | _ _ (cons e p) := have iH : p.occurrences.length = 1 + p.length, from length_occurrences p, begin simp [length], simp at iH, assumption end lemma occurrences_append_targets : Π {x y z}(p₁ : path R x y)(p₂ : path R y z), occurrences (append p₁ p₂) = occurrences p₁ ++ targets p₂ | _ ._ _ nil p := rfl | x y z (@cons ._ ._ ._ w ._ e p₁) p₂ := begin have iH : occurrences (append p₁ p₂) = occurrences p₁ ++ targets p₂, from occurrences_append_targets p₁ p₂, simp at iH, simp [targets, append], assumption end lemma occurrences_append_sources {x y z}(p₁ : path R x y)(p₂ : path R y z) : occurrences (append p₁ p₂) = sources p₁ ++ occurrences p₂ := begin simp [occurrences], change occurrences (append p₁ p₂) = sources p₁ ++ ([y] ++ targets p₂), rw ←list.append_assoc, rw ←list.concat_eq_append, rw ←occurrences_eq_concat_sources, apply occurrences_append_targets end def rewind_path (R) : α → α → Type _ := function.swap (path (function.swap R)) def rewind : Π {x y}, path R x y → rewind_path R x y | _ .(_) nil := nil | _ _ (cons e p) := concat (rewind p) e def occurrences_rewind : Π {x y} {p : path R x y}, p.rewind.occurrences = p.occurrences.reverse | _ ._ nil := rfl | x y (cons e p) := begin unfold rewind, rw occurrences_concat, rw occurrences_rewind, simp end lemma rewind_concat : Π {x y z}{p : path R x y}{e : R y z}, rewind (concat p e) = cons e (rewind p) | _ ._ _ nil _ := rfl | _ _ _ (cons e₁ p) e₂ := begin unfold concat, unfold rewind, rw rewind_concat, refl end lemma rewind_rewind : Π {x y}{p : path R x y}, p.rewind.rewind = p | _ ._ nil := rfl | _ _ (cons e p) := begin unfold rewind, rw rewind_concat, rw rewind_rewind end lemma rewind_append : Π {x y z}{p₁ : path R x y}{p₂ : path R y z}, rewind (append p₁ p₂) = append p₂.rewind p₁.rewind | _ ._ _ nil _ := by simp [rewind,append] | _ _ _ (cons e p₁) p₂ := begin unfold append, unfold rewind, rw rewind_append, apply concat_append end def split [deq : decidable_eq α] : Π {x y z} {p : path R x y}, z ∈ occurrences p → Σ' (p₁ : path R x z) (p₂ : path R z y), p = append p₁ p₂ ∧ z ∉ sources p₁ := begin intros x y z p h, induction p with x x w y e p iH, { simp [occurrences, targets] at h, rw h, exact ⟨nil, nil, rfl, list.not_mem_nil _⟩ }, { cases (deq z x) with Hne Heq, { simp [occurrences, targets] at h, have H : z ∈ occurrences p, apply or.resolve_left h Hne, cases (iH H) with p₁ rest, cases rest with p₂ Hp, exact ⟨cons e p₁, p₂, begin rw Hp.left, refl end, list.not_mem_cons_of_ne_of_not_mem Hne Hp.right⟩ }, { rw Heq, exact ⟨nil, cons e p, rfl, list.not_mem_nil _⟩ } } end @[reducible] def is_simple {x y}(p : path R x y) : Prop := list.nodup (occurrences p) def simple_path (R) := λ x y : α, { p : path R x y // is_simple p} instance {x y} : has_coe (simple_path R x y) (path R x y) := ⟨subtype.val⟩ lemma nil_is_simple {x : α} : is_simple (@nil _ R x) := list.nodup_singleton _ lemma is_simple_of_is_simple_append_left {x y z}{p₁ : path R x y}{p₂ : path R y z} : is_simple (append p₁ p₂) → is_simple p₁ := begin unfold is_simple, rw occurrences_append_targets, apply list.nodup_of_nodup_append_left end lemma is_simple_of_is_simple_append_right {x y z}{p₁ : path R x y}{p₂ : path R y z} : is_simple (append p₁ p₂) → is_simple p₂ := begin unfold is_simple, rw occurrences_append_sources, apply list.nodup_of_nodup_append_right end def is_simple_rewind_of_is_simple {x y} {p : path R x y} : is_simple p → is_simple p.rewind := begin intro H, unfold is_simple at *, rw [occurrences_rewind, list.nodup_reverse], assumption end def reduce_cycle [decidable_eq α] : Π {x y} (p : path R x y), Σ' (sp : simple_path R x y), occurrences sp.val <+ occurrences p | _ ._ nil := ⟨⟨nil, nil_is_simple⟩ , by trivial⟩ | x y (cons e p) := let ⟨sp , sub_sp⟩ := reduce_cycle p in match list.decidable_mem x sp.1.occurrences with | is_false x_not_in_sp := ⟨⟨cons e sp.1 , begin unfold is_simple, simp only [occurrences], simp at x_not_in_sp, rw list.nodup_cons, split, { simp, have H: list.nodup (sp.1.occurrences), apply sp.2, simp at H, trivial}, {apply sp.2} end ⟩ , begin apply list.sublist.cons2, assumption end ⟩ | is_true x_in_sp := let ⟨sp₁, sp₂ , Hsp, Hnmem ⟩ := split x_in_sp in have simple_sp₂ : is_simple sp₂, from begin apply is_simple_of_is_simple_append_right, rw ←Hsp, apply sp.2, end, let ret : simple_path R x y := ⟨sp₂, simple_sp₂⟩ in have sp₂_sub : occurrences (ret.1) <+ occurrences (cons e p), from begin transitivity, { apply list.sublist_append_right, exact (sources sp₁), }, { rw ←occurrences_append_sources, rw ←Hsp, apply list.sublist.cons, apply sub_sp } end, ⟨ret , sp₂_sub⟩ end def to_simple_path [decidable_eq α] {x y} : path R x y → simple_path R x y := λ p, (reduce_cycle p).1 def is_nonempty : Π {x y}(p : path R x y ), Prop | _ ._ nil := false | _ _ _ := true end path