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
dc35eeecd55854578a60cd11ba30b9f5a1fe5ef0
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/transport.lean
00d8d3d08e0ac599c7e2095cd4954a6bfea1aefc
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
565
lean
import .tactics lemma {u v} congr_refl {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} (h₁ : f₁ = f₂) (a : α) : congr h₁ (eq.refl a) = congr_fun h₁ a := begin reflexivity, end lemma {u v} symm_congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : eq.symm (congr_fun h a) = congr_fun (eq.symm h) a := begin reflexivity, end -- lemma hfunext {α₁ : Type} {β₁ : Type} {α₂ : Type} {β₂ : Type} { f₁ : α₁ → β₁ } { f₂ : α₂ → β₂ } (hα : α₁ = α₂) : f₁ == f₂ := -- begin -- end
5ed6b3593f189f7b415367a61215590a5f66fe96
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/fundamental_groupoid/product.lean
d3c3594941a8379f2aec78108afa8bf7cd77838a
[ "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
7,427
lean
/- Copyright (c) 2022 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import category_theory.groupoid import algebraic_topology.fundamental_groupoid.basic import topology.category.Top.limits import topology.homotopy.product /-! # Fundamental groupoid preserves products In this file, we give the following definitions/theorems: - `fundamental_groupoid_functor.pi_iso` An isomorphism between Π i, (π Xᵢ) and π (Πi, Xᵢ), whose inverse is precisely the product of the maps π (Π i, Xᵢ) → π (Xᵢ), each induced by the projection in `Top` Π i, Xᵢ → Xᵢ. - `fundamental_groupoid_functor.prod_iso` An isomorphism between πX × πY and π (X × Y), whose inverse is precisely the product of the maps π (X × Y) → πX and π (X × Y) → Y, each induced by the projections X × Y → X and X × Y → Y - `fundamental_groupoid_functor.preserves_product` A proof that the fundamental groupoid functor preserves all products. -/ noncomputable theory namespace fundamental_groupoid_functor open_locale fundamental_groupoid universes u section pi variables {I : Type u} (X : I → Top.{u}) /-- The projection map Π i, X i → X i induces a map π(Π i, X i) ⟶ π(X i). -/ def proj (i : I) : πₓ (Top.of (Π i, X i)) ⥤ πₓ (X i) := πₘ ⟨_, continuous_apply i⟩ /-- The projection map is precisely path.homotopic.proj interpreted as a functor -/ @[simp] lemma proj_map (i : I) (x₀ x₁ : πₓ (Top.of (Π i, X i))) (p : x₀ ⟶ x₁) : (proj X i).map p = (@path.homotopic.proj _ _ _ _ _ i p) := rfl /-- The map taking the pi product of a family of fundamental groupoids to the fundamental groupoid of the pi product. This is actually an isomorphism (see `pi_iso`) -/ @[simps] def pi_to_pi_Top : (Π i, πₓ (X i)) ⥤ πₓ (Top.of (Π i, X i)) := { obj := λ g, g, map := λ v₁ v₂ p, path.homotopic.pi p, map_id' := begin intro x, change path.homotopic.pi (λ i, 𝟙 (x i)) = _, simp only [fundamental_groupoid.id_eq_path_refl, path.homotopic.pi_lift], refl, end, map_comp' := λ x y z f g, (path.homotopic.comp_pi_eq_pi_comp f g).symm, } /-- Shows `pi_to_pi_Top` is an isomorphism, whose inverse is precisely the pi product of the induced projections. This shows that `fundamental_groupoid_functor` preserves products. -/ @[simps] def pi_iso : category_theory.Groupoid.of (Π i : I, πₓ (X i)) ≅ πₓ (Top.of (Π i, X i)) := { hom := pi_to_pi_Top X, inv := category_theory.functor.pi' (proj X), hom_inv_id' := begin change pi_to_pi_Top X ⋙ (category_theory.functor.pi' (proj X)) = 𝟭 _, apply category_theory.functor.ext; intros, { ext, simp, }, { refl, }, end, inv_hom_id' := begin change (category_theory.functor.pi' (proj X)) ⋙ pi_to_pi_Top X = 𝟭 _, apply category_theory.functor.ext; intros, { suffices : path.homotopic.pi ((category_theory.functor.pi' (proj X)).map f) = f, { simpa, }, change (category_theory.functor.pi' (proj X)).map f with λ i, (category_theory.functor.pi' (proj X)).map f i, simp, }, { refl, } end } section preserves open category_theory /-- Equivalence between the categories of cones over the objects `π Xᵢ` written in two ways -/ def cone_discrete_comp : limits.cone (discrete.functor X ⋙ π) ≌ limits.cone (discrete.functor (λ i, πₓ (X i))) := limits.cones.postcompose_equivalence (discrete.comp_nat_iso_discrete X π) lemma cone_discrete_comp_obj_map_cone : (cone_discrete_comp X).functor.obj ((π).map_cone (Top.pi_fan.{u} X)) = limits.fan.mk (πₓ (Top.of (Π i, X i))) (proj X) := rfl /-- This is `pi_iso.inv` as a cone morphism (in fact, isomorphism) -/ def pi_Top_to_pi_cone : (limits.fan.mk (πₓ (Top.of (Π i, X i))) (proj X)) ⟶ Groupoid.pi_limit_fan (λ i : I, (πₓ (X i))) := { hom := category_theory.functor.pi' (proj X) } instance : is_iso (pi_Top_to_pi_cone X) := begin haveI : is_iso (pi_Top_to_pi_cone X).hom := (infer_instance : is_iso (pi_iso X).inv), exact limits.cones.cone_iso_of_hom_iso (pi_Top_to_pi_cone X), end /-- The fundamental groupoid functor preserves products -/ def preserves_product : limits.preserves_limit (discrete.functor X) π := begin apply limits.preserves_limit_of_preserves_limit_cone (Top.pi_fan_is_limit.{u} X), apply (limits.is_limit.of_cone_equiv (cone_discrete_comp X)).to_fun, simp only [cone_discrete_comp_obj_map_cone], apply limits.is_limit.of_iso_limit _ (as_iso (pi_Top_to_pi_cone X)).symm, exact Groupoid.pi_limit_fan_is_limit _, end end preserves end pi section prod variables (A B : Top.{u}) /-- The induced map of the left projection map X × Y → X -/ def proj_left : πₓ (Top.of (A × B)) ⥤ πₓ A := πₘ ⟨_, continuous_fst⟩ /-- The induced map of the right projection map X × Y → Y -/ def proj_right : πₓ (Top.of (A × B)) ⥤ πₓ B := πₘ ⟨_, continuous_snd⟩ @[simp] lemma proj_left_map (x₀ x₁ : πₓ (Top.of (A × B))) (p : x₀ ⟶ x₁) : (proj_left A B).map p = path.homotopic.proj_left p := rfl @[simp] lemma proj_right_map (x₀ x₁ : πₓ (Top.of (A × B))) (p : x₀ ⟶ x₁) : (proj_right A B).map p = path.homotopic.proj_right p := rfl /-- The map taking the product of two fundamental groupoids to the fundamental groupoid of the product of the two topological spaces. This is in fact an isomorphism (see `prod_iso`). -/ @[simps obj] def prod_to_prod_Top : (πₓ A) × (πₓ B) ⥤ πₓ (Top.of (A × B)) := { obj := λ g, g, map := λ x y p, match x, y, p with | (x₀, x₁), (y₀, y₁), (p₀, p₁) := path.homotopic.prod p₀ p₁ end, map_id' := begin rintro ⟨x₀, x₁⟩, simp only [category_theory.prod_id, fundamental_groupoid.id_eq_path_refl], unfold_aux, rw path.homotopic.prod_lift, refl, end, map_comp' := λ x y z f g, match x, y, z, f, g with | (x₀, x₁), (y₀, y₁), (z₀, z₁), (f₀, f₁), (g₀, g₁) := (path.homotopic.comp_prod_eq_prod_comp f₀ f₁ g₀ g₁).symm end } lemma prod_to_prod_Top_map {x₀ x₁ : πₓ A} {y₀ y₁ : πₓ B} (p₀ : x₀ ⟶ x₁) (p₁ : y₀ ⟶ y₁) : @category_theory.functor.map _ _ _ _ (prod_to_prod_Top A B) (x₀, y₀) (x₁, y₁) (p₀, p₁) = path.homotopic.prod p₀ p₁ := rfl /-- Shows `prod_to_prod_Top` is an isomorphism, whose inverse is precisely the product of the induced left and right projections. -/ @[simps] def prod_iso : category_theory.Groupoid.of ((πₓ A) × (πₓ B)) ≅ (πₓ (Top.of (A × B))) := { hom := prod_to_prod_Top A B, inv := (proj_left A B).prod' (proj_right A B), hom_inv_id' := begin change prod_to_prod_Top A B ⋙ ((proj_left A B).prod' (proj_right A B)) = 𝟭 _, apply category_theory.functor.hext, { intros, ext; simp; refl, }, rintros ⟨x₀, x₁⟩ ⟨y₀, y₁⟩ ⟨f₀, f₁⟩, have := and.intro (path.homotopic.proj_left_prod f₀ f₁) (path.homotopic.proj_right_prod f₀ f₁), simpa, end, inv_hom_id' := begin change ((proj_left A B).prod' (proj_right A B)) ⋙ prod_to_prod_Top A B = 𝟭 _, apply category_theory.functor.hext, { intros, ext; simp; refl, }, rintros ⟨x₀, x₁⟩ ⟨y₀, y₁⟩ f, have := path.homotopic.prod_proj_left_proj_right f, simpa, end } end prod end fundamental_groupoid_functor
c9950d1752ebb07446917bc5d4c255f3f5f5ba3e
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/deprecated/subring.lean
a786a26c885ae231dc4752073fac2a725c99a0b4
[ "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
8,294
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import deprecated.subgroup import deprecated.group universes u v open group variables {R : Type u} [ring R] section prio set_option default_priority 100 -- see Note [default priority] /-- `S` is a subring: a set containing 1 and closed under multiplication, addition and and additive inverse. -/ class is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop. end prio instance subset.ring {S : set R} [is_subring S] : ring S := { left_distrib := λ x y z, subtype.eq $ left_distrib x.1 y.1 z.1, right_distrib := λ x y z, subtype.eq $ right_distrib x.1 y.1 z.1, .. subtype.add_comm_group, .. subtype.monoid } instance subtype.ring {S : set R} [is_subring S] : ring (subtype S) := subset.ring namespace ring_hom instance is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] : is_subring (f ⁻¹' s) := {} instance is_subring_image {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set R) [is_subring s] : is_subring (f '' s) := {} instance is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : is_subring (set.range f) := {} end ring_hom /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def ring_hom.cod_restrict {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } /-- Coersion `S → R` as a ring homormorphism-/ def is_subring.subtype (S : set R) [is_subring S] : S →+* R := ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ @[simp] lemma is_subring.coe_subtype {S : set R} [is_subring S] : ⇑(is_subring.subtype S) = coe := rfl variables {cR : Type u} [comm_ring cR] instance subset.comm_ring {S : set cR} [is_subring S] : comm_ring S := { mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1, .. subset.ring } instance subtype.comm_ring {S : set cR} [is_subring S] : comm_ring (subtype S) := subset.comm_ring instance subring.domain {D : Type*} [integral_domain D] (S : set D) [is_subring S] : integral_domain S := { exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.1 zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨x, hx⟩ ⟨y, hy⟩, by { simp only [subtype.ext_iff_val, subtype.coe_mk], exact eq_zero_or_eq_zero_of_mul_eq_zero }, .. subset.comm_ring } instance is_subring.inter (S₁ S₂ : set R) [is_subring S₁] [is_subring S₂] : is_subring (S₁ ∩ S₂) := { } instance is_subring.Inter {ι : Sort*} (S : ι → set R) [h : ∀ y : ι, is_subring (S y)] : is_subring (set.Inter S) := { } lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set R) [∀ i, is_subring (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subring (⋃i, s i) := { to_is_add_subgroup := is_add_subgroup_Union_of_directed s directed, to_is_submonoid := is_submonoid_Union_of_directed s directed } namespace ring def closure (s : set R) := add_group.closure (monoid.closure s) variable {s : set R} local attribute [reducible] closure theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) : (∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) := add_group.in_closure.rec_on h (λ x hx, match x, monoid.exists_list_of_mem_closure hx with | _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩ end) ⟨[], list.forall_mem_nil _, rfl⟩ (λ b _ ih, match b, ih with | _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)), λ L2 h2, match L2, list.mem_map.1 h2 with | _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩ end, by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul]; exact list.rec_on L1 neg_zero.symm (λ hd tl ih, by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩ end) (λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with | _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩, by rw [list.map_append, list.sum_append]⟩ end) @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end instance : is_subring (closure s) := { one_mem := add_group.mem_closure is_submonoid.one_mem, mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb (λ b hb, add_group.in_closure.rec_on ha (λ a ha, add_group.subset_closure (is_submonoid.mul_mem ha hb)) ((zero_mul b).symm ▸ is_add_submonoid.zero_mem) (λ a ha hab, (neg_mul_eq_neg_mul a b) ▸ is_add_subgroup.neg_mem hab) (λ a c ha hc hab hcb, (add_mul a c b).symm ▸ is_add_submonoid.add_mem hab hcb)) ((mul_zero a).symm ▸ is_add_submonoid.zero_mem) (λ b hb hab, (neg_mul_eq_mul_neg a b) ▸ is_add_subgroup.neg_mem hab) (λ b c hb hc hab hac, (mul_add a b c).symm ▸ is_add_submonoid.add_mem hab hac), .. add_group.closure.is_add_subgroup _ } theorem mem_closure {a : R} : a ∈ s → a ∈ closure s := add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _ theorem subset_closure : s ⊆ closure s := λ _, mem_closure theorem closure_subset {t : set R} [is_subring t] : s ⊆ t → closure s ⊆ t := add_group.closure_subset ∘ monoid.closure_subset theorem closure_subset_iff (s t : set R) [is_subring t] : closure s ⊆ t ↔ s ⊆ t := (add_group.closure_subset_iff _ t).trans ⟨set.subset.trans monoid.subset_closure, monoid.closure_subset⟩ theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure lemma image_closure {S : Type*} [ring S] (f : R →+* S) (s : set R) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { rw [f.map_one], apply is_submonoid.one_mem }, { rw [f.map_neg, f.map_one], apply is_add_subgroup.neg_mem, apply is_submonoid.one_mem }, { rw [f.map_mul], apply is_submonoid.mul_mem; solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [f.map_add], apply is_add_submonoid.add_mem, assumption' }, end (closure_subset $ set.image_subset _ subset_closure) end ring
3c3dfa32484f08d8252353256cedc1cf7115ca2d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/509.lean
2eb1d933b2c69619b3aefa24d796d697f73534a2
[ "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
911
lean
class has_note (M : Type) where note : M notation "♩" => has_note.note class has_note2 (M : Type) extends has_note M variable {ι : Type} (β : ι → Type) structure foo [∀ i, has_note (β i)] : Type where to_fun : ∀ i, β i instance foo.has_note [∀ i, has_note (β i)] : has_note (foo (λ i => β i)) where note := { to_fun := λ _ => ♩ } instance foo.has_note2 [∀ i, has_note2 (β i)] : has_note2 (foo (λ i => β i)) where note := ♩ variable (α : Type) (M : Type) structure bar [has_note M] where to_fun : α → M instance bar.has_note [has_note M] : has_note (bar α M) where note := { to_fun := λ _ => ♩ } instance bar.has_note2 [has_note2 M] : has_note2 (bar α M) where note := ♩ example [has_note2 M] : has_note2 (foo (λ (i : ι) => bar (β i) M)) := inferInstance example [has_note2 M] : has_note2 (foo (λ (i : ι) => bar (β i) M)) := foo.has_note2 _
651f59d601e3e10bd5f663d9a1f4489202bcadff
4fa161becb8ce7378a709f5992a594764699e268
/src/category_theory/limits/preserves.lean
d229da979dcb0b744641bb73cbc973eac0594ba9
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
12,549
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, Bhavik Mehta -/ 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] 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.cocone_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 } 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⟩⟩ } } 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'))⟩ /-- Transfer preservation of limits along a natural isomorphism in the shape. -/ def preserves_limit_of_iso {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [preserves_limit K₁ F] : preserves_limit K₂ F := { preserves := λ c t, begin have t' := is_limit.of_cone_equiv (cones.postcompose_equivalence h).inverse t, let hF := iso_whisker_right h F, have := is_limit.of_cone_equiv (cones.postcompose_equivalence hF).functor (preserves_limit.preserves t'), apply is_limit.of_iso_limit this, refine cones.ext (iso.refl _) (λ j, _), dsimp, rw [← F.map_comp], simp, end } /-- 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'))⟩ /-- Transfer preservation of colimits along a natural isomorphism in the shape. -/ def preserves_colimit_of_iso {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [preserves_colimit K₁ F] : preserves_colimit K₂ F := { preserves := λ c t, begin have t' := is_colimit.of_cocone_equiv (cocones.precompose_equivalence h).functor t, let hF := iso_whisker_right h F, have := is_colimit.of_cocone_equiv (cocones.precompose_equivalence hF).inverse (preserves_colimit.preserves t'), apply is_colimit.of_iso_colimit this, refine cocones.ext (iso.refl _) (λ j, _), dsimp, rw [← F.map_comp], simp, end } /- 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 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⟩⟩ } } 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
dae45bff8a2de18542b19fbbc3b68576e57d728d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/group/units.lean
060aeef30d9fdfacec4f2aafc7424016e1f45e0d
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
20,082
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker, Jon Eugster -/ import algebra.group.basic import logic.unique import tactic.nontriviality /-! # Units (i.e., invertible elements) of a monoid > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/549 > Any changes to this file require a corresponding PR to mathlib4. An element of a `monoid` is a unit if it has a two-sided inverse. ## Main declarations * `units M`: the group of units (i.e., invertible elements) of a monoid. * `is_unit x`: a predicate asserting that `x` is a unit (i.e., invertible element) of a monoid. For both declarations, there is an additive counterpart: `add_units` and `is_add_unit`. ## Notation We provide `Mˣ` as notation for `units M`, resembling the notation $R^{\times}$ for the units of a ring, which is common in mathematics. -/ open function universe u variable {α : Type u} /-- Units of a `monoid`, bundled version. Notation: `αˣ`. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) postfix `ˣ`:1025 := units -- We don't provide notation for the additive version, because its use is somewhat rare. /-- Units of an `add_monoid`, bundled version. An element of an `add_monoid` is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive] units section has_elem @[to_additive] lemma unique_has_one {α : Type*} [unique α] [has_one α] : default = (1 : α) := unique.default_eq 1 end has_elem namespace units variables [monoid α] @[to_additive] instance : has_coe αˣ α := ⟨val⟩ @[to_additive] instance : has_inv αˣ := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩ /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe (u : αˣ) : α := u /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe_inv (u : αˣ) : α := ↑(u⁻¹) initialize_simps_projections units (val → coe as_prefix, inv → coe_inv as_prefix) initialize_simps_projections add_units (val → coe as_prefix, neg → coe_neg as_prefix) @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : αˣ → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : αˣ} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : αˣ} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq αˣ := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : αˣ) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Copy a unit, adjusting definition equalities. -/ @[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps] def copy (u : αˣ) (val : α) (hv : val = u) (inv : α) (hi : inv = ↑(u⁻¹)) : αˣ := { val := val, inv := inv, inv_val := hv.symm ▸ hi.symm ▸ u.inv_val, val_inv := hv.symm ▸ hi.symm ▸ u.val_inv } @[to_additive] lemma copy_eq (u : αˣ) (val hv inv hi) : u.copy val hv inv hi = u := ext hv @[to_additive] instance : mul_one_class αˣ := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ←mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ←mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, one_mul := λ u, ext $ one_mul u, mul_one := λ u, ext $ mul_one u } /-- Units of a monoid form a group. -/ @[to_additive "Additive units of an additive monoid form an additive group."] instance : group αˣ := { mul := (*), one := 1, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := has_inv.inv, mul_left_inv := λ u, ext u.inv_val, ..units.mul_one_class } @[to_additive] instance {α} [comm_monoid α] : comm_group αˣ := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance : inhabited αˣ := ⟨1⟩ @[to_additive] instance [has_repr α] : has_repr αˣ := ⟨repr ∘ val⟩ variables (a b c : αˣ) {u : αˣ} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : αˣ) : α) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_eq_one {a : αˣ} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[simp, to_additive] lemma val_eq_coe : a.val = (↑a : α) := rfl @[simp, to_additive] lemma inv_eq_coe_inv : a.inv = ((a⁻¹ : αˣ) : α) := rfl @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by rw [←h, u.inv_mul] @[to_additive] lemma mul_inv_of_eq {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by rw [←h, u.mul_inv] @[simp, to_additive] lemma mul_inv_cancel_left (a : αˣ) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : αˣ) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : αˣ) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : αˣ) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[simp, to_additive] theorem mul_right_inj (a : αˣ) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : αˣ) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive] protected lemma inv_eq_of_mul_eq_one_left {a : α} (h : a * u = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = 1 * ↑u⁻¹ : by rw one_mul ... = a : by rw [←h, mul_inv_cancel_right] @[to_additive] protected lemma inv_eq_of_mul_eq_one_right {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = a : by rw [←h, inv_mul_cancel_left] @[to_additive] protected lemma eq_inv_of_mul_eq_one_left {a : α} (h : ↑u * a = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_right h).symm @[to_additive] protected lemma eq_inv_of_mul_eq_one_right {a : α} (h : a * u = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_left h).symm @[simp, to_additive] lemma mul_inv_eq_one {a : α} : a * ↑u⁻¹ = 1 ↔ a = u := ⟨inv_inv u ▸ units.eq_inv_of_mul_eq_one_right, λ h, mul_inv_of_eq h.symm⟩ @[simp, to_additive] lemma inv_mul_eq_one {a : α} : ↑u⁻¹ * a = 1 ↔ ↑u = a := ⟨inv_inv u ▸ units.inv_eq_of_mul_eq_one_right, inv_mul_of_eq⟩ @[to_additive] lemma mul_eq_one_iff_eq_inv {a : α} : a * u = 1 ↔ a = ↑u⁻¹ := by rw [←mul_inv_eq_one, inv_inv] @[to_additive] lemma mul_eq_one_iff_inv_eq {a : α} : ↑u * a = 1 ↔ ↑u⁻¹ = a := by rw [←inv_mul_eq_one, inv_inv] @[to_additive] lemma inv_unique {u₁ u₂ : αˣ} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := units.inv_eq_of_mul_eq_one_right $ by rw [h, u₂.mul_inv] @[simp, to_additive] lemma coe_inv {M : Type*} [division_monoid M] (u : units M) : ↑u⁻¹ = (u⁻¹ : M) := eq.symm $ inv_eq_of_mul_eq_one_right u.mul_inv end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : αˣ := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : αˣ) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : αˣ) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : αˣ) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ /-- `field_simp` needs the reverse direction of `divp_assoc` to move all `/ₚ` to the right. -/ @[field_simps] lemma divp_assoc' (x y : α) (u : αˣ) : x * (y /ₚ u) = (x * y) /ₚ u := (divp_assoc _ _ _).symm @[simp] theorem divp_inv (u : αˣ) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : αˣ) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : αˣ) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : αˣ) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ @[field_simps] theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : αˣ) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] @[field_simps] theorem divp_eq_iff_mul_eq {x : α} {u : αˣ} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ @[field_simps] theorem eq_divp_iff_mul_eq {x : α} {u : αˣ} {y : α} : x = y /ₚ u ↔ x * u = y := by rw [eq_comm, divp_eq_iff_mul_eq] theorem divp_eq_one_iff_eq {a : α} {u : αˣ} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : αˣ) : 1 /ₚ u = ↑u⁻¹ := one_mul _ /-- Used for `field_simp` to deal with inverses of units. -/ @[field_simps] lemma inv_eq_one_divp (u : αˣ) : ↑u⁻¹ = 1 /ₚ u := by rw one_divp /-- Used for `field_simp` to deal with inverses of units. This form of the lemma is essential since `field_simp` likes to use `inv_eq_one_div` to rewrite `↑u⁻¹ = ↑(1 / u)`. -/ @[field_simps] lemma inv_eq_one_divp' (u : αˣ) : ((1 / u : αˣ) : α) = 1 /ₚ u := by rw [one_div, one_divp] /-- `field_simp` moves division inside `αˣ` to the right, and this lemma lifts the calculation to `α`. -/ @[field_simps] lemma coe_div_eq_divp (u₁ u₂ : αˣ) : ↑(u₁ / u₂) = ↑u₁ /ₚ u₂ := by rw [divp, division_def, units.coe_mul] end monoid section comm_monoid variables [comm_monoid α] @[field_simps] theorem divp_mul_eq_mul_divp (x y : α) (u : αˣ) : x /ₚ u * y = x * y /ₚ u := by simp_rw [divp, mul_assoc, mul_comm] -- Theoretically redundant as `field_simp` lemma. @[field_simps] lemma divp_eq_divp_iff {x y : α} {ux uy : αˣ} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, divp_mul_eq_mul_divp, divp_eq_iff_mul_eq] -- Theoretically redundant as `field_simp` lemma. @[field_simps] lemma divp_mul_divp (x y : α) (ux uy : αˣ) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [divp_mul_eq_mul_divp, divp_assoc', divp_divp_eq_divp_mul] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : Mˣ`, where `Mˣ` is a bundled version of `is_unit`. -/ @[to_additive "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : Mˣ, (u : M) = a @[nontriviality, to_additive] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ attribute [nontriviality] is_add_unit_of_subsingleton @[to_additive] instance [monoid M] : can_lift M Mˣ coe is_unit := { prf := λ _, id } @[to_additive] instance [monoid M] [subsingleton M] : unique Mˣ := { default := 1, uniq := λ a, units.coe_eq_one.mp $ subsingleton.elim (a : M) 1 } @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : Mˣ) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, a * b = 1 := by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ } @[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, b * a = 1 := by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ } @[to_additive] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨λ h, h.exists_right_inv, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } /-- Multiplication by a `u : Mˣ` on the right doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the right doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : Mˣ) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (λ v, v.mul u.is_unit) /-- Multiplication by a `u : Mˣ` on the left doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the left doesn't affect `is_add_unit`."] theorem units.is_unit_units_mul {M : Type*} [monoid M] (u : Mˣ) (a : M) : is_unit (↑u * a) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (↑u⁻¹ * (↑u * a)), by existsi u⁻¹ * v; rw [←hv, units.coe_mul], by rwa [←mul_assoc, units.inv_mul, one_mul] at this) u.is_unit.mul @[to_additive] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm namespace is_unit @[simp, to_additive] lemma mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, λ h, is_unit.mul h.1 h.2⟩ section monoid variables [monoid M] {a b c : M} /-- The element of the group of units, corresponding to an element of a monoid which is a unit. When `α` is a `division_monoid`, use `is_unit.unit'` instead. -/ @[to_additive "The element of the additive group of additive units, corresponding to an element of an additive monoid which is an additive unit. When `α` is a `subtraction_monoid`, use `is_add_unit.add_unit'` instead."] protected noncomputable def unit (h : is_unit a) : Mˣ := (classical.some h).copy a (classical.some_spec h).symm _ rfl @[simp, to_additive] lemma unit_of_coe_units {a : Mˣ} (h : is_unit (a : M)) : h.unit = a := units.ext $ rfl @[simp, to_additive] lemma unit_spec (h : is_unit a) : ↑h.unit = a := rfl @[simp, to_additive] lemma coe_inv_mul (h : is_unit a) : ↑(h.unit)⁻¹ * a = 1 := units.mul_inv _ @[simp, to_additive] lemma mul_coe_inv (h : is_unit a) : a * ↑(h.unit)⁻¹ = 1 := by convert h.unit.mul_inv /-- `is_unit x` is decidable if we can decide if `x` comes from `Mˣ`. -/ instance (x : M) [h : decidable (∃ u : Mˣ, ↑u = x)] : decidable (is_unit x) := h @[to_additive] lemma mul_left_inj (h : is_unit a) : b * a = c * a ↔ b = c := let ⟨u, hu⟩ := h in hu ▸ u.mul_left_inj @[to_additive] lemma mul_right_inj (h : is_unit a) : a * b = a * c ↔ b = c := let ⟨u, hu⟩ := h in hu ▸ u.mul_right_inj @[to_additive] protected lemma mul_left_cancel (h : is_unit a) : a * b = a * c → b = c := h.mul_right_inj.1 @[to_additive] protected lemma mul_right_cancel (h : is_unit b) : a * b = c * b → a = c := h.mul_left_inj.1 @[to_additive] protected lemma mul_right_injective (h : is_unit a) : injective ((*) a) := λ _ _, h.mul_left_cancel @[to_additive] protected lemma mul_left_injective (h : is_unit b) : injective (* b) := λ _ _, h.mul_right_cancel end monoid variables [division_monoid M] {a : M} @[simp, to_additive] protected lemma inv_mul_cancel : is_unit a → a⁻¹ * a = 1 := by { rintro ⟨u, rfl⟩, rw [← units.coe_inv, units.inv_mul] } @[simp, to_additive] protected lemma mul_inv_cancel : is_unit a → a * a⁻¹ = 1 := by { rintro ⟨u, rfl⟩, rw [← units.coe_inv, units.mul_inv] } end is_unit -- namespace end is_unit -- section section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
5dd4152726ea614c3fd4f7c1e3aff36b389cf4d8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/atoms.lean
e7863c9974d326463331fcedddf7a6e9d861922c
[ "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
30,269
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.modular_lattice import order.well_founded /-! # Atoms, Coatoms, and Simple Lattices > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module defines atoms, which are minimal non-`⊥` elements in bounded lattices, simple lattices, which are lattices with only two elements, and related ideas. ## Main definitions ### Atoms and Coatoms * `is_atom a` indicates that the only element below `a` is `⊥`. * `is_coatom a` indicates that the only element above `a` is `⊤`. ### Atomic and Atomistic Lattices * `is_atomic` indicates that every element other than `⊥` is above an atom. * `is_coatomic` indicates that every element other than `⊤` is below a coatom. * `is_atomistic` indicates that every element is the `Sup` of a set of atoms. * `is_coatomistic` indicates that every element is the `Inf` of a set of coatoms. ### Simple Lattices * `is_simple_order` indicates that an order has only two unique elements, `⊥` and `⊤`. * `is_simple_order.bounded_order` * `is_simple_order.distrib_lattice` * Given an instance of `is_simple_order`, we provide the following definitions. These are not made global instances as they contain data : * `is_simple_order.boolean_algebra` * `is_simple_order.complete_lattice` * `is_simple_order.complete_boolean_algebra` ## Main results * `is_atom_dual_iff_is_coatom` and `is_coatom_dual_iff_is_atom` express the (definitional) duality of `is_atom` and `is_coatom`. * `is_simple_order_iff_is_atom_top` and `is_simple_order_iff_is_coatom_bot` express the connection between atoms, coatoms, and simple lattices * `is_compl.is_atom_iff_is_coatom` and `is_compl.is_coatom_if_is_atom`: In a modular bounded lattice, a complement of an atom is a coatom and vice versa. * `is_atomic_iff_is_coatomic`: A modular complemented lattice is atomic iff it is coatomic. -/ variables {α β : Type*} section atoms section is_atom section preorder variables [preorder α] [order_bot α] {a b x : α} /-- An atom of an `order_bot` is an element with no other element between it and `⊥`, which is not `⊥`. -/ def is_atom (a : α) : Prop := a ≠ ⊥ ∧ (∀ b, b < a → b = ⊥) lemma is_atom.Iic (ha : is_atom a) (hax : a ≤ x) : is_atom (⟨a, hax⟩ : set.Iic x) := ⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩ lemma is_atom.of_is_atom_coe_Iic {a : set.Iic x} (ha : is_atom a) : is_atom (a : α) := ⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, hba.le.trans a.prop⟩ hba)⟩ lemma is_atom_iff {a : α} : is_atom a ↔ a ≠ ⊥ ∧ ∀ b ≠ ⊥, b ≤ a → a ≤ b := and_congr iff.rfl $ forall_congr $ λ b, by simp only [ne.def, @not_imp_comm (b = ⊥), not_imp, lt_iff_le_not_le] end preorder variables [partial_order α] [order_bot α] {a b x : α} lemma is_atom.lt_iff (h : is_atom a) : x < a ↔ x = ⊥ := ⟨h.2 x, λ hx, hx.symm ▸ h.1.bot_lt⟩ lemma is_atom.le_iff (h : is_atom a) : x ≤ a ↔ x = ⊥ ∨ x = a := by rw [le_iff_lt_or_eq, h.lt_iff] lemma is_atom.Iic_eq (h : is_atom a) : set.Iic a = {⊥, a} := set.ext $ λ x, h.le_iff @[simp] lemma bot_covby_iff : ⊥ ⋖ a ↔ is_atom a := by simp only [covby, bot_lt_iff_ne_bot, is_atom, not_imp_not] alias bot_covby_iff ↔ covby.is_atom is_atom.bot_covby end is_atom section is_coatom section preorder variables [preorder α] /-- A coatom of an `order_top` is an element with no other element between it and `⊤`, which is not `⊤`. -/ def is_coatom [order_top α] (a : α) : Prop := a ≠ ⊤ ∧ (∀ b, a < b → b = ⊤) @[simp] lemma is_coatom_dual_iff_is_atom [order_bot α] {a : α}: is_coatom (order_dual.to_dual a) ↔ is_atom a := iff.rfl @[simp] lemma is_atom_dual_iff_is_coatom [order_top α] {a : α} : is_atom (order_dual.to_dual a) ↔ is_coatom a := iff.rfl alias is_coatom_dual_iff_is_atom ↔ _ is_atom.dual alias is_atom_dual_iff_is_coatom ↔ _ is_coatom.dual variables [order_top α] {a x : α} lemma is_coatom.Ici (ha : is_coatom a) (hax : x ≤ a) : is_coatom (⟨a, hax⟩ : set.Ici x) := ha.dual.Iic hax lemma is_coatom.of_is_coatom_coe_Ici {a : set.Ici x} (ha : is_coatom a) : is_coatom (a : α) := @is_atom.of_is_atom_coe_Iic αᵒᵈ _ _ x a ha lemma is_coatom_iff {a : α} : is_coatom a ↔ a ≠ ⊤ ∧ ∀ b ≠ ⊤, a ≤ b → b ≤ a := @is_atom_iff αᵒᵈ _ _ _ end preorder variables [partial_order α] [order_top α] {a b x : α} lemma is_coatom.lt_iff (h : is_coatom a) : a < x ↔ x = ⊤ := h.dual.lt_iff lemma is_coatom.le_iff (h : is_coatom a) : a ≤ x ↔ x = ⊤ ∨ x = a := h.dual.le_iff lemma is_coatom.Ici_eq (h : is_coatom a) : set.Ici a = {⊤, a} := h.dual.Iic_eq @[simp] lemma covby_top_iff : a ⋖ ⊤ ↔ is_coatom a := to_dual_covby_to_dual_iff.symm.trans bot_covby_iff alias covby_top_iff ↔ covby.is_coatom is_coatom.covby_top end is_coatom section partial_order variables [partial_order α] {a b : α} @[simp] lemma set.Ici.is_atom_iff {b : set.Ici a} : is_atom b ↔ a ⋖ b := begin rw ←bot_covby_iff, refine (set.ord_connected.apply_covby_apply_iff (order_embedding.subtype $ λ c, a ≤ c) _).symm, simpa only [order_embedding.subtype_apply, subtype.range_coe_subtype] using set.ord_connected_Ici, end @[simp] lemma set.Iic.is_coatom_iff {a : set.Iic b} : is_coatom a ↔ ↑a ⋖ b := begin rw ←covby_top_iff, refine (set.ord_connected.apply_covby_apply_iff (order_embedding.subtype $ λ c, c ≤ b) _).symm, simpa only [order_embedding.subtype_apply, subtype.range_coe_subtype] using set.ord_connected_Iic, end lemma covby_iff_atom_Ici (h : a ≤ b) : a ⋖ b ↔ is_atom (⟨b, h⟩ : set.Ici a) := by simp lemma covby_iff_coatom_Iic (h : a ≤ b) : a ⋖ b ↔ is_coatom (⟨a, h⟩ : set.Iic b) := by simp end partial_order section pairwise lemma is_atom.inf_eq_bot_of_ne [semilattice_inf α] [order_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : a ⊓ b = ⊥ := hab.not_le_or_not_le.elim (ha.lt_iff.1 ∘ inf_lt_left.2) (hb.lt_iff.1 ∘ inf_lt_right.2) lemma is_atom.disjoint_of_ne [semilattice_inf α] [order_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : disjoint a b := disjoint_iff.mpr (is_atom.inf_eq_bot_of_ne ha hb hab) lemma is_coatom.sup_eq_top_of_ne [semilattice_sup α] [order_top α] {a b : α} (ha : is_coatom a) (hb : is_coatom b) (hab : a ≠ b) : a ⊔ b = ⊤ := ha.dual.inf_eq_bot_of_ne hb.dual hab end pairwise end atoms section atomic variables [partial_order α] (α) /-- A lattice is atomic iff every element other than `⊥` has an atom below it. -/ @[mk_iff] class is_atomic [order_bot α] : Prop := (eq_bot_or_exists_atom_le : ∀ (b : α), b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) /-- A lattice is coatomic iff every element other than `⊤` has a coatom above it. -/ @[mk_iff] class is_coatomic [order_top α] : Prop := (eq_top_or_exists_le_coatom : ∀ (b : α), b = ⊤ ∨ ∃ (a : α), is_coatom a ∧ b ≤ a) export is_atomic (eq_bot_or_exists_atom_le) is_coatomic (eq_top_or_exists_le_coatom) variable {α} @[simp] lemma is_coatomic_dual_iff_is_atomic [order_bot α] : is_coatomic αᵒᵈ ↔ is_atomic α := ⟨λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩, λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩⟩ @[simp] lemma is_atomic_dual_iff_is_coatomic [order_top α] : is_atomic αᵒᵈ ↔ is_coatomic α := ⟨λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩, λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩⟩ namespace is_atomic variables [order_bot α] [is_atomic α] instance is_coatomic_dual : is_coatomic αᵒᵈ := is_coatomic_dual_iff_is_atomic.2 ‹is_atomic α› instance {x : α} : is_atomic (set.Iic x) := ⟨λ ⟨y, hy⟩, (eq_bot_or_exists_atom_le y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, hay.trans hy⟩, ha.Iic (hay.trans hy), hay⟩)⟩ end is_atomic namespace is_coatomic variables [order_top α] [is_coatomic α] instance is_coatomic : is_atomic αᵒᵈ := is_atomic_dual_iff_is_coatomic.2 ‹is_coatomic α› instance {x : α} : is_coatomic (set.Ici x) := ⟨λ ⟨y, hy⟩, (eq_top_or_exists_le_coatom y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, le_trans hy hay⟩, ha.Ici (le_trans hy hay), hay⟩)⟩ end is_coatomic theorem is_atomic_iff_forall_is_atomic_Iic [order_bot α] : is_atomic α ↔ ∀ (x : α), is_atomic (set.Iic x) := ⟨@is_atomic.set.Iic.is_atomic _ _ _, λ h, ⟨λ x, ((@eq_bot_or_exists_atom_le _ _ _ (h x)) (⊤ : set.Iic x)).imp subtype.mk_eq_mk.1 (exists_imp_exists' coe (λ ⟨a, ha⟩, and.imp_left (is_atom.of_is_atom_coe_Iic)))⟩⟩ theorem is_coatomic_iff_forall_is_coatomic_Ici [order_top α] : is_coatomic α ↔ ∀ (x : α), is_coatomic (set.Ici x) := is_atomic_dual_iff_is_coatomic.symm.trans $ is_atomic_iff_forall_is_atomic_Iic.trans $ forall_congr (λ x, is_coatomic_dual_iff_is_atomic.symm.trans iff.rfl) section well_founded lemma is_atomic_of_order_bot_well_founded_lt [order_bot α] (h : well_founded ((<) : α → α → Prop)) : is_atomic α := ⟨λ a, or_iff_not_imp_left.2 $ λ ha, let ⟨b, hb, hm⟩ := h.has_min { b | b ≠ ⊥ ∧ b ≤ a } ⟨a, ha, le_rfl⟩ in ⟨b, ⟨hb.1, λ c, not_imp_not.1 $ λ hc hl, hm c ⟨hc, hl.le.trans hb.2⟩ hl⟩, hb.2⟩⟩ lemma is_coatomic_of_order_top_gt_well_founded [order_top α] (h : well_founded ((>) : α → α → Prop)) : is_coatomic α := is_atomic_dual_iff_is_coatomic.1 (@is_atomic_of_order_bot_well_founded_lt αᵒᵈ _ _ h) end well_founded end atomic section atomistic variables (α) [complete_lattice α] /-- A lattice is atomistic iff every element is a `Sup` of a set of atoms. -/ class is_atomistic : Prop := (eq_Sup_atoms : ∀ (b : α), ∃ (s : set α), b = Sup s ∧ ∀ a, a ∈ s → is_atom a) /-- A lattice is coatomistic iff every element is an `Inf` of a set of coatoms. -/ class is_coatomistic : Prop := (eq_Inf_coatoms : ∀ (b : α), ∃ (s : set α), b = Inf s ∧ ∀ a, a ∈ s → is_coatom a) export is_atomistic (eq_Sup_atoms) is_coatomistic (eq_Inf_coatoms) variable {α} @[simp] theorem is_coatomistic_dual_iff_is_atomistic : is_coatomistic αᵒᵈ ↔ is_atomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩, λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩⟩ @[simp] theorem is_atomistic_dual_iff_is_coatomistic : is_atomistic αᵒᵈ ↔ is_coatomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩, λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩⟩ namespace is_atomistic instance is_coatomistic_dual [h : is_atomistic α] : is_coatomistic αᵒᵈ := is_coatomistic_dual_iff_is_atomistic.2 h variable [is_atomistic α] @[priority 100] instance : is_atomic α := ⟨λ b, by { rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, le_Sup h.some_spec⟩ } } ⟩ end is_atomistic section is_atomistic variables [is_atomistic α] @[simp] theorem Sup_atoms_le_eq (b : α) : Sup {a : α | is_atom a ∧ a ≤ b} = b := begin rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, exact le_antisymm (Sup_le (λ _, and.right)) (Sup_le_Sup (λ a ha, ⟨hs a ha, le_Sup ha⟩)), end @[simp] theorem Sup_atoms_eq_top : Sup {a : α | is_atom a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_atoms_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_atom_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, is_atom c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_atoms_le_eq a, ← Sup_atoms_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ end is_atomistic namespace is_coatomistic instance is_atomistic_dual [h : is_coatomistic α] : is_atomistic αᵒᵈ := is_atomistic_dual_iff_is_coatomistic.2 h variable [is_coatomistic α] @[priority 100] instance : is_coatomic α := ⟨λ b, by { rcases eq_Inf_coatoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, Inf_le h.some_spec⟩ } } ⟩ end is_coatomistic end atomistic /-- An order is simple iff it has exactly two elements, `⊥` and `⊤`. -/ class is_simple_order (α : Type*) [has_le α] [bounded_order α] extends nontrivial α : Prop := (eq_bot_or_eq_top : ∀ (a : α), a = ⊥ ∨ a = ⊤) export is_simple_order (eq_bot_or_eq_top) theorem is_simple_order_iff_is_simple_order_order_dual [has_le α] [bounded_order α] : is_simple_order α ↔ is_simple_order αᵒᵈ := begin split; intro i; haveI := i, { exact { exists_pair_ne := @exists_pair_ne α _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top ((order_dual.of_dual a)) : _ ∨ _) } }, { exact { exists_pair_ne := @exists_pair_ne αᵒᵈ _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top (order_dual.to_dual a)) } } end lemma is_simple_order.bot_ne_top [has_le α] [bounded_order α] [is_simple_order α] : (⊥ : α) ≠ (⊤ : α) := begin obtain ⟨a, b, h⟩ := exists_pair_ne α, rcases eq_bot_or_eq_top a with rfl|rfl; rcases eq_bot_or_eq_top b with rfl|rfl; simpa <|> simpa using h.symm end section is_simple_order variables [partial_order α] [bounded_order α] [is_simple_order α] instance {α} [has_le α] [bounded_order α] [is_simple_order α] : is_simple_order αᵒᵈ := is_simple_order_iff_is_simple_order_order_dual.1 (by apply_instance) /-- A simple `bounded_order` induces a preorder. This is not an instance to prevent loops. -/ protected def is_simple_order.preorder {α} [has_le α] [bounded_order α] [is_simple_order α] : preorder α := { le := (≤), le_refl := λ a, by rcases eq_bot_or_eq_top a with rfl|rfl; simp, le_trans := λ a b c, begin rcases eq_bot_or_eq_top a with rfl|rfl, { simp }, { rcases eq_bot_or_eq_top b with rfl|rfl, { rcases eq_bot_or_eq_top c with rfl|rfl; simp }, { simp } } end } /-- A simple partial ordered `bounded_order` induces a linear order. This is not an instance to prevent loops. -/ protected def is_simple_order.linear_order [decidable_eq α] : linear_order α := { le_total := λ a b, by rcases eq_bot_or_eq_top a with rfl|rfl; simp, decidable_le := λ a b, if ha : a = ⊥ then is_true (ha.le.trans bot_le) else if hb : b = ⊤ then is_true (le_top.trans hb.ge) else is_false (λ H, hb (top_unique (le_trans (top_le_iff.mpr (or.resolve_left (eq_bot_or_eq_top a) ha)) H))), decidable_eq := by assumption, ..(infer_instance : partial_order α) } @[simp] lemma is_atom_top : is_atom (⊤ : α) := ⟨top_ne_bot, λ a ha, or.resolve_right (eq_bot_or_eq_top a) (ne_of_lt ha)⟩ @[simp] lemma is_coatom_bot : is_coatom (⊥ : α) := is_atom_dual_iff_is_coatom.1 is_atom_top lemma bot_covby_top : (⊥ : α) ⋖ ⊤ := is_atom_top.bot_covby end is_simple_order namespace is_simple_order section preorder variables [preorder α] [bounded_order α] [is_simple_order α] {a b : α} (h : a < b) lemma eq_bot_of_lt : a = ⊥ := (is_simple_order.eq_bot_or_eq_top _).resolve_right h.ne_top lemma eq_top_of_lt : b = ⊤ := (is_simple_order.eq_bot_or_eq_top _).resolve_left h.ne_bot alias eq_bot_of_lt ← has_lt.lt.eq_bot alias eq_top_of_lt ← has_lt.lt.eq_top end preorder section bounded_order variables [lattice α] [bounded_order α] [is_simple_order α] /-- A simple partial ordered `bounded_order` induces a lattice. This is not an instance to prevent loops -/ protected def lattice {α} [decidable_eq α] [partial_order α] [bounded_order α] [is_simple_order α] : lattice α := @linear_order.to_lattice α (is_simple_order.linear_order) /-- A lattice that is a `bounded_order` is a distributive lattice. This is not an instance to prevent loops -/ protected def distrib_lattice : distrib_lattice α := { le_sup_inf := λ x y z, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp }, .. (infer_instance : lattice α) } @[priority 100] -- see Note [lower instance priority] instance : is_atomic α := ⟨λ b, (eq_bot_or_eq_top b).imp_right (λ h, ⟨⊤, ⟨is_atom_top, ge_of_eq h⟩⟩)⟩ @[priority 100] -- see Note [lower instance priority] instance : is_coatomic α := is_atomic_dual_iff_is_coatomic.1 is_simple_order.is_atomic end bounded_order /- It is important that in this section `is_simple_order` is the last type-class argument. -/ section decidable_eq variables [decidable_eq α] [partial_order α] [bounded_order α] [is_simple_order α] /-- Every simple lattice is isomorphic to `bool`, regardless of order. -/ @[simps] def equiv_bool {α} [decidable_eq α] [has_le α] [bounded_order α] [is_simple_order α] : α ≃ bool := { to_fun := λ x, x = ⊤, inv_fun := λ x, cond x ⊤ ⊥, left_inv := λ x, by { rcases (eq_bot_or_eq_top x) with rfl | rfl; simp [bot_ne_top] }, right_inv := λ x, by { cases x; simp [bot_ne_top] } } /-- Every simple lattice over a partial order is order-isomorphic to `bool`. -/ def order_iso_bool : α ≃o bool := { map_rel_iff' := λ a b, begin rcases (eq_bot_or_eq_top a) with rfl | rfl, { simp [bot_ne_top] }, { rcases (eq_bot_or_eq_top b) with rfl | rfl, { simp [bot_ne_top.symm, bot_ne_top, bool.ff_lt_tt] }, { simp [bot_ne_top] } } end, ..equiv_bool } /-- A simple `bounded_order` is also a `boolean_algebra`. -/ protected def boolean_algebra {α} [decidable_eq α] [lattice α] [bounded_order α] [is_simple_order α] : boolean_algebra α := { compl := λ x, if x = ⊥ then ⊤ else ⊥, sdiff := λ x y, if x = ⊤ ∧ y = ⊥ then ⊤ else ⊥, sdiff_eq := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; simp [bot_ne_top, has_sdiff.sdiff, compl], inf_compl_le_bot := λ x, begin rcases eq_bot_or_eq_top x with rfl | rfl, { simp }, { simp only [top_inf_eq], split_ifs with h h; simp [h] } end, top_le_sup_compl := λ x, by rcases eq_bot_or_eq_top x with rfl | rfl; simp, .. (show bounded_order α, by apply_instance), .. is_simple_order.distrib_lattice } end decidable_eq variables [lattice α] [bounded_order α] [is_simple_order α] open_locale classical /-- A simple `bounded_order` is also complete. -/ protected noncomputable def complete_lattice : complete_lattice α := { Sup := λ s, if ⊤ ∈ s then ⊤ else ⊥, Inf := λ s, if ⊥ ∈ s then ⊥ else ⊤, le_Sup := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_pos h } }, Sup_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_neg, intro con, exact bot_ne_top (eq_top_iff.2 (h ⊤ con)) }, { exact le_top } }, Inf_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_pos h }, { exact le_top } }, le_Inf := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_neg, intro con, exact top_ne_bot (eq_bot_iff.2 (h ⊥ con)) } }, .. (infer_instance : lattice α), .. (infer_instance : bounded_order α) } /-- A simple `bounded_order` is also a `complete_boolean_algebra`. -/ protected noncomputable def complete_boolean_algebra : complete_boolean_algebra α := { infi_sup_le_sup_Inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_sup_eq, ← Inf_eq_infi], exact le_rfl }, { simp only [top_sup_eq, le_top] }, }, inf_Sup_le_supr_inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_inf_eq, bot_le] }, { simp only [top_inf_eq, ← Sup_eq_supr], exact le_rfl } }, .. is_simple_order.complete_lattice, .. is_simple_order.boolean_algebra } end is_simple_order namespace is_simple_order variables [complete_lattice α] [is_simple_order α] set_option default_priority 100 instance : is_atomistic α := ⟨λ b, (eq_bot_or_eq_top b).elim (λ h, ⟨∅, ⟨h.trans Sup_empty.symm, λ a ha, false.elim (set.not_mem_empty _ ha)⟩⟩) (λ h, ⟨{⊤}, h.trans Sup_singleton.symm, λ a ha, (set.mem_singleton_iff.1 ha).symm ▸ is_atom_top⟩)⟩ instance : is_coatomistic α := is_atomistic_dual_iff_is_coatomistic.1 is_simple_order.is_atomistic end is_simple_order theorem is_simple_order_iff_is_atom_top [partial_order α] [bounded_order α] : is_simple_order α ↔ is_atom (⊤ : α) := ⟨λ h, @is_atom_top _ _ _ h, λ h, { exists_pair_ne := ⟨⊤, ⊥, h.1⟩, eq_bot_or_eq_top := λ a, ((eq_or_lt_of_le le_top).imp_right (h.2 a)).symm }⟩ theorem is_simple_order_iff_is_coatom_bot [partial_order α] [bounded_order α] : is_simple_order α ↔ is_coatom (⊥ : α) := is_simple_order_iff_is_simple_order_order_dual.trans is_simple_order_iff_is_atom_top namespace set theorem is_simple_order_Iic_iff_is_atom [partial_order α] [order_bot α] {a : α} : is_simple_order (Iic a) ↔ is_atom a := is_simple_order_iff_is_atom_top.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ theorem is_simple_order_Ici_iff_is_coatom [partial_order α] [order_top α] {a : α} : is_simple_order (Ici a) ↔ is_coatom a := is_simple_order_iff_is_coatom_bot.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ end set namespace order_embedding variables [partial_order α] [partial_order β] lemma is_atom_of_map_bot_of_image [order_bot α] [order_bot β] (f : β ↪o α) (hbot : f ⊥ = ⊥) {b : β} (hb : is_atom (f b)) : is_atom b := by { simp only [←bot_covby_iff] at hb ⊢, exact covby.of_image f (hbot.symm ▸ hb) } lemma is_coatom_of_map_top_of_image [order_top α] [order_top β] (f : β ↪o α) (htop : f ⊤ = ⊤) {b : β} (hb : is_coatom (f b)) : is_coatom b := f.dual.is_atom_of_map_bot_of_image htop hb end order_embedding namespace galois_insertion variables [partial_order α] [partial_order β] lemma is_atom_of_u_bot [order_bot α] [order_bot β] {l : α → β} {u : β → α} (gi : galois_insertion l u) (hbot : u ⊥ = ⊥) {b : β} (hb : is_atom (u b)) : is_atom b := order_embedding.is_atom_of_map_bot_of_image ⟨⟨u, gi.u_injective⟩, @galois_insertion.u_le_u_iff _ _ _ _ _ _ gi⟩ hbot hb lemma is_atom_iff [order_bot α] [is_atomic α] [order_bot β] {l : α → β} {u : β → α} (gi : galois_insertion l u) (hbot : u ⊥ = ⊥) (h_atom : ∀ a, is_atom a → u (l a) = a) (a : α) : is_atom (l a) ↔ is_atom a := begin refine ⟨λ hla, _, λ ha, gi.is_atom_of_u_bot hbot ((h_atom a ha).symm ▸ ha)⟩, obtain ⟨a', ha', hab'⟩ := (eq_bot_or_exists_atom_le (u (l a))).resolve_left (hbot ▸ λ h, hla.1 (gi.u_injective h)), have := (hla.le_iff.mp $ (gi.l_u_eq (l a) ▸ gi.gc.monotone_l hab' : l a' ≤ l a)).resolve_left (λ h, ha'.1 (hbot ▸ (h_atom a' ha') ▸ congr_arg u h)), have haa' : a = a' := (ha'.le_iff.mp $ (gi.gc.le_u_l a).trans_eq (h_atom a' ha' ▸ congr_arg u this.symm)).resolve_left (mt (congr_arg l) (gi.gc.l_bot.symm ▸ hla.1)), exact haa'.symm ▸ ha' end lemma is_atom_iff' [order_bot α] [is_atomic α] [order_bot β] {l : α → β} {u : β → α} (gi : galois_insertion l u) (hbot : u ⊥ = ⊥) (h_atom : ∀ a, is_atom a → u (l a) = a) (b : β) : is_atom (u b) ↔ is_atom b := by rw [←gi.is_atom_iff hbot h_atom, gi.l_u_eq] lemma is_coatom_of_image [order_top α] [order_top β] {l : α → β} {u : β → α} (gi : galois_insertion l u) {b : β} (hb : is_coatom (u b)) : is_coatom b := order_embedding.is_coatom_of_map_top_of_image ⟨⟨u, gi.u_injective⟩, @galois_insertion.u_le_u_iff _ _ _ _ _ _ gi⟩ gi.gc.u_top hb lemma is_coatom_iff [order_top α] [is_coatomic α] [order_top β] {l : α → β} {u : β → α} (gi : galois_insertion l u) (h_coatom : ∀ a : α, is_coatom a → u (l a) = a) (b : β) : is_coatom (u b) ↔ is_coatom b := begin refine ⟨λ hb, gi.is_coatom_of_image hb, λ hb, _⟩, obtain ⟨a, ha, hab⟩ := (eq_top_or_exists_le_coatom (u b)).resolve_left (λ h, hb.1 $ (gi.gc.u_top ▸ gi.l_u_eq ⊤ : l ⊤ = ⊤) ▸ gi.l_u_eq b ▸ congr_arg l h), have : l a = b := (hb.le_iff.mp ((gi.l_u_eq b ▸ gi.gc.monotone_l hab) : b ≤ l a)).resolve_left (λ hla, ha.1 (gi.gc.u_top ▸ h_coatom a ha ▸ congr_arg u hla)), exact this ▸ (h_coatom a ha).symm ▸ ha, end end galois_insertion namespace galois_coinsertion variables [partial_order α] [partial_order β] lemma is_coatom_of_l_top [order_top α] [order_top β] {l : α → β} {u : β → α} (gi : galois_coinsertion l u) (hbot : l ⊤ = ⊤) {a : α} (hb : is_coatom (l a)) : is_coatom a := gi.dual.is_atom_of_u_bot hbot hb.dual lemma is_coatom_iff [order_top α] [order_top β] [is_coatomic β] {l : α → β} {u : β → α} (gi : galois_coinsertion l u) (htop : l ⊤ = ⊤) (h_coatom : ∀ b, is_coatom b → l (u b) = b) (b : β) : is_coatom (u b) ↔ is_coatom b := gi.dual.is_atom_iff htop h_coatom b lemma is_coatom_iff' [order_top α] [order_top β] [is_coatomic β] {l : α → β} {u : β → α} (gi : galois_coinsertion l u) (htop : l ⊤ = ⊤) (h_coatom : ∀ b, is_coatom b → l (u b) = b) (a : α) : is_coatom (l a) ↔ is_coatom a := gi.dual.is_atom_iff' htop h_coatom a lemma is_atom_of_image [order_bot α] [order_bot β] {l : α → β} {u : β → α} (gi : galois_coinsertion l u) {a : α} (hb : is_atom (l a)) : is_atom a := gi.dual.is_coatom_of_image hb.dual lemma is_atom_iff [order_bot α] [order_bot β] [is_atomic β] {l : α → β} {u : β → α} (gi : galois_coinsertion l u) (h_atom : ∀ b, is_atom b → l (u b) = b) (a : α) : is_atom (l a) ↔ is_atom a := gi.dual.is_coatom_iff h_atom a end galois_coinsertion namespace order_iso variables [partial_order α] [partial_order β] @[simp] lemma is_atom_iff [order_bot α] [order_bot β] (f : α ≃o β) (a : α) : is_atom (f a) ↔ is_atom a := ⟨f.to_galois_coinsertion.is_atom_of_image, λ ha, f.to_galois_insertion.is_atom_of_u_bot (map_bot f.symm) $ (f.symm_apply_apply a).symm ▸ ha⟩ @[simp] lemma is_coatom_iff [order_top α] [order_top β] (f : α ≃o β) (a : α) : is_coatom (f a) ↔ is_coatom a := f.dual.is_atom_iff a lemma is_simple_order_iff [bounded_order α] [bounded_order β] (f : α ≃o β) : is_simple_order α ↔ is_simple_order β := by rw [is_simple_order_iff_is_atom_top, is_simple_order_iff_is_atom_top, ← f.is_atom_iff ⊤, f.map_top] lemma is_simple_order [bounded_order α] [bounded_order β] [h : is_simple_order β] (f : α ≃o β) : is_simple_order α := f.is_simple_order_iff.mpr h protected lemma is_atomic_iff [order_bot α] [order_bot β] (f : α ≃o β) : is_atomic α ↔ is_atomic β := by simp only [is_atomic_iff, f.surjective.forall, f.surjective.exists, ← map_bot f, f.eq_iff_eq, f.le_iff_le, f.is_atom_iff] protected lemma is_coatomic_iff [order_top α] [order_top β] (f : α ≃o β) : is_coatomic α ↔ is_coatomic β := by simp only [← is_atomic_dual_iff_is_coatomic, f.dual.is_atomic_iff] end order_iso section is_modular_lattice variables [lattice α] [bounded_order α] [is_modular_lattice α] namespace is_compl variables {a b : α} (hc : is_compl a b) include hc lemma is_atom_iff_is_coatom : is_atom a ↔ is_coatom b := set.is_simple_order_Iic_iff_is_atom.symm.trans $ hc.Iic_order_iso_Ici.is_simple_order_iff.trans set.is_simple_order_Ici_iff_is_coatom lemma is_coatom_iff_is_atom : is_coatom a ↔ is_atom b := hc.symm.is_atom_iff_is_coatom.symm end is_compl variables [complemented_lattice α] lemma is_coatomic_of_is_atomic_of_complemented_lattice_of_is_modular [is_atomic α] : is_coatomic α := ⟨λ x, begin rcases exists_is_compl x with ⟨y, xy⟩, apply (eq_bot_or_exists_atom_le y).imp _ _, { rintro rfl, exact eq_top_of_is_compl_bot xy }, { rintro ⟨a, ha, ay⟩, rcases exists_is_compl (xy.symm.Iic_order_iso_Ici ⟨a, ay⟩) with ⟨⟨b, xb⟩, hb⟩, refine ⟨↑(⟨b, xb⟩ : set.Ici x), is_coatom.of_is_coatom_coe_Ici _, xb⟩, rw [← hb.is_atom_iff_is_coatom, order_iso.is_atom_iff], apply ha.Iic } end⟩ lemma is_atomic_of_is_coatomic_of_complemented_lattice_of_is_modular [is_coatomic α] : is_atomic α := is_coatomic_dual_iff_is_atomic.1 is_coatomic_of_is_atomic_of_complemented_lattice_of_is_modular theorem is_atomic_iff_is_coatomic : is_atomic α ↔ is_coatomic α := ⟨λ h, @is_coatomic_of_is_atomic_of_complemented_lattice_of_is_modular _ _ _ _ _ h, λ h, @is_atomic_of_is_coatomic_of_complemented_lattice_of_is_modular _ _ _ _ _ h⟩ end is_modular_lattice namespace set lemma is_atom_singleton (x : α) : is_atom ({x} : set α) := ⟨singleton_ne_empty _, λ s hs, ssubset_singleton_iff.mp hs⟩ lemma is_atom_iff (s : set α) : is_atom s ↔ ∃ x, s = {x} := begin refine ⟨_, by { rintro ⟨x, rfl⟩, exact is_atom_singleton x }⟩, rw [is_atom_iff, bot_eq_empty, ←nonempty_iff_ne_empty], rintro ⟨⟨x, hx⟩, hs⟩, exact ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, λ y hy, (hs {y} (singleton_ne_empty _) (singleton_subset_iff.2 hy) hx).symm⟩⟩, end lemma is_coatom_iff (s : set α) : is_coatom s ↔ ∃ x, s = {x}ᶜ := by simp_rw [is_compl_compl.is_coatom_iff_is_atom, is_atom_iff, @eq_comm _ s, compl_eq_comm] lemma is_coatom_singleton_compl (x : α) : is_coatom ({x}ᶜ : set α) := (is_coatom_iff {x}ᶜ).mpr ⟨x, rfl⟩ instance : is_atomistic (set α) := { eq_Sup_atoms := λ s, ⟨(λ x, {x}) '' s, by rw [Sup_eq_sUnion, sUnion_image, bUnion_of_singleton], by { rintro - ⟨x, hx, rfl⟩, exact is_atom_singleton x }⟩ } instance : is_coatomistic (set α) := { eq_Inf_coatoms := λ s, ⟨(λ x, {x}ᶜ) '' sᶜ, by rw [Inf_eq_sInter, sInter_image, ←compl_Union₂, bUnion_of_singleton, compl_compl], by { rintro - ⟨x, hx, rfl⟩, exact is_coatom_singleton_compl x }⟩ } end set
985e9d2bbcaf07617c6d9eeb6e3a4275f15af88a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/IO2.lean
8235b822005680aa6a15769b7c7f24e6cf6af0a4
[ "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
383
lean
import system.io open list io /- B and unit must be in the same universe So, we must put B at Type₁ or use poly_unit since unit is at Type₁ -/ definition foreach {A : Type} {B : Type} : list A → (A → io B) → io punit | [] f := return punit.star | (x::xs) f := do f x, foreach xs f #eval foreach [1,2,3,4,5] (λ i, do put_str "value: ", print i, put_str "\n")
c41d46efbcb0ffae18f96c6ca8fd9c4a32afc311
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/Simp.lean
7361938464ad6ae2e1bdc4717a33b7eddba61e07
[ "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
2,604
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.ReduceJpArity import Lean.Compiler.LCNF.Renaming import Lean.Compiler.LCNF.Simp.Basic import Lean.Compiler.LCNF.Simp.FunDeclInfo import Lean.Compiler.LCNF.Simp.JpCases import Lean.Compiler.LCNF.Simp.Config import Lean.Compiler.LCNF.Simp.InlineCandidate import Lean.Compiler.LCNF.Simp.SimpM import Lean.Compiler.LCNF.Simp.Main import Lean.Compiler.LCNF.Simp.InlineProj import Lean.Compiler.LCNF.Simp.DefaultAlt import Lean.Compiler.LCNF.Simp.SimpValue import Lean.Compiler.LCNF.Simp.Used namespace Lean.Compiler.LCNF open Simp def Decl.simp? (decl : Decl) : SimpM (Option Decl) := do updateFunDeclInfo decl.value trace[Compiler.simp.inline.info] "{decl.name}:{Format.nest 2 (← (← get).funDeclInfoMap.format)}" traceM `Compiler.simp.step do ppDecl decl let value ← simp decl.value let s ← get let value ← value.applyRenaming s.binderRenaming traceM `Compiler.simp.step.new do return m!"{decl.name} :=\n{← ppCode value}" trace[Compiler.simp.stat] "{decl.name}, size: {value.size}, # visited: {s.visited}, # inline: {s.inline}, # inline local: {s.inlineLocal}" if let some value ← simpJpCases? value then let decl := { decl with value } decl.reduceJpArity else if (← get).simplified then return some { decl with value } else return none partial def Decl.simp (decl : Decl) (config : Config) : CompilerM Decl := do let mut config := config if (← isTemplateLike decl) then /- We do not eta-expand or inline partial applications in template like code. Recall we don't want to generate code for them. Remark: by eta-expanding partial applications in instances, we also make the simplifier work harder when inlining instance projections. -/ config := { config with etaPoly := false, inlinePartial := false } go decl config where go (decl : Decl) (config : Config) : CompilerM Decl := do if let some decl ← decl.simp? |>.run { config, declName := decl.name } |>.run' {} |>.run {} then -- TODO: bound number of steps? go decl config else return decl def simp (config : Config := {}) (occurrence : Nat := 0) : Pass := .mkPerDeclaration `simp (Decl.simp · config) .base (occurrence := occurrence) builtin_initialize registerTraceClass `Compiler.simp (inherited := true) registerTraceClass `Compiler.simp.stat registerTraceClass `Compiler.simp.step registerTraceClass `Compiler.simp.step.new
49f0c258c53fe084a90c960e618473adbca27a63
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Scopes.lean
56ac510af69fb8fc1646a226e1bd477744e23521
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,706
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 /- Scope management TODO: delete after we delete parser implemented in C++. We have decided to store scope information at ElabState -/ structure ScopeManagerState := (allNamespaces : NameSet := {}) /- Stack of namespaces for each each open namespace and section -/ (namespaces : List Name := []) /- Stack of namespace/section headers -/ (headers : List Name := []) (isNamespace : List Bool := []) namespace ScopeManagerState instance : Inhabited ScopeManagerState := ⟨{}⟩ def saveNamespace (s : ScopeManagerState) (n : Name) : ScopeManagerState := { s with allNamespaces := s.allNamespaces.insert n } end ScopeManagerState def regScopeManagerExtension : IO (SimplePersistentEnvExtension Name ScopeManagerState) := registerSimplePersistentEnvExtension { name := `scopes, addImportedFn := fun as => mkStateFromImportedEntries ScopeManagerState.saveNamespace {} as, addEntryFn := fun s n => { s with allNamespaces := s.allNamespaces.insert n }, } @[init regScopeManagerExtension] constant scopeManagerExt : SimplePersistentEnvExtension Name ScopeManagerState := arbitrary _ namespace Environment @[export lean_get_namespaces] def getNamespaces (env : Environment) : List Name := (scopeManagerExt.getState env).namespaces def getNamespaceSet (env : Environment) : NameSet := (scopeManagerExt.getState env).allNamespaces @[export lean_is_namespace] def isNamespace (env : Environment) (n : Name) : Bool := env.getNamespaceSet.contains n @[export lean_in_section] def inSection (env : Environment) : Bool := match (scopeManagerExt.getState env).isNamespace with | (b::_) => !b | _ => false @[export lean_has_open_scopes] def hasOpenScopes (env : Environment) : Bool := !env.getNamespaces.isEmpty @[export lean_get_namespace] def getNamespace (env : Environment) : Name := match env.getNamespaces with | (n::_) => n | _ => Name.anonymous @[export lean_get_scope_header] def getScopeHeader (env : Environment) : Name := match (scopeManagerExt.getState env).headers with | (n::_) => n | _ => Name.anonymous @[export lean_to_valid_namespace] def toValidNamespace (env : Environment) (n : Name) : Option Name := let s := scopeManagerExt.getState env; if s.allNamespaces.contains n then some n else s.namespaces.foldl (fun r ns => match r with | some _ => r | none => let c := ns ++ n; if s.allNamespaces.contains c then some c else none) none def registerNamespaceAux (env : Environment) (n : Name) : Environment := if env.getNamespaceSet.contains n then env else scopeManagerExt.addEntry env n @[export lean_register_namespace] def registerNamespace : Environment → Name → Environment | env, n@(Name.str p _ _) => registerNamespace (registerNamespaceAux env n) p | env, _ => env def pushScopeCore (env : Environment) (header : Name) (isNamespace : Bool) : Environment := let ns := env.getNamespace; let newNs := if isNamespace then ns ++ header else ns; let env := env.registerNamespaceAux newNs; let env := scopeManagerExt.modifyState env $ fun s => { s with headers := header :: s.headers, namespaces := newNs :: s.namespaces, isNamespace := isNamespace :: s.isNamespace }; env def popScopeCore (env : Environment) : Environment := if env.getNamespaces.isEmpty then env else scopeManagerExt.modifyState env $ fun s => { s with headers := s.headers.tail!, namespaces := s.namespaces.tail!, isNamespace := s.isNamespace.tail! } end Environment end Lean
fc7b2a718407211c9af9134308378b4b564f0e98
2cf781335f4a6706b7452ab07ce323201e2e101f
/lean/deps/galois_stdlib/src/galois/data/char.lean
027e0d14ba6cd79874f2f9fe2531eade1ad9eec9
[ "Apache-2.0" ]
permissive
simonjwinwood/reopt-vcg
697cdd5e68366b5aa3298845eebc34fc97ccfbe2
6aca24e759bff4f2230bb58270bac6746c13665e
refs/heads/master
1,586,353,878,347
1,549,667,148,000
1,549,667,148,000
159,409,828
0
0
null
1,543,358,444,000
1,543,358,444,000
null
UTF-8
Lean
false
false
2,775
lean
import galois.logic import tactic.fin_cases namespace char /-- Predicate that holds if character is a 7-bit ascii printable character. -/ def is_ascii7_printable (c:char) : Prop := 0x20 ≤ c.val ∧ c.val ≤ 0x7e local attribute [reducible] is_ascii7_printable namespace is_ascii7_printable instance decidable : decidable_pred is_ascii7_printable := by apply_instance end is_ascii7_printable theorem alpha_is_printable {c:char} : c.is_alpha → c.is_ascii7_printable := begin unfold is_alpha, unfold is_ascii7_printable, intro isa, cases isa; { simp [is_upper, is_lower] at isa, apply and.intro, { transitivity, tactic.swap, exact isa.left, exact dec_trivial, }, { transitivity, exact isa.right, exact dec_trivial, }, }, end theorem digit_is_printable {c:char} : c.is_digit → c.is_ascii7_printable := begin unfold is_digit, intro isd, apply and.intro, { transitivity, tactic.swap, exact isd.left, exact dec_trivial, }, { transitivity, exact isd.right, exact dec_trivial, }, end theorem digit_char_is_digit (i:ℕ) (p : i < 10): is_digit (nat.digit_char i) := begin unfold nat.digit_char, have q : 0 ≤ i := nat.zero_le _, -- Repeatedly try numbers starting from zero until we can't prove the theorem. repeat { cases (nat.eq_or_lt_of_le q) with h lt, case or.inl : h { simp only [h.symm, if_pos], exact (of_as_true trivial), }, simp only [(ne_of_lt lt).symm, if_false], have q := nat.succ_le_of_lt lt, }, -- The last q should assert that i is at least 10 have q : 10 ≤ i := q, have r := not_lt_of_ge q, contradiction, end section protected theorem le_refl : ∀ a : char, a ≤ a := begin intro c, unfold has_le.le, unfold char.le, end end protected theorem le_trans : ∀ a b c : char, a ≤ b → b ≤ c → a ≤ c := begin intros a b c, unfold has_le.le, unfold char.le, apply le_trans, end protected theorem lt_iff_le_not_le : ∀ a b : char, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := begin intros a b, unfold has_le.le, unfold char.le, unfold has_lt.lt, unfold char.lt, apply lt_iff_le_not_le , end protected theorem le_antisymm : ∀ a b : char, a ≤ b → b ≤ a → a = b := begin intros a b, cases a, cases b, unfold has_le.le, unfold char.le, intros a_le_b b_le_a, exact eq_of_veq (le_antisymm a_le_b b_le_a), end protected theorem le_total : ∀ a b : char, a ≤ b ∨ b ≤ a := begin intros a b, unfold has_le.le, unfold char.le, apply le_total end -- Show characters have a linear order. instance : linear_order char := { le := char.le , le_refl := char.le_refl , le_trans := char.le_trans , lt := char.lt , lt_iff_le_not_le := char.lt_iff_le_not_le , le_antisymm := char.le_antisymm , le_total := char.le_total } end char
8b5790e2841d42f8caff79e6271421af7ea2df34
a5e2e6395319779f21675263bc0e486be5bc03bd
/bench/asymptotics.lean
5607e943496291a592a4bea2d60cfa8781eed645
[ "MIT" ]
permissive
AndrasKovacs/smalltt
10f0ec55fb3f487e9dd21a740fe1a899e0cdb790
c306f727ba3c92abe6ef75013da5a5dade6b15c8
refs/heads/master
1,689,497,785,394
1,680,893,106,000
1,680,893,106,000
112,098,494
483
26
MIT
1,640,720,815,000
1,511,713,805,000
Lean
UTF-8
Lean
false
false
14,062
lean
set_option maxRecDepth 10000 universe i def CNat : Type 1 := ∀ (N : Type), (N → N) → N → N def czero : CNat := λ n s z => z def csuc : CNat → CNat := λ a n s z => s (a n s z) def Vec : Type → CNat → Type 1 := λ A n => ∀ (V : CNat → Type), (∀ n, A → V n → V (csuc n)) → V czero → V n def nil {A:Type} : Vec A czero := λ V c n => n def cons {A:Type} {n:CNat} : A → Vec A n → Vec A (csuc n) := λ x xs V c nil => c n x (xs V c nil) def Pair : Type i -> Type i -> Type (i + 1) := λ A B => ∀ (P : Type i), (A → B → P) → P def dup : ∀ {A : Type i}, A → Pair A A := λ a P p => p a a -------------------------------------------------------------------------------- -- fails -- def idTest {A : Type} : A → A -- := id id id id id id id id id id id id id id id id id id id id -- id id id id id id id id id id id id id id id id id id id id -- fails, but! 20 still works, memory usage is low constant, and only -- the "compilation" phase in --profile appears to be exponential -- def pairTest := -- let x0 := dup true ; -- let x1 := dup x0 ; -- let x2 := dup x1 ; -- let x3 := dup x2 ; -- let x4 := dup x3 ; -- let x5 := dup x4 ; -- let x6 := dup x5 ; -- let x7 := dup x6 ; -- let x8 := dup x7 ; -- let x9 := dup x8 ; -- let x10 := dup x9 ; -- let x11 := dup x10 ; -- let x12 := dup x11 ; -- let x13 := dup x12 ; -- let x14 := dup x13 ; -- let x15 := dup x14 ; -- let x16 := dup x15 ; -- let x17 := dup x16 ; -- let x18 := dup x17 ; -- let x19 := dup x18 ; -- let x20 := dup x19 ; -- let x21 := dup x20 ; -- let x22 := dup x21 ; -- let x23 := dup x22 ; -- let x24 := dup x23 ; -- let x25 := dup x24 ; -- let x26 := dup x25 ; -- let x27 := dup x26 ; -- let x28 := dup x27 ; -- let x29 := dup x28 ; -- let x30 := dup x29 ; -- x30 def vecTest := (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true (cons true nil )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))
3011896a55895445d5bab9e0981c6be998773ed1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/invertible.lean
8a980c994d89095b2693d8adee1f17b3a1ea793e
[ "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
11,956
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.group.units import algebra.ne_zero import algebra.ring.basic /-! # Invertible elements This file defines a typeclass `invertible a` for elements `a` with a two-sided multiplicative inverse. The intent of the typeclass is to provide a way to write e.g. `⅟2` in a ring like `ℤ[1/2]` where some inverses exist but there is no general `⁻¹` operator; or to specify that a field has characteristic `≠ 2`. It is the `Type`-valued analogue to the `Prop`-valued `is_unit`. For constructions of the invertible element given a characteristic, see `algebra/char_p/invertible` and other lemmas in that file. ## Notation * `⅟a` is `invertible.inv_of a`, the inverse of `a` ## Implementation notes The `invertible` class lives in `Type`, not `Prop`, to make computation easier. If multiplication is associative, `invertible` is a subsingleton anyway. The `simp` normal form tries to normalize `⅟a` to `a ⁻¹`. Otherwise, it pushes `⅟` inside the expression as much as possible. Since `invertible a` is not a `Prop` (but it is a `subsingleton`), we have to be careful about coherence issues: we should avoid having multiple non-defeq instances for `invertible a` in the same context. This file plays it safe and uses `def` rather than `instance` for most definitions, users can choose which instances to use at the point of use. For example, here's how you can use an `invertible 1` instance: ```lean variables {α : Type*} [monoid α] def something_that_needs_inverses (x : α) [invertible x] := sorry section local attribute [instance] invertible_one def something_one := something_that_needs_inverses 1 end ``` ## Tags invertible, inverse element, inv_of, a half, one half, a third, one third, ½, ⅓ -/ universes u variables {α : Type u} /-- `invertible a` gives a two-sided multiplicative inverse of `a`. -/ class invertible [has_mul α] [has_one α] (a : α) : Type u := (inv_of : α) (inv_of_mul_self : inv_of * a = 1) (mul_inv_of_self : a * inv_of = 1) -- This notation has the same precedence as `has_inv.inv`. notation `⅟`:1034 := invertible.inv_of @[simp] lemma inv_of_mul_self [has_mul α] [has_one α] (a : α) [invertible a] : ⅟a * a = 1 := invertible.inv_of_mul_self @[simp] lemma mul_inv_of_self [has_mul α] [has_one α] (a : α) [invertible a] : a * ⅟a = 1 := invertible.mul_inv_of_self @[simp] lemma inv_of_mul_self_assoc [monoid α] (a b : α) [invertible a] : ⅟a * (a * b) = b := by rw [←mul_assoc, inv_of_mul_self, one_mul] @[simp] lemma mul_inv_of_self_assoc [monoid α] (a b : α) [invertible a] : a * (⅟a * b) = b := by rw [←mul_assoc, mul_inv_of_self, one_mul] @[simp] lemma mul_inv_of_mul_self_cancel [monoid α] (a b : α) [invertible b] : a * ⅟b * b = a := by simp [mul_assoc] @[simp] lemma mul_mul_inv_of_self_cancel [monoid α] (a b : α) [invertible b] : a * b * ⅟b = a := by simp [mul_assoc] lemma inv_of_eq_right_inv [monoid α] {a b : α} [invertible a] (hac : a * b = 1) : ⅟a = b := left_inv_eq_right_inv (inv_of_mul_self _) hac lemma inv_of_eq_left_inv [monoid α] {a b : α} [invertible a] (hac : b * a = 1) : ⅟a = b := (left_inv_eq_right_inv hac (mul_inv_of_self _)).symm lemma invertible_unique {α : Type u} [monoid α] (a b : α) [invertible a] [invertible b] (h : a = b) : ⅟a = ⅟b := by { apply inv_of_eq_right_inv, rw [h, mul_inv_of_self], } instance [monoid α] (a : α) : subsingleton (invertible a) := ⟨ λ ⟨b, hba, hab⟩ ⟨c, hca, hac⟩, by { congr, exact left_inv_eq_right_inv hba hac } ⟩ /-- If `r` is invertible and `s = r`, then `s` is invertible. -/ def invertible.copy [mul_one_class α] {r : α} (hr : invertible r) (s : α) (hs : s = r) : invertible s := { inv_of := ⅟r, inv_of_mul_self := by rw [hs, inv_of_mul_self], mul_inv_of_self := by rw [hs, mul_inv_of_self] } /-- An `invertible` element is a unit. -/ @[simps] def unit_of_invertible [monoid α] (a : α) [invertible a] : αˣ := { val := a, inv := ⅟a, val_inv := by simp, inv_val := by simp, } lemma is_unit_of_invertible [monoid α] (a : α) [invertible a] : is_unit a := ⟨unit_of_invertible a, rfl⟩ /-- Units are invertible in their associated monoid. -/ def units.invertible [monoid α] (u : αˣ) : invertible (u : α) := { inv_of := ↑(u⁻¹), inv_of_mul_self := u.inv_mul, mul_inv_of_self := u.mul_inv } @[simp] lemma inv_of_units [monoid α] (u : αˣ) [invertible (u : α)] : ⅟(u : α) = ↑(u⁻¹) := inv_of_eq_right_inv u.mul_inv lemma is_unit.nonempty_invertible [monoid α] {a : α} (h : is_unit a) : nonempty (invertible a) := let ⟨x, hx⟩ := h in ⟨x.invertible.copy _ hx.symm⟩ /-- Convert `is_unit` to `invertible` using `classical.choice`. Prefer `casesI h.nonempty_invertible` over `letI := h.invertible` if you want to avoid choice. -/ noncomputable def is_unit.invertible [monoid α] {a : α} (h : is_unit a) : invertible a := classical.choice h.nonempty_invertible @[simp] lemma nonempty_invertible_iff_is_unit [monoid α] (a : α) : nonempty (invertible a) ↔ is_unit a := ⟨nonempty.rec $ @is_unit_of_invertible _ _ _, is_unit.nonempty_invertible⟩ /-- Each element of a group is invertible. -/ def invertible_of_group [group α] (a : α) : invertible a := ⟨a⁻¹, inv_mul_self a, mul_inv_self a⟩ @[simp] lemma inv_of_eq_group_inv [group α] (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_self a) /-- `1` is the inverse of itself -/ def invertible_one [monoid α] : invertible (1 : α) := ⟨1, mul_one _, one_mul _⟩ @[simp] lemma inv_of_one [monoid α] [invertible (1 : α)] : ⅟(1 : α) = 1 := inv_of_eq_right_inv (mul_one _) /-- `-⅟a` is the inverse of `-a` -/ def invertible_neg [has_mul α] [has_one α] [has_distrib_neg α] (a : α) [invertible a] : invertible (-a) := ⟨-⅟a, by simp, by simp ⟩ @[simp] lemma inv_of_neg [monoid α] [has_distrib_neg α] (a : α) [invertible a] [invertible (-a)] : ⅟(-a) = -⅟a := inv_of_eq_right_inv (by simp) @[simp] lemma one_sub_inv_of_two [ring α] [invertible (2:α)] : 1 - (⅟2:α) = ⅟2 := (is_unit_of_invertible (2:α)).mul_right_inj.1 $ by rw [mul_sub, mul_inv_of_self, mul_one, bit0, add_sub_cancel] @[simp] lemma inv_of_two_add_inv_of_two [non_assoc_semiring α] [invertible (2 : α)] : (⅟2 : α) + (⅟2 : α) = 1 := by rw [←two_mul, mul_inv_of_self] /-- `a` is the inverse of `⅟a`. -/ instance invertible_inv_of [has_one α] [has_mul α] {a : α} [invertible a] : invertible (⅟a) := ⟨ a, mul_inv_of_self a, inv_of_mul_self a ⟩ @[simp] lemma inv_of_inv_of [monoid α] (a : α) [invertible a] [invertible (⅟a)] : ⅟(⅟a) = a := inv_of_eq_right_inv (inv_of_mul_self _) @[simp] lemma inv_of_inj [monoid α] {a b : α} [invertible a] [invertible b] : ⅟ a = ⅟ b ↔ a = b := ⟨invertible_unique _ _, invertible_unique _ _⟩ /-- `⅟b * ⅟a` is the inverse of `a * b` -/ def invertible_mul [monoid α] (a b : α) [invertible a] [invertible b] : invertible (a * b) := ⟨ ⅟b * ⅟a, by simp [←mul_assoc], by simp [←mul_assoc] ⟩ @[simp] lemma inv_of_mul [monoid α] (a b : α) [invertible a] [invertible b] [invertible (a * b)] : ⅟(a * b) = ⅟b * ⅟a := inv_of_eq_right_inv (by simp [←mul_assoc]) theorem commute.inv_of_right [monoid α] {a b : α} [invertible b] (h : commute a b) : commute a (⅟b) := calc a * (⅟b) = (⅟b) * (b * a * (⅟b)) : by simp [mul_assoc] ... = (⅟b) * (a * b * ((⅟b))) : by rw h.eq ... = (⅟b) * a : by simp [mul_assoc] theorem commute.inv_of_left [monoid α] {a b : α} [invertible b] (h : commute b a) : commute (⅟b) a := calc (⅟b) * a = (⅟b) * (a * b * (⅟b)) : by simp [mul_assoc] ... = (⅟b) * (b * a * (⅟b)) : by rw h.eq ... = a * (⅟b) : by simp [mul_assoc] lemma commute_inv_of {M : Type*} [has_one M] [has_mul M] (m : M) [invertible m] : commute m (⅟m) := calc m * ⅟m = 1 : mul_inv_of_self m ... = ⅟ m * m : (inv_of_mul_self m).symm lemma nonzero_of_invertible [mul_zero_one_class α] (a : α) [nontrivial α] [invertible a] : a ≠ 0 := λ ha, zero_ne_one $ calc 0 = ⅟a * a : by simp [ha] ... = 1 : inv_of_mul_self a @[priority 100] instance invertible.ne_zero [mul_zero_one_class α] [nontrivial α] (a : α) [invertible a] : ne_zero a := ⟨nonzero_of_invertible a⟩ section monoid_with_zero variable [monoid_with_zero α] /-- A variant of `ring.inverse_unit`. -/ @[simp] lemma ring.inverse_invertible (x : α) [invertible x] : ring.inverse x = ⅟x := ring.inverse_unit (unit_of_invertible _) end monoid_with_zero section group_with_zero variable [group_with_zero α] /-- `a⁻¹` is an inverse of `a` if `a ≠ 0` -/ def invertible_of_nonzero {a : α} (h : a ≠ 0) : invertible a := ⟨ a⁻¹, inv_mul_cancel h, mul_inv_cancel h ⟩ @[simp] lemma inv_of_eq_inv (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_cancel (nonzero_of_invertible a)) @[simp] lemma inv_mul_cancel_of_invertible (a : α) [invertible a] : a⁻¹ * a = 1 := inv_mul_cancel (nonzero_of_invertible a) @[simp] lemma mul_inv_cancel_of_invertible (a : α) [invertible a] : a * a⁻¹ = 1 := mul_inv_cancel (nonzero_of_invertible a) @[simp] lemma div_mul_cancel_of_invertible (a b : α) [invertible b] : a / b * b = a := div_mul_cancel a (nonzero_of_invertible b) @[simp] lemma mul_div_cancel_of_invertible (a b : α) [invertible b] : a * b / b = a := mul_div_cancel a (nonzero_of_invertible b) @[simp] lemma div_self_of_invertible (a : α) [invertible a] : a / a = 1 := div_self (nonzero_of_invertible a) /-- `b / a` is the inverse of `a / b` -/ def invertible_div (a b : α) [invertible a] [invertible b] : invertible (a / b) := ⟨b / a, by simp [←mul_div_assoc], by simp [←mul_div_assoc]⟩ @[simp] lemma inv_of_div (a b : α) [invertible a] [invertible b] [invertible (a / b)] : ⅟(a / b) = b / a := inv_of_eq_right_inv (by simp [←mul_div_assoc]) /-- `a` is the inverse of `a⁻¹` -/ def invertible_inv {a : α} [invertible a] : invertible (a⁻¹) := ⟨ a, by simp, by simp ⟩ end group_with_zero /-- Monoid homs preserve invertibility. -/ def invertible.map {R : Type*} {S : Type*} {F : Type*} [mul_one_class R] [mul_one_class S] [monoid_hom_class F R S] (f : F) (r : R) [invertible r] : invertible (f r) := { inv_of := f (⅟r), inv_of_mul_self := by rw [←map_mul, inv_of_mul_self, map_one], mul_inv_of_self := by rw [←map_mul, mul_inv_of_self, map_one] } /-- Note that the `invertible (f r)` argument can be satisfied by using `letI := invertible.map f r` before applying this lemma. -/ lemma map_inv_of {R : Type*} {S : Type*} {F : Type*} [mul_one_class R] [monoid S] [monoid_hom_class F R S] (f : F) (r : R) [invertible r] [invertible (f r)] : f (⅟r) = ⅟(f r) := by { letI := invertible.map f r, convert rfl } /-- A monoid hom with a left-inverse that is also a monoid hom is invertible. The inverse is computed as `g (⅟(f r))` -/ @[simps {attrs := []}] def invertible.of_left_inverse {R : Type*} {S : Type*} {F G : Type*} [mul_one_class R] [mul_one_class S] [monoid_hom_class F R S] [monoid_hom_class G S R] (f : F) (g : G) (r : R) (h : function.left_inverse g f) [invertible (f r)] : invertible r := (invertible.map g (f r)).copy _ (h r).symm /-- Invertibility on either side of a monoid hom with a left-inverse is equivalent. -/ @[simps] def invertible_equiv_of_left_inverse {R : Type*} {S : Type*} {F G : Type*} [monoid R] [monoid S] [monoid_hom_class F R S] [monoid_hom_class G S R] (f : F) (g : G) (r : R) (h : function.left_inverse g f) : invertible (f r) ≃ invertible r := { to_fun := λ _, by exactI invertible.of_left_inverse f _ _ h, inv_fun := λ _, by exactI invertible.map f _, left_inv := λ x, subsingleton.elim _ _, right_inv := λ x, subsingleton.elim _ _ }
8b481232c70058c85750e41a0b27eda30d04814a
5ae26df177f810c5006841e9c73dc56e01b978d7
/test/norm_cast.lean
04f8e12710fc04b875adff18dc7849e08eee0d8a
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
2,668
lean
/- Tests for norm_cast -/ import tactic.norm_cast import data.complex.basic -- ℕ, ℤ, ℚ, ℝ, ℂ constants (an bn cn dn : ℕ) (az bz cz dz : ℤ) (aq bq cq dq : ℚ) constants (ar br cr dr : ℝ) (ac bc cc dc : ℂ) example : (an : ℤ) = bn → an = bn := λ h, by exact_mod_cast h -- by simp example : an = bn → (an : ℤ) = bn := λ h, by exact_mod_cast h -- by simp example : az = bz ↔ (az : ℚ) = bz := by norm_cast -- by simp example : (aq : ℝ) = br ↔ (aq : ℂ) = br := by norm_cast example : (an : ℚ) = bz ↔ (an : ℂ) = bz := by norm_cast example : (((an : ℤ) : ℚ) : ℝ) = bq ↔ ((an : ℚ) : ℂ) = (bq : ℝ) := by norm_cast example : (an : ℤ) < bn ↔ an < bn := by norm_cast -- by simp example : (an : ℚ) < bz ↔ (an : ℝ) < bz := by norm_cast example : ((an : ℤ) : ℝ) < bq ↔ (an : ℚ) < bq := by norm_cast example : (an : ℤ) ≠ (bn : ℤ) ↔ an ≠ bn := by norm_cast -- by simp -- zero and one cause special problems example : 0 < (bq : ℝ) ↔ 0 < bq := by norm_cast -- by simp example : az > (1 : ℕ) ↔ az > 1 := by norm_cast -- by simp example : az > (0 : ℕ) ↔ az > 0 := by norm_cast -- by simp example : (an : ℤ) ≠ 0 ↔ an ≠ 0 := by norm_cast -- by simp example : aq < (1 : ℕ) ↔ (aq : ℝ) < (1 : ℤ) := by norm_cast example : (an : ℤ) + bn = (an + bn : ℕ) := by norm_cast -- by simp example : (an : ℂ) + bq = ((an + bq) : ℚ) := by norm_cast -- by simp example : (((an : ℤ) : ℚ) : ℝ) + bn = (an + (bn : ℤ)) := by norm_cast -- by simp example : (((((an : ℚ) : ℝ) * bq) + (cq : ℝ) ^ dn) : ℂ) = (an : ℂ) * (bq : ℝ) + cq ^ dn := by norm_cast -- by simp example : ((an : ℤ) : ℝ) < bq ∧ (cr : ℂ) ^ 2 = dz ↔ (an : ℚ) < bq ∧ ((cr ^ 2) : ℂ) = dz := by norm_cast example : (an : ℤ) = 1 → an = 1 := λ h, by exact_mod_cast h example : (an : ℤ) < 5 → an < 5 := λ h, by exact_mod_cast h example : an < 5 → (an : ℤ) < 5 := λ h, by exact_mod_cast h example : (an + 5) < 10 → (an : ℤ) + 5 < 10 := λ h, by exact_mod_cast h example : (an : ℤ) + 5 < 10 → (an + 5) < 10 := λ h, by exact_mod_cast h example : ((an + 5 : ℕ) : ℤ) < 10 → an + 5 < 10 := λ h, by exact_mod_cast h example : an + 5 < 10 → ((an + 5 : ℕ) : ℤ) < 10 := λ h, by exact_mod_cast h example (h : bn ≤ an) : an - bn = 1 ↔ (an - bn : ℤ) = 1 := by norm_cast example (h : (cz : ℚ) = az / bz) : (cz : ℝ) = az / bz := by assumption_mod_cast example : aq * bq = rat.mk (aq.num * bq.num) (↑aq.denom * ↑bq.denom) := by rw_mod_cast rat.mul_num_denom example (h : an = 0) : (an : ℝ) = (bn : ℂ).im := by exact_mod_cast h
3ed18f66553491b5d9705a3a413a0bf4bdde0232
28be2ab6091504b6ba250b367205fb94d50ab284
/src/game/intro.lean
e2899716ea7472f8da19b0dcd87cc4bef1499683
[ "Apache-2.0" ]
permissive
postmasters/natural_number_game
87304ac22e5e1c5ac2382d6e523d6914dd67a92d
38a7adcdfdb18c49c87b37831736c8f15300d821
refs/heads/master
1,649,856,819,031
1,586,444,676,000
1,586,444,676,000
255,006,061
0
0
Apache-2.0
1,586,664,599,000
1,586,664,598,000
null
UTF-8
Lean
false
false
3,755
lean
/- # The Natural Number Game, version 1.2rc2 ## By Kevin Buzzard and Mohammad Pedramfar. Works in Chrome. Usually works in other browsers. If you see "Lean is busy" and it hasn't gone away after about 20 seconds, try Chrome. Recent Firefox works fine. Safari 13.0.3 has been reported not to work, but Safari 13.1 apparently works fine. Cookies need to be enabled to make Lean work in your browser. # What is this game? Welcome to the natural number game -- a part-book part-game which shows the power of induction. Blue nodes on the graph are ones that you are ready to enter. Grey nodes you should stay away from -- a grey node turns blue when *all* nodes above it are complete. Green nodes are completed. In this game, you get own version of the natural numbers, called `mynat`, in a programming language called Lean. Your version of the natural numbers satisfies something called the principle of mathematical induction, and a couple of other things too (Peano's axioms). Unfortunately, nobody has proved any theorems about these natural numbers yet. For example, addition will be defined for you, but nobody has proved that `x + y = y + x` yet. This is your job. You're going to prove mathematical theorems using the Lean theorem prover. In other words, you're going to solve levels in a computer game. You're going to prove these theorems using *tactics*. The introductory world, Tutorial World, will take you through some of these tactics. During your proofs, your "goal" (i.e. what you're supposed to be proving) will be displayed with a `⊢` symbol in front of it. If the top right hand box reports "Theorem Proved!", you have closed all the goals in the level and can move on to the next level in the world you're in. When you've finished a world, hit "main menu" in the top left to get back here. # What's new? Lots of typo fixes. Thank you, all the people who made PR's and opened issues. This is Kevin's first ever open source project and it is an amazing experience. # What's to come? Still haven't ported the <a href="https://github.com/ImperialCollegeLondon/natural_number_game/blob/master/src/game/world10/level18a.lean" target="blank"> less-than worlds</a>. # Hey, real Lean works slightly differently to this Lean. What is going on? Here is a <a href="https://github.com/ImperialCollegeLondon/natural_number_game/blob/master/docs/technical.md" target="blank"> technical explanation</a> of how it all works. # I love these levels! Where can I get more of this stuff? Read about <a href="https://github.com/ImperialCollegeLondon/natural_number_game/blob/master/WHATS_NEXT.md" target="blank">what's next</a> here. # Thanks Special thanks to Rob Lewis for tactic hackery, Bryan Gin-Ge Chen for javascript hackery, Patrick Massot for his <a href="https://github.com/leanprover-community/format_lean" target="blank">Lean to html formatter</a>, Sian Carey for Power World, and, last but not least, all the people who fed back comments, including the 2019-20 Imperial College 1st year maths beta tester students, Marie-Amélie Lawn, Toby Gee, Joseph Myers, and all the people who have been in touch via the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a> or the <a href="https://xenaproject.wordpress.com/" target="blank">Xena Project blog</a> or via <a href="https://twitter.com/XenaProject" target="blank">Twitter</a>. The natural number game is brought to you by the Xena project, a project based at Imperial College London whose aim is to get mathematics undergraduates using computer theorem provers. Lean is a computer theorem prover being developed at Microsoft Research. Prove a theorem. Write a function. <a href="https://twitter.com/XenaProject" target="blank">@XenaProject</a>. -/
95cb25efa82ae72d3ef2297762a7f9d18c9eaec8
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/fin.lean
40cb6f6ca7d47d0b80678f342f6bb5d45e69fc9b
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
1,563
lean
import data.nat.basic open fin nat /-- Embedding of `fin n` in `fin (n+1)` -/ def raise_fin {n : ℕ} (k : fin n) : fin (n + 1) := ⟨val k, lt_succ_of_lt (is_lt k)⟩ theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩ instance fin_to_int (n : ℕ) : has_coe (fin n) int := ⟨λ k, ↑(fin.val k)⟩ variables {n : ℕ} {a b : fin n} protected theorem fin.succ.inj (p : fin.succ a = fin.succ b) : a = b := by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p)) @[elab_as_eliminator] def fin.succ_rec {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : ∀ {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (fin.succ_rec ⟨i, lt_of_succ_lt_succ h⟩) @[elab_as_eliminator] def fin.succ_rec_on {n : ℕ} (i : fin n) {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem fin.succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem fin.succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl
bcf45efb8f3329ad2feba238a715b5b8c554fee2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/offset_is_def_eq_trick.lean
2be963cf29e8e35bf885945db55f97b8a5cca555
[ "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
238
lean
universe variables u inductive Vec (α : Type u) : nat → Type u | nil {} : Vec 0 | cons : Π {n}, α → Vec n → Vec (nat.succ n) def head {α} : Π {n}, Vec α (n+1) → α | n (Vec.cons h t) := h #check @head.equations._eqn_1
d16ad129b698f8963978d566e38378522b74a261
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/complex/roots_of_unity.lean
29b7ab71c6eee0aafc86968d41316e285ed74055
[ "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
3,566
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import analysis.special_functions.trigonometric import ring_theory.roots_of_unity /-! # Complex roots of unity In this file we show that the `n`-th complex roots of unity are exactly the complex numbers `e ^ (2 * real.pi * complex.I * (i / n))` for `i ∈ finset.range n`. ## Main declarations * `complex.mem_roots_of_unity`: the complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. * `complex.card_roots_of_unity`: the number of `n`-th roots of unity is exactly `n`. -/ namespace complex open polynomial real open_locale nat real lemma is_primitive_root_exp_of_coprime (i n : ℕ) (h0 : n ≠ 0) (hi : i.coprime n) : is_primitive_root (exp (2 * π * I * (i / n))) n := begin rw is_primitive_root.iff_def, simp only [← exp_nat_mul, exp_eq_one_iff], have hn0 : (n : ℂ) ≠ 0, by exact_mod_cast h0, split, { use i, field_simp [hn0, mul_comm (i : ℂ), mul_comm (n : ℂ)] }, { simp only [hn0, mul_right_comm _ _ ↑n, mul_left_inj' two_pi_I_ne_zero, ne.def, not_false_iff, mul_comm _ (i : ℂ), ← mul_assoc _ (i : ℂ), exists_imp_distrib] with field_simps, norm_cast, rintro l k hk, have : n ∣ i * l, { rw [← int.coe_nat_dvd, hk], apply dvd_mul_left }, exact hi.symm.dvd_of_dvd_mul_left this } end lemma is_primitive_root_exp (n : ℕ) (h0 : n ≠ 0) : is_primitive_root (exp (2 * π * I / n)) n := by simpa only [nat.cast_one, one_div] using is_primitive_root_exp_of_coprime 1 n h0 n.coprime_one_left lemma is_primitive_root_iff (ζ : ℂ) (n : ℕ) (hn : n ≠ 0) : is_primitive_root ζ n ↔ (∃ (i < (n : ℕ)) (hi : i.coprime n), exp (2 * π * I * (i / n)) = ζ) := begin have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast hn, split, swap, { rintro ⟨i, -, hi, rfl⟩, exact is_primitive_root_exp_of_coprime i n hn hi }, intro h, obtain ⟨i, hi, rfl⟩ := (is_primitive_root_exp n hn).eq_pow_of_pow_eq_one h.pow_eq_one (nat.pos_of_ne_zero hn), refine ⟨i, hi, ((is_primitive_root_exp n hn).pow_iff_coprime (nat.pos_of_ne_zero hn) i).mp h, _⟩, rw [← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] end /-- The complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. -/ lemma mem_roots_of_unity (n : ℕ+) (x : units ℂ) : x ∈ roots_of_unity n ℂ ↔ (∃ i < (n : ℕ), exp (2 * π * I * (i / n)) = x) := begin rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, units.coe_one], have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast (n.ne_zero), split, { intro h, obtain ⟨i, hi, H⟩ : ∃ i < (n : ℕ), exp (2 * π * I / n) ^ i = x, { simpa only using (is_primitive_root_exp n n.ne_zero).eq_pow_of_pow_eq_one h n.pos }, refine ⟨i, hi, _⟩, rw [← H, ← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] }, { rintro ⟨i, hi, H⟩, rw [← H, ← exp_nat_mul, exp_eq_one_iff], use i, field_simp [hn0, mul_comm ((n : ℕ) : ℂ), mul_comm (i : ℂ)] } end lemma card_roots_of_unity (n : ℕ+) : fintype.card (roots_of_unity n ℂ) = n := (is_primitive_root_exp n n.ne_zero).card_roots_of_unity lemma card_primitive_roots (k : ℕ) (h : k ≠ 0) : (primitive_roots k ℂ).card = φ k := (is_primitive_root_exp k h).card_primitive_roots (nat.pos_of_ne_zero h) end complex
c8bb6d137ad502681f2ad9faa19ccf3cb52f7aca
618003631150032a5676f229d13a079ac875ff77
/src/tactic/ring.lean
e4d1f554d5c95bd6a0632832d434953a17bf2124
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
28,904
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache tactic α /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m ℕ := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache α, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(ℕ), using_new_ref ic $ λ r, using_new_ref nc $ λ nr, using_new_ref mk_buffer $ λ atoms, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : ring_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and `ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : ℚ) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr → expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr → bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr → string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr → tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do let n := c₁ + c₂, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n, return (ic, const e n, p) | he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``zero_add [e₂], return (ic, he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do c ← get_cache, if c₂ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr × ℚ) : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂, return (const e' (c₁ * c₂), p) | (const e₁ c₁) e₂ := if c₁ = 0 then do c ← get_cache, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂], return (const α0 0, p) else if c₁ = 1 then do p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul (e₁, c₁) e₂ | e₁ he₂@(const e₂ c₂) := do p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0), if b₂.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] theorem pow_succ {α} [comm_semiring α] (a n b c) (h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c := by rw [← h₂, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e], return (const α1 1, p) | e (_, 1) := do p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (e₂, m) := ic_lift $ λ ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic e₂, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', h₂) ← eval_pow a m, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const α0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂]) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := h /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%P %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``division_ring_has_div [], lift $ is_def_eq inst inst')) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | some k, `(nat.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p₃ ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], p₄ ← lift $ mk_eq_symm $ `(nat.pow_eq_pow).mk_app [e₁, e₂], p ← lift $ mk_eq_trans p₄ p₃, return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (e : expr) : tactic (expr × expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
e338a1e515f53f45cf138923c773dfcfee735a31
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/fractional_ideal.lean
b9049d7ac93716afc3e0eb38aca28b6f0019f7dd
[ "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
24,264
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.localization import ring_theory.principal_ideal_domain /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal f` is the type of fractional ideals in `P` * `has_coe (ideal R) (fractional_ideal f)` instance * `comm_semiring (fractional_ideal f)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal f)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R \ {0}` and `g` the natural ring hom from `R` to `K`. * `has_div (fractional_ideal g)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `right_inverse_eq` states that `1 / I` is the inverse of `I` if one exists ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`. In `ring_theory.localization`, we define a copy of the localization map `f`'s codomain `P` (`f.codomain`) so that the `R`-algebra instance on `P` can 'know' the map needed to induce the `R`-algebra structure. We don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `non_zero_divisors R`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open localization_map namespace ring section defs variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P] (f : localization_map S P) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R f.codomain) := ∃ a ∈ S, ∀ b ∈ I, f.is_integer (f.to_map a * b) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R f.codomain // is_fractional f I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P] {f : localization_map S P} instance : has_coe (fractional_ideal f) (submodule R f.codomain) := ⟨λ I, I.val⟩ @[simp] lemma val_eq_coe (I : fractional_ideal f) : I.val = I := rfl instance : has_mem P (fractional_ideal f) := ⟨λ x I, x ∈ (I : submodule R f.codomain)⟩ /-- Fractional ideals are equal if their submodules are equal. Combined with `submodule.ext` this gives that fractional ideals are equal if they have the same elements. -/ @[ext] lemma ext {I J : fractional_ideal f} : (I : submodule R f.codomain) = J → I = J := subtype.ext_iff_val.mpr lemma fractional_of_subset_one (I : submodule R f.codomain) (h : I ≤ (submodule.span R {1})) : is_fractional f I := begin use [1, S.one_mem], intros b hb, rw [f.to_map.map_one, one_mul], rw ←submodule.one_eq_span at h, obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb, rw (show b = f.to_map b', from b'_eq_b.symm), exact set.mem_range_self b', end instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal f) := ⟨ λ I, ⟨f.coe_submodule I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩, submodule.mem_span_singleton.2 ⟨y, by rw ←h; exact mul_one _⟩⟩ ⟩ @[simp] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal f) : submodule R f.codomain) = f.coe_submodule I := rfl @[simp] lemma mem_coe {x : f.codomain} {I : ideal R} : x ∈ (I : fractional_ideal f) ↔ ∃ (x' ∈ I), f.to_map x' = x := ⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩, λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩ instance : has_zero (fractional_ideal f) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal f) ↔ x = 0 := ⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩ @[simp] lemma coe_zero : ↑(0 : fractional_ideal f) = (⊥ : submodule R f.codomain) := submodule.ext $ λ _, mem_zero_iff lemma coe_ne_bot_iff_nonzero {I : fractional_ideal f} : ↑I ≠ (⊥ : submodule R f.codomain) ↔ I ≠ 0 := ⟨ λ h h', h (by simp [h']), λ h h', h (ext (by simp [h'])) ⟩ instance : inhabited (fractional_ideal f) := ⟨0⟩ instance : has_one (fractional_ideal f) := ⟨(1 : ideal R)⟩ lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal f) ↔ ∃ x' : R, f.to_map x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩) lemma coe_mem_one (x : R) : f.to_map x ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨1, f.to_map.map_one⟩ @[simp] lemma coe_one : ↑(1 : fractional_ideal f) = f.coe_submodule 1 := rfl section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ instance : partial_order (fractional_ideal f) := { le := λ I J, I.1 ≤ J.1, le_refl := λ I, le_refl I.1, le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI }, le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK } lemma le_iff {I J : fractional_ideal f} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.refl _ lemma zero_le (I : fractional_ideal f) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal f) := { bot := 0, bot_le := zero_le, ..fractional_ideal.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal f) = 0 := rfl lemma eq_zero_iff {I : fractional_ideal f} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal f) : is_fractional f (I.1 ⊔ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, rcases J.2 with ⟨aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, hbIJ⟩, rw [←hbIJ, mul_add], apply is_integer_add, { rw [mul_comm aI, f.to_map.map_mul, mul_assoc], apply is_integer_smul (hI bI hbI), }, { rw [f.to_map.map_mul, mul_assoc], apply is_integer_smul (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal f) : is_fractional f (I.1 ⊓ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact (hI b hbI) end instance lattice : lattice (fractional_ideal f) := { inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩, sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩, inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left, inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right, le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK, le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left, le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right, sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK, ..fractional_ideal.partial_order } instance : semilattice_sup_bot (fractional_ideal f) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal f) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal f) : I ⊔ J = I + J := rfl @[simp] lemma coe_add (I J : fractional_ideal f) : (↑(I + J) : submodule R f.codomain) = I + J := rfl lemma fractional_mul (I J : fractional_ideal f) : is_fractional f (I.1 * J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨I, aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [f.to_map.map_mul, mul_comm m, ←mul_assoc, mul_assoc _ _ n], erw ←hn', rw mul_assoc, apply hI, exact submodule.smul_mem _ _ hm }, { rw [mul_zero], exact ⟨0, f.to_map.map_zero⟩ }, { intros x y hx hy, rw [mul_add], apply is_integer_add hx hy }, { intros r x hx, show f.is_integer (_ * (f.to_map r * x)), rw [←mul_assoc, ←f.to_map.map_mul, mul_comm _ r, f.to_map.map_mul, mul_assoc], apply is_integer_smul hx }, end instance : has_mul (fractional_ideal f) := ⟨λ I J, ⟨I.1 * J.1, fractional_mul I J⟩⟩ @[simp] lemma coe_mul (I J : fractional_ideal f) : (↑(I * J) : submodule R f.codomain) = I * J := rfl lemma mul_left_mono (I : fractional_ideal f) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal f) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) instance add_comm_monoid : add_comm_monoid (fractional_ideal f) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, ..fractional_ideal.has_zero, ..fractional_ideal.has_add } instance comm_monoid : comm_monoid (fractional_ideal f) := { mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _), mul_comm := λ I J, ext (submodule.mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩, rw [←y'_eq_y, mul_comm], exact submodule.smul_mem _ _ hx }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h one_mem_one, rwa [mul_one] at this } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy, rw ←x'_eq_x, exact submodule.smul_mem _ _ hy }, { have : 1 * x ∈ (1 * I) := mul_mem_mul one_mem_one h, rwa [one_mul] at this } end, ..fractional_ideal.has_mul, ..fractional_ideal.has_one } instance comm_semiring : comm_semiring (fractional_ideal f) := { mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, ext (mul_add _ _ _), right_distrib := λ I J K, ext (add_mul _ _ _), ..fractional_ideal.add_comm_monoid, ..fractional_ideal.comm_monoid } variables {P' : Type*} [comm_ring P'] {f' : localization_map S P'} variables {P'' : Type*} [comm_ring P''] {f'' : localization_map S P''} lemma fractional_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : is_fractional f' (submodule.map g.to_linear_map I.1) := begin rcases I with ⟨I, a, a_nonzero, hI⟩, use [a, a_nonzero], intros b hb, obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'], refl end /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : f.codomain →ₐ[R] f'.codomain) : fractional_ideal f → fractional_ideal f' := λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩ @[simp] lemma coe_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma map_id (I : fractional_ideal f) : I.map (alg_hom.id _ _) = I := ext (submodule.map_id I.1) @[simp] lemma map_comp (g : f.codomain →ₐ[R] f'.codomain) (g' : f'.codomain →ₐ[R] f''.codomain) (I : fractional_ideal f) : I.map (g'.comp g) = (I.map g).map g' := ext (submodule.map_comp g.to_linear_map g'.to_linear_map I.1) @[simp] lemma map_add (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) : (I + J).map g = I.map g + J.map g := ext (submodule.map_sup _ _ _) @[simp] lemma map_mul (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) : (I * J).map g = I.map g * J.map g := ext (submodule.map_mul _ _ _) /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) : fractional_ideal f ≃+* fractional_ideal f' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma map_equiv_apply (g : f.codomain ≃ₐ[R] f'.codomain) (I : fractional_ideal f) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal f) := ring_equiv.ext (λ x, by simp) /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `f.codomain` and in `f'.codomain` -/ noncomputable def canonical_equiv (f f' : localization_map S P) : fractional_ideal f ≃+* fractional_ideal f' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _ _, ..ring_equiv_of_ring_equiv f f' (ring_equiv.refl R) (by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } end semiring section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {K : Type*} [field K] {g : fraction_map R K} instance : nontrivial (fractional_ideal g) := ⟨⟨0, 1, λ h, have this : (1 : K) ∈ (0 : fractional_ideal g) := by rw ←g.to_map.map_one; convert coe_mem_one _, one_ne_zero (mem_zero_iff.mp this) ⟩⟩ lemma fractional_div_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : is_fractional g (I.1 / J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : g.to_map aJ * y = 0 := by rw [←hy', y'_eq_zero, g.to_map.map_zero], obtain aJ_zero | y_zero := mul_eq_zero.mp this, { have : aJ = 0 := g.to_map.injective_iff.1 g.injective _ aJ_zero, have : aJ ≠ 0 := mem_non_zero_divisors_iff_ne_zero.mp haJ, contradiction }, { exact not_mem_zero (mem_zero_iff.mpr y_zero) } }, intros b hb, rw [g.to_map.map_mul, mul_assoc, mul_comm _ b, hy'], exact hI _ (hb _ (submodule.smul_mem _ aJ mem_J)), end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal g) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩ noncomputable instance : has_inv (fractional_ideal g) := ⟨λ I, 1 / I⟩ lemma div_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : (I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ := dif_neg h lemma inv_nonzero {I : fractional_ideal g} (h : I ≠ 0) : I⁻¹ = ⟨(1 : fractional_ideal g) / I, fractional_div_of_nonzero h⟩ := div_nonzero h -- set_option pp.all true lemma coe_inv_of_nonzero {I : fractional_ideal g} (h : I ≠ 0) : (↑(I⁻¹) : submodule R g.codomain) = g.coe_submodule 1 / I := by { rw inv_nonzero h, refl } @[simp] lemma div_one {I : fractional_ideal g} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal g) _ _)], ext, split; intro h, { convert mem_div_iff_forall_mul_mem.mp h 1 (g.to_map.map_one ▸ coe_mem_one 1), simp }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, y_eq_y'⟩, rw [mul_comm], convert submodule.smul_mem _ y' h, rw ←y_eq_y', refl } end lemma ne_zero_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal g) _ _ (by { convert h, simp [hI], }) /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal g) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, rw [div_nonzero hI], apply le_antisymm, { apply submodule.mul_le.mpr _, intros x hx y hy, rw [mul_comm], exact mem_div_iff_forall_mul_mem.mp hy x hx }, rw [←h], apply mul_left_mono I, apply submodule.le_div_iff.mpr _, intros y hy x hx, rw [mul_comm], exact mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal g} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa [←right_inverse_eq I J hJ]⟩ end quotient section principal_ideal_ring variables {K : Type*} [field K] {g : fraction_map R K} open_locale classical open submodule submodule.is_principal lemma span_fractional_iff {s : set f.codomain} : is_fractional f (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → f.is_integer (f.to_map a * b) := ⟨ λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (is_integer_smul ⟨0, f.to_map.map_zero⟩) (λ x y hx hy, by { rw mul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw algebra.mul_smul_comm, exact is_integer_smul hx }) ⟩ ⟩ lemma span_singleton_fractional (x : f.codomain) : is_fractional f (span R {x}) := let ⟨a, ha⟩ := f.exists_integer_multiple x in span_fractional_iff.mpr ⟨ a.1, a.2, λ x hx, (mem_singleton_iff.mp hx).symm ▸ ha⟩ /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ def span_singleton (x : f.codomain) : fractional_ideal f := ⟨span R {x}, span_singleton_fractional x⟩ @[simp] lemma coe_span_singleton (x : f.codomain) : (span_singleton x : submodule R f.codomain) = span R {x} := rfl lemma eq_span_singleton_of_principal (I : fractional_ideal f) [is_principal I.1] : I = span_singleton (generator I.1) := ext (span_singleton_generator I.1).symm lemma is_principal_iff (I : fractional_ideal f) : is_principal I.1 ↔ ∃ x, I = span_singleton x := ⟨ λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton (0 : f.codomain) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm, -singleton_zero] } lemma span_singleton_eq_zero_iff {y : f.codomain} : span_singleton y = 0 ↔ y = 0 := ⟨ λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y), λ h, by simp [h] ⟩ @[simp] lemma span_singleton_one : span_singleton (1 : f.codomain) = 1 := begin ext, refine mem_span_singleton.trans ((exists_congr _).trans mem_one_iff.symm), intro x', refine eq.congr (mul_one _) rfl, end @[simp] lemma span_singleton_mul_span_singleton (x y : f.codomain) : span_singleton x * span_singleton y = span_singleton (x * y) := begin ext, simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul] end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(span R {x} : ideal R) : fractional_ideal f) = span_singleton (f.to_map x) := begin ext y, refine mem_coe.trans (iff.trans _ mem_span_singleton.symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := mem_span_singleton.mp hy', use x', rw [smul_eq_mul, f.to_map.map_mul], refl }, { rintros ⟨y', rfl⟩, exact ⟨y' * x, mem_span_singleton.mpr ⟨y', rfl⟩, f.to_map.map_mul _ _⟩ } end lemma mem_singleton_mul {x y : f.codomain} {I : fractional_ideal f} : y ∈ span_singleton x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply submodule.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := mem_span_singleton.mp hx', use [a • y', I.1.smul_mem a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ }, { rintros r _ ⟨y', hy', rfl⟩, exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul (mem_span_singleton.mpr ⟨1, one_smul _ _⟩) hy' } end lemma mul_generator_self_inv (I : fractional_ideal g) [submodule.is_principal I.1] (h : I ≠ 0) : I * span_singleton (generator I.1)⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw eq_span_singleton_of_principal I }, rw [span_singleton_mul_span_singleton, mul_inv_cancel, span_singleton_one], intro generator_I_eq_zero, apply h, rw [eq_span_singleton_of_principal I, generator_I_eq_zero, span_singleton_zero] end lemma exists_eq_span_singleton_mul (I : fractional_ideal g) : ∃ (a : K) (aI : ideal R), I = span_singleton a * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.2, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero := mt g.to_map_eq_zero_iff.mp nonzero, use (g.to_map a_inv)⁻¹, use (span_singleton (g.to_map a_inv) * I).1.comap g.lin_coe, ext, refine iff.trans _ mem_singleton_mul.symm, split, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, refine ⟨g.to_map x', mem_coe.mpr ⟨x', (mem_singleton_mul.mpr ⟨x, hx, hx'⟩), rfl⟩, _⟩, erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := mem_coe.mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw lin_coe_apply at hx', erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul], exact hy' } end instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] {f : fraction_map R K} (I : fractional_ideal f) : (I : submodule R f.codomain).is_principal := ⟨ begin obtain ⟨a, aI, ha⟩ := exists_eq_span_singleton_mul I, have := a * f.to_map (generator aI), use a * f.to_map (generator aI), suffices : I = span_singleton (a * f.to_map (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end ⟩ end principal_ideal_ring end fractional_ideal end ring
93b9c868e9598b5f16f3bc14f809d50a4d220166
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monoidal/functor_category.lean
0f5bc2d773ff6d48e5b8e07eae09304fe5750a9d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,593
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.braided import category_theory.functor.category import category_theory.functor.const /-! # Monoidal structure on `C ⥤ D` when `D` is monoidal. When `C` is any category, and `D` is a monoidal category, there is a natural "pointwise" monoidal structure on `C ⥤ D`. The initial intended application is tensor product of presheaves. -/ universes v₁ v₂ u₁ u₂ open category_theory open category_theory.monoidal_category namespace category_theory.monoidal variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] namespace functor_category variables (F G F' G' : C ⥤ D) /-- (An auxiliary definition for `functor_category_monoidal`.) Tensor product of functors `C ⥤ D`, when `D` is monoidal. -/ @[simps] def tensor_obj : C ⥤ D := { obj := λ X, F.obj X ⊗ G.obj X, map := λ X Y f, F.map f ⊗ G.map f, map_id' := λ X, by rw [F.map_id, G.map_id, tensor_id], map_comp' := λ X Y Z f g, by rw [F.map_comp, G.map_comp, tensor_comp], } variables {F G F' G'} variables (α : F ⟶ G) (β : F' ⟶ G') /-- (An auxiliary definition for `functor_category_monoidal`.) Tensor product of natural transformations into `D`, when `D` is monoidal. -/ @[simps] def tensor_hom : tensor_obj F F' ⟶ tensor_obj G G' := { app := λ X, α.app X ⊗ β.app X, naturality' := λ X Y f, by { dsimp, rw [←tensor_comp, α.naturality, β.naturality, tensor_comp], } } end functor_category open category_theory.monoidal.functor_category /-- When `C` is any category, and `D` is a monoidal category, the functor category `C ⥤ D` has a natural pointwise monoidal structure, where `(F ⊗ G).obj X = F.obj X ⊗ G.obj X`. -/ instance functor_category_monoidal : monoidal_category (C ⥤ D) := { tensor_obj := λ F G, tensor_obj F G, tensor_hom := λ F G F' G' α β, tensor_hom α β, tensor_id' := λ F G, by { ext, dsimp, rw [tensor_id], }, tensor_comp' := λ F G H F' G' H' α β γ δ, by { ext, dsimp, rw [tensor_comp], }, tensor_unit := (category_theory.functor.const C).obj (𝟙_ D), left_unitor := λ F, nat_iso.of_components (λ X, λ_ (F.obj X)) (λ X Y f, by { dsimp, rw left_unitor_naturality, }), right_unitor := λ F, nat_iso.of_components (λ X, ρ_ (F.obj X)) (λ X Y f, by { dsimp, rw right_unitor_naturality, }), associator := λ F G H, nat_iso.of_components (λ X, α_ (F.obj X) (G.obj X) (H.obj X)) (λ X Y f, by { dsimp, rw associator_naturality, }), left_unitor_naturality' := λ F G α, by { ext X, dsimp, rw left_unitor_naturality, }, right_unitor_naturality' := λ F G α, by { ext X, dsimp, rw right_unitor_naturality, }, associator_naturality' := λ F G H F' G' H' α β γ, by { ext X, dsimp, rw associator_naturality, }, triangle' := λ F G, begin ext X, dsimp, rw triangle, end, pentagon' := λ F G H K, begin ext X, dsimp, rw pentagon, end, } @[simp] lemma tensor_unit_obj {X} : (𝟙_ (C ⥤ D)).obj X = 𝟙_ D := rfl @[simp] lemma tensor_unit_map {X Y} {f : X ⟶ Y} : (𝟙_ (C ⥤ D)).map f = 𝟙 (𝟙_ D) := rfl @[simp] lemma tensor_obj_obj {F G : C ⥤ D} {X} : (F ⊗ G).obj X = F.obj X ⊗ G.obj X := rfl @[simp] lemma tensor_obj_map {F G : C ⥤ D} {X Y} {f : X ⟶ Y} : (F ⊗ G).map f = F.map f ⊗ G.map f := rfl @[simp] lemma tensor_hom_app {F G F' G' : C ⥤ D} {α : F ⟶ G} {β : F' ⟶ G'} {X} : (α ⊗ β).app X = α.app X ⊗ β.app X := rfl @[simp] lemma left_unitor_hom_app {F : C ⥤ D} {X} : ((λ_ F).hom : (𝟙_ _) ⊗ F ⟶ F).app X = (λ_ (F.obj X)).hom := rfl @[simp] lemma left_unitor_inv_app {F : C ⥤ D} {X} : ((λ_ F).inv : F ⟶ (𝟙_ _) ⊗ F).app X = (λ_ (F.obj X)).inv := rfl @[simp] lemma right_unitor_hom_app {F : C ⥤ D} {X} : ((ρ_ F).hom : F ⊗ (𝟙_ _) ⟶ F).app X = (ρ_ (F.obj X)).hom := rfl @[simp] lemma right_unitor_inv_app {F : C ⥤ D} {X} : ((ρ_ F).inv : F ⟶ F ⊗ (𝟙_ _)).app X = (ρ_ (F.obj X)).inv := rfl @[simp] lemma associator_hom_app {F G H : C ⥤ D} {X} : ((α_ F G H).hom : (F ⊗ G) ⊗ H ⟶ F ⊗ (G ⊗ H)).app X = (α_ (F.obj X) (G.obj X) (H.obj X)).hom := rfl @[simp] lemma associator_inv_app {F G H : C ⥤ D} {X} : ((α_ F G H).inv : F ⊗ (G ⊗ H) ⟶ (F ⊗ G) ⊗ H).app X = (α_ (F.obj X) (G.obj X) (H.obj X)).inv := rfl section braided_category open category_theory.braided_category variables [braided_category.{v₂} D] /-- When `C` is any category, and `D` is a braided monoidal category, the natural pointwise monoidal structure on the functor category `C ⥤ D` is also braided. -/ instance functor_category_braided : braided_category (C ⥤ D) := { braiding := λ F G, nat_iso.of_components (λ X, β_ _ _) (by tidy), hexagon_forward' := λ F G H, by { ext X, apply hexagon_forward, }, hexagon_reverse' := λ F G H, by { ext X, apply hexagon_reverse, }, } example : braided_category (C ⥤ D) := category_theory.monoidal.functor_category_braided end braided_category section symmetric_category open category_theory.symmetric_category variables [symmetric_category.{v₂} D] /-- When `C` is any category, and `D` is a symmetric monoidal category, the natural pointwise monoidal structure on the functor category `C ⥤ D` is also symmetric. -/ instance functor_category_symmetric : symmetric_category (C ⥤ D) := { symmetry' := λ F G, by { ext X, apply symmetry, },} end symmetric_category end category_theory.monoidal
0a274d02b17e8068966c16f658d6bb74eaf95af7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/exp_decay.lean
aaf1b899783dd4e54cb42165b9b2dbe9d15eaf69
[ "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,977
lean
/- Copyright (c) 2022 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import measure_theory.integral.interval_integral import measure_theory.integral.integral_eq_improper /-! # Integrals with exponential decay at ∞ > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. As easy special cases of general theorems in the library, we prove the following test for integrability: * `integrable_of_is_O_exp_neg`: If `f` is continuous on `[a,∞)`, for some `a ∈ ℝ`, and there exists `b > 0` such that `f(x) = O(exp(-b x))` as `x → ∞`, then `f` is integrable on `(a, ∞)`. -/ noncomputable theory open real interval_integral measure_theory set filter open_locale topology /-- `exp (-b * x)` is integrable on `(a, ∞)`. -/ lemma exp_neg_integrable_on_Ioi (a : ℝ) {b : ℝ} (h : 0 < b) : integrable_on (λ x : ℝ, exp (-b * x)) (Ioi a) := begin have : tendsto (λ x, -exp (-b * x) / b) at_top (𝓝 (-0/b)), { refine tendsto.div_const (tendsto.neg _) _, exact tendsto_exp_at_bot.comp (tendsto_id.neg_const_mul_at_top (right.neg_neg_iff.2 h)) }, refine integrable_on_Ioi_deriv_of_nonneg' (λ x hx, _) (λ x hx, (exp_pos _).le) this, simpa [h.ne'] using ((has_deriv_at_id x).const_mul b).neg.exp.neg.div_const b, end /-- If `f` is continuous on `[a, ∞)`, and is `O (exp (-b * x))` at `∞` for some `b > 0`, then `f` is integrable on `(a, ∞)`. -/ lemma integrable_of_is_O_exp_neg {f : ℝ → ℝ} {a b : ℝ} (h0 : 0 < b) (h1 : continuous_on f (Ici a)) (h2 : f =O[at_top] (λ x, exp (-b * x))) : integrable_on f (Ioi a) := begin cases h2.is_O_with with c h3, rw [asymptotics.is_O_with_iff, eventually_at_top] at h3, cases h3 with r bdr, let v := max a r, -- show integrable on `(a, v]` from continuity have int_left : integrable_on f (Ioc a v), { rw ←(interval_integrable_iff_integrable_Ioc_of_le (le_max_left a r)), have u : Icc a v ⊆ Ici a := Icc_subset_Ici_self, exact (h1.mono u).interval_integrable_of_Icc (le_max_left a r), }, suffices : integrable_on f (Ioi v), { have t : integrable_on f (Ioc a v ∪ Ioi v) := integrable_on_union.mpr ⟨int_left, this⟩, simpa only [Ioc_union_Ioi_eq_Ioi, le_max_iff, le_refl, true_or] using t }, -- now show integrable on `(v, ∞)` from asymptotic split, { exact (h1.mono $ Ioi_subset_Ici $ le_max_left a r).ae_strongly_measurable measurable_set_Ioi }, have : has_finite_integral (λ x : ℝ, c * exp (-b * x)) (volume.restrict (Ioi v)), { exact (exp_neg_integrable_on_Ioi v h0).has_finite_integral.const_mul c }, apply this.mono, refine (ae_restrict_iff' measurable_set_Ioi).mpr _, refine ae_of_all _ (λ x h1x, _), rw [norm_mul, norm_eq_abs], rw [mem_Ioi] at h1x, specialize bdr x ((le_max_right a r).trans h1x.le), exact bdr.trans (mul_le_mul_of_nonneg_right (le_abs_self c) (norm_nonneg _)) end
ae6e26f8da6a97d7af85f1dc23fdc95290d3a642
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/PreDefinition/Main.lean
cdd67b6ecbee0cfb905a1307a8e1a7cc7e134892
[ "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,282
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.SCC import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural import Lean.Elab.PreDefinition.WF.Main import Lean.Elab.PreDefinition.MkInhabitant namespace Lean.Elab open Meta open Term structure TerminationHints where terminationBy? : Option Syntax := none decreasingBy? : Option Syntax := none deriving Inhabited private def addAndCompilePartial (preDefs : Array PreDefinition) (useSorry := false) : TermElabM Unit := do for preDef in preDefs do trace[Elab.definition] "processing {preDef.declName}" let all := preDefs.toList.map (·.declName) forallTelescope preDef.type fun xs type => do let value ← if useSorry then mkLambdaFVars xs (← mkSorry type (synthetic := true)) else liftM <| mkInhabitantFor preDef.declName xs type addNonRec { preDef with kind := DefKind.«opaque» value } (all := all) addAndCompilePartialRec preDefs private def isNonRecursive (preDef : PreDefinition) : Bool := Option.isNone $ preDef.value.find? fun | Expr.const declName _ => preDef.declName == declName | _ => false private def partitionPreDefs (preDefs : Array PreDefinition) : Array (Array PreDefinition) := let getPreDef := fun declName => (preDefs.find? fun preDef => preDef.declName == declName).get! let vertices := preDefs.toList.map (·.declName) let successorsOf := fun declName => (getPreDef declName).value.foldConsts [] fun declName successors => if preDefs.any fun preDef => preDef.declName == declName then declName :: successors else successors let sccs := SCC.scc vertices successorsOf sccs.toArray.map fun scc => scc.toArray.map getPreDef private def collectMVarsAtPreDef (preDef : PreDefinition) : StateRefT CollectMVars.State MetaM Unit := do collectMVars preDef.value collectMVars preDef.type private def getMVarsAtPreDef (preDef : PreDefinition) : MetaM (Array MVarId) := do let (_, s) ← (collectMVarsAtPreDef preDef).run {} pure s.result private def ensureNoUnassignedMVarsAtPreDef (preDef : PreDefinition) : TermElabM PreDefinition := do let pendingMVarIds ← getMVarsAtPreDef preDef if (← logUnassignedUsingErrorInfos pendingMVarIds) then let preDef := { preDef with value := (← mkSorry preDef.type (synthetic := true)) } if (← getMVarsAtPreDef preDef).isEmpty then return preDef else throwAbortCommand else return preDef /-- Letrec declarations produce terms of the form `(fun .. => ..) d` where `d` is a (partial) application of an auxiliary declaration for a letrec declaration. This method beta-reduces them to make sure they can be eliminated by the well-founded recursion module. -/ private def betaReduceLetRecApps (preDefs : Array PreDefinition) : MetaM (Array PreDefinition) := preDefs.mapM fun preDef => do let value ← transform preDef.value fun e => do if e.isApp && e.getAppFn.isLambda && e.getAppArgs.all fun arg => arg.getAppFn.isConst && preDefs.any fun preDef => preDef.declName == arg.getAppFn.constName! then return .visit e.headBeta else return .continue return { preDef with value } private def addAsAxioms (preDefs : Array PreDefinition) : TermElabM Unit := do for preDef in preDefs do let decl := Declaration.axiomDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, isUnsafe := preDef.modifiers.isUnsafe } addDecl decl withSaveInfoContext do -- save new env addTermInfo' preDef.ref (← mkConstWithLevelParams preDef.declName) (isBinder := true) applyAttributesOf #[preDef] AttributeApplicationTime.afterTypeChecking applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation def addPreDefinitions (preDefs : Array PreDefinition) (hints : TerminationHints) : TermElabM Unit := withLCtx {} {} do for preDef in preDefs do trace[Elab.definition.body] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" let preDefs ← preDefs.mapM ensureNoUnassignedMVarsAtPreDef let preDefs ← betaReduceLetRecApps preDefs let cliques := partitionPreDefs preDefs let mut terminationBy ← liftMacroM <| WF.expandTerminationBy hints.terminationBy? (cliques.map fun ds => ds.map (·.declName)) let mut decreasingBy ← liftMacroM <| WF.expandTerminationHint hints.decreasingBy? (cliques.map fun ds => ds.map (·.declName)) let mut hasErrors := false for preDefs in cliques do trace[Elab.definition.scc] "{preDefs.map (·.declName)}" if preDefs.size == 1 && isNonRecursive preDefs[0]! then let preDef := preDefs[0]! if preDef.modifiers.isNoncomputable then addNonRec preDef else addAndCompileNonRec preDef else if preDefs.any (·.modifiers.isUnsafe) then addAndCompileUnsafe preDefs else if preDefs.any (·.modifiers.isPartial) then for preDef in preDefs do if preDef.modifiers.isPartial && !(← whnfD preDef.type).isForall then withRef preDef.ref <| throwError "invalid use of 'partial', '{preDef.declName}' is not a function{indentExpr preDef.type}" addAndCompilePartial preDefs else try let mut wf? := none let mut decrTactic? := none if let some wf := terminationBy.find? (preDefs.map (·.declName)) then wf? := some wf terminationBy := terminationBy.markAsUsed (preDefs.map (·.declName)) if let some { ref, value := decrTactic } := decreasingBy.find? (preDefs.map (·.declName)) then decrTactic? := some (← withRef ref `(by $(⟨decrTactic⟩))) decreasingBy := decreasingBy.markAsUsed (preDefs.map (·.declName)) if wf?.isSome || decrTactic?.isSome then wfRecursion preDefs wf? decrTactic? else withRef (preDefs[0]!.ref) <| mapError (orelseMergeErrors (structuralRecursion preDefs) (wfRecursion preDefs none none)) (fun msg => let preDefMsgs := preDefs.toList.map (MessageData.ofExpr $ mkConst ·.declName) m!"fail to show termination for{indentD (MessageData.joinSep preDefMsgs Format.line)}\nwith errors\n{msg}") catch ex => hasErrors := true logException ex let s ← saveState try if preDefs.all fun preDef => preDef.kind == DefKind.def || preDefs.all fun preDef => preDef.kind == DefKind.abbrev then -- try to add as partial definition try addAndCompilePartial preDefs (useSorry := true) catch _ => -- Compilation failed try again just as axiom s.restore addAsAxioms preDefs else if preDefs.all fun preDef => preDef.kind == DefKind.theorem then addAsAxioms preDefs catch _ => s.restore unless hasErrors do liftMacroM <| terminationBy.ensureAllUsed liftMacroM <| decreasingBy.ensureAllUsed builtin_initialize registerTraceClass `Elab.definition.body registerTraceClass `Elab.definition.scc end Lean.Elab
63edaad87927ff3ff3e35978e7a5acecbe6c6b2c
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Init/Data/Array/BinSearch.lean
34b940ff8efc10939af3a416912d241fa4bce74d
[ "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
2,928
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.Data.Array.Basic universe u v -- TODO: CLEANUP namespace Array -- TODO: remove the [Inhabited α] parameters as soon as we have the tactic framework for automating proof generation and using Array.fget -- TODO: remove `partial` using well-founded recursion @[specialize] partial def binSearchAux {α : Type u} {β : Type v} [Inhabited α] [Inhabited β] (lt : α → α → Bool) (found : Option α → β) (as : Array α) (k : α) : Nat → Nat → β | lo, hi => if lo <= hi then let m := (lo + hi)/2 let a := as.get! m if lt a k then binSearchAux lt found as k (m+1) hi else if lt k a then if m == 0 then found none else binSearchAux lt found as k lo (m-1) else found (some a) else found none @[inline] def binSearch {α : Type} [Inhabited α] (as : Array α) (k : α) (lt : α → α → Bool) (lo := 0) (hi := as.size - 1) : Option α := if lo < as.size then let hi := if hi < as.size then hi else as.size - 1 binSearchAux lt id as k lo hi else none @[inline] def binSearchContains {α : Type} [Inhabited α] (as : Array α) (k : α) (lt : α → α → Bool) (lo := 0) (hi := as.size - 1) : Bool := if lo < as.size then let hi := if hi < as.size then hi else as.size - 1 binSearchAux lt Option.isSome as k lo hi else false @[specialize] private partial def binInsertAux {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] (lt : α → α → Bool) (merge : α → m α) (add : Unit → m α) (as : Array α) (k : α) : Nat → Nat → m (Array α) | lo, hi => -- as[lo] < k < as[hi] let mid := (lo + hi)/2 let midVal := as.get! mid if lt midVal k then if mid == lo then do let v ← add (); pure <| as.insertAt! (lo+1) v else binInsertAux lt merge add as k mid hi else if lt k midVal then binInsertAux lt merge add as k lo mid else do as.modifyM mid <| fun v => merge v @[specialize] def binInsertM {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] (lt : α → α → Bool) (merge : α → m α) (add : Unit → m α) (as : Array α) (k : α) : m (Array α) := if as.isEmpty then do let v ← add (); pure <| as.push v else if lt k (as.get! 0) then do let v ← add (); pure <| as.insertAt! 0 v else if !lt (as.get! 0) k then as.modifyM 0 <| merge else if lt as.back k then do let v ← add (); pure <| as.push v else if !lt k as.back then as.modifyM (as.size - 1) <| merge else binInsertAux lt merge add as k 0 (as.size - 1) @[inline] def binInsert {α : Type u} [Inhabited α] (lt : α → α → Bool) (as : Array α) (k : α) : Array α := Id.run <| binInsertM lt (fun _ => k) (fun _ => k) as k end Array
566da2872b6e2bc8c5f5351c86939bcde5bc7914
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/topology/algebra/group.lean
a8d6ed3272211c7fce8cbd986d4c1c1380a1655e
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
20,811
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of topological groups. -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph open classical set filter topological_space open_locale classical topological_space filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_group /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (α : Type u) [topological_space α] [add_group α] extends has_continuous_add α : Prop := (continuous_neg : continuous (λa:α, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (α : Type*) [topological_space α] [group α] extends has_continuous_mul α : Prop := (continuous_inv : continuous (λa:α, a⁻¹)) variables [topological_space α] [group α] @[to_additive] lemma continuous_inv [topological_group α] : continuous (λx:α, x⁻¹) := topological_group.continuous_inv @[to_additive, continuity] lemma continuous.inv [topological_group α] [topological_space β] {f : β → α} (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg @[to_additive] lemma continuous_on_inv [topological_group α] {s : set α} : continuous_on (λx:α, x⁻¹) s := continuous_inv.continuous_on @[to_additive] lemma continuous_on.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma tendsto_inv {α : Type*} [group α] [topological_space α] [topological_group α] (a : α) : tendsto (λ x, x⁻¹) (nhds a) (nhds (a⁻¹)) := continuous_inv.tendsto a /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv [topological_group α] {f : β → α} {x : filter β} {a : α} (hf : tendsto f x (𝓝 a)) : tendsto (λx, (f x)⁻¹) x (𝓝 a⁻¹) := tendsto.comp (continuous_iff_continuous_at.mp topological_group.continuous_inv a) hf @[to_additive] lemma continuous_at.inv [topological_group α] [topological_space β] {f : β → α} {x : β} (hf : continuous_at f x) : continuous_at (λx, (f x)⁻¹) x := hf.inv @[to_additive] lemma continuous_within_at.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} {x : β} (hf : continuous_within_at f s x) : continuous_within_at (λx, (f x)⁻¹) s x := hf.inv @[to_additive] instance [topological_group α] [topological_space β] [group β] [topological_group β] : topological_group (α × β) := { continuous_inv := continuous_fst.inv.prod_mk continuous_snd.inv } attribute [instance] prod.topological_add_group /-- Multiplication from the left in a topological group as a homeomorphism.-/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left [topological_group α] (a : α) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map /-- Multiplication from the right in a topological group as a homeomorphism.-/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right {α : Type*} [topological_space α] [group α] [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right [topological_group α] (a : α) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map /-- Inversion in a topological group as a homeomorphism.-/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] : α ≃ₜ α := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv α } @[to_additive exists_nhds_half] lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w ∈ s := begin have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : α × α) := tendsto_mul (by simpa using hs), rw nhds_prod_eq at this, rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ (v ∈ V) (w ∈ V), v * w⁻¹ ∈ s := begin have : tendsto (λa:α×α, a.1 * (a.2)⁻¹) (𝓝 (1:α) ×ᶠ 𝓝 (1:α)) (𝓝 1), { simpa using (@tendsto_fst α α (𝓝 1) (𝓝 1)).mul tendsto_snd.inv }, have : ((λa:α×α, a.1 * (a.2)⁻¹) ⁻¹' s) ∈ 𝓝 (1:α) ×ᶠ 𝓝 (1:α) := this (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end @[to_additive exists_nhds_quarter] lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩, rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩, existsi [V, V_nhd], intros v w s t v_in w_in s_in t_in, simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in) end section variable (α) @[to_additive] lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (𝓝 (1 : α)) = 𝓝 (1 : α) := begin have lim : tendsto (λr:α, r⁻¹) (𝓝 1) (𝓝 1), { simpa using (@tendsto_id α (𝓝 1)).inv }, refine comap_eq_of_inverse _ _ lim lim, { funext x, simp }, end end @[to_additive] lemma nhds_translation_mul_inv [topological_group α] (x : α) : comap (λy:α, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λy:α, y * x) _ _ _, { funext x; simp }, { suffices : tendsto (λy:α, y * x⁻¹) (𝓝 x) (𝓝 (x * x⁻¹)), { simpa }, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λy:α, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space α] [group α] [topological_group α] (N : subgroup α) (n : N.normal) @[to_additive] instance {α : Type u} [group α] [topological_space α] (N : subgroup α) : topological_space (quotient_group.quotient N) := by dunfold quotient_group.quotient; apply_instance open quotient_group @[to_additive] lemma quotient_group_saturate {α : Type u} [group α] (N : subgroup α) (s : set α) : (coe : α → quotient N) ⁻¹' ((coe : α → quotient N) '' s) = (⋃ x : N, (λ y, y*x.1) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, quotient_group.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, h⟩, a, a_in, mul_inv_cancel_left _ _⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by { simp only [eq.symm, (mul_assoc _ _ _).symm, inv_mul_cancel_left], exact hi }⟩ } end @[to_additive] lemma quotient_group.open_coe : is_open_map (coe : α → quotient N) := begin intros s s_op, change is_open ((coe : α → quotient N) ⁻¹' (coe '' s)), rw quotient_group_saturate N s, apply is_open_Union, rintro ⟨n, _⟩, exact is_open_map_mul_right n s s_op end @[to_additive] instance topological_group_quotient (n : N.normal) : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : α → quotient N) ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : α × α, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact is_open_map.prod (quotient_group.open_coe N) (quotient_group.open_coe N) }, { exact (continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd) }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin apply continuous_quotient_lift, change continuous ((coe : α → quotient N) ∘ (λ (a : α), a⁻¹)), exact continuous_quot_mk.comp continuous_inv end } attribute [instance] topological_add_group_quotient end quotient_topological_group section topological_add_group variables [topological_space α] [add_group α] @[continuity] lemma continuous.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma continuous_sub [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) := continuous_fst.sub continuous_snd lemma continuous_on.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} {s : set β} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := continuous_sub.comp_continuous_on (hf.prod hg) lemma filter.tendsto.sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x - g x) x (𝓝 (a - b)) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (𝓝 0) = 𝓝 x := nhds_translation_add_neg x end topological_add_group /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (α : Type u) extends add_comm_group α := (Z [] : filter α) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:α×α, p.1 - p.2) (Z ×ᶠ Z) Z) namespace add_group_with_zero_nhd variables (α) [add_group_with_zero_nhd α] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space α := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α) variables {α} lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) := have tendsto (λa, (0:α)) (Z α) (Z α), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:α, 0 - a) (Z α) (Z α), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:α×α, p.1 + p.2) (Z α ×ᶠ Z α) (Z α) := suffices tendsto (λp:α×α, p.1 - -p.2) (Z α ×ᶠ Z α) (Z α), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set α} (hs : s ∈ Z α) : ∃ V ∈ Z α, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ Z α ×ᶠ Z α := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : α) : 𝓝 a = map (λx, x + a) (Z α) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:α) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z α).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z α := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add α := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (Z α ×ᶠ Z α) (map (λx:α, (a + b) + x) (Z α)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group α := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space α] [group α] [topological_group α] @[to_additive] lemma is_open_mul_left {s t : set α} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : α), a * x) '' t), assume a, apply is_open_map_mul_left, exact ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open_mul_right {s t : set α} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : α), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (α) lemma topological_group.t1_space (h : @is_closed α _ {1}) : t1_space α := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space α] : regular_space α := ⟨assume s a hs ha, let f := λ p : α × α, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_mul.comp (continuous_fst.prod_mk (continuous_inv.comp continuous_snd)), -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:α) (by simpa [f]) in begin use s * t₂, use is_open_mul_left ht₂, use λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩, apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space α] : t2_space α := regular_space.t2_space α end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space α] [group α] [topological_group α] /-- Given a open neighborhood `U` of `1` there is a open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma one_open_separated_mul {U : set α} (h1U : is_open U) (h2U : (1 : α) ∈ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ V * V ⊆ U := begin rcases exists_nhds_square (continuous_mul U h1U) (by simp only [mem_preimage, one_mul, h2U] : ((1 : α), (1 : α)) ∈ (λ p : α × α, p.1 * p.2) ⁻¹' U) with ⟨V, h1V, h2V, h3V⟩, refine ⟨V, h1V, h2V, _⟩, rwa [← image_subset_iff, image_mul_prod] at h3V end /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ K * V ⊆ U := begin let W : α → set α := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, continuous_mul_left x U hU, have h2W : ∀ x ∈ K, (1 : α) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, one_open_separated_mul (h1W x) (h2W x.1 x.2), let X : K → set α := λ x, (λ y, (x : α)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, continuous_mul_left x⁻¹ (V x) (hV x).1) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : α)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set α} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset α, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : α, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end end section variables [topological_space α] [comm_group α] [topological_group α] @[to_additive] lemma nhds_mul (x y : α) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_split ht with ⟨V, V_mem, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, ⟨V, V_mem, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) (w * y⁻¹) v_mem w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:α, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul
66aff896583c611ef86a4ff093f564e5f0bf21b8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/list/join.lean
eaeca717c82259c934da042af43efa7f8c199aa7
[ "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
7,459
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Floris van Doorn, Mario Carneiro, Martin Dvorak -/ import data.list.big_operators.basic /-! # Join of a list of lists > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves basic properties of `list.join`, which concatenates a list of lists. It is defined in [`data.list.defs`](./defs). -/ variables {α β : Type*} namespace list attribute [simp] join @[simp] lemma join_singleton (l : list α) : [l].join = l := by rw [join, join, append_nil] @[simp] lemma join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l :: L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] lemma join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_concat (L : list (list α)) (l : list α) : join (L.concat l) = join L ++ l := by simp @[simp] lemma join_filter_empty_eq_ff [decidable_pred (λ l : list α, l.empty = ff)] : ∀ {L : list (list α)}, join (L.filter (λ l, l.empty = ff)) = L.join | [] := rfl | ([] :: L) := by simp [@join_filter_empty_eq_ff L] | ((a :: l) :: L) := by simp [@join_filter_empty_eq_ff L] @[simp] lemma join_filter_ne_nil [decidable_pred (λ l : list α, l ≠ [])] {L : list (list α)} : join (L.filter (λ l, l ≠ [])) = L.join := by simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } @[simp] lemma length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] lemma length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] @[simp] lemma bind_eq_nil {l : list α} {f : α → list β} : list.bind l f = [] ↔ ∀ x ∈ l, f x = [] := join_eq_nil.trans $ by simp only [mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end lemma join_drop_length_sub_one {L : list (list α)} (h : L ≠ []) : (L.drop (L.length - 1)).join = L.last h := begin induction L using list.reverse_rec_on, { cases h rfl }, { simp }, end /-- We can rebracket `x ++ (l₁ ++ x) ++ (l₂ ++ x) ++ ... ++ (lₙ ++ x)` to `(x ++ l₁) ++ (x ++ l₂) ++ ... ++ (x ++ lₙ) ++ x` where `L = [l₁, l₂, ..., lₙ]`. -/ lemma append_join_map_append (L : list (list α)) (x : list α) : x ++ (list.map (λ l, l ++ x) L).join = (list.map (λ l, x ++ l) L).join ++ x := begin induction L, { rw [map_nil, join, append_nil, map_nil, join, nil_append] }, { rw [map_cons, join, map_cons, join, append_assoc, L_ih, append_assoc, append_assoc] }, end /-- Reversing a join is the same as reversing the order of parts and reversing all parts. -/ lemma reverse_join (L : list (list α)) : L.join.reverse = (list.map list.reverse L).reverse.join := begin induction L, { refl }, { rw [join, reverse_append, L_ih, map_cons, reverse_cons', join_concat] }, end /-- Joining a reverse is the same as reversing all parts and reversing the joined result. -/ lemma join_reverse (L : list (list α)) : L.reverse.join = (list.map list.reverse L).join.reverse := by simpa [reverse_reverse] using congr_arg list.reverse (reverse_join L.reverse) end list
ae013a043908a38933d662e799ce7847e8f5a852
5a8eb1c11f93715e070b588e85f2961065c3714d
/books/theorem-proving-in-lean/ch02-08-2.lean
59af9b54e8c9342ee0be2a4e88534bf543853ef2
[ "MIT" ]
permissive
luksamuk/study
0e19bf99d33e0793127c3d3f8ad3936fbeb36505
6a9417e071a8624c4cd9db696c16a3abcc430219
refs/heads/master
1,677,960,533,266
1,676,234,529,000
1,676,234,529,000
151,009,060
4
1
MIT
1,676,234,531,000
1,538,343,224,000
C++
UTF-8
Lean
false
false
253
lean
section sigma_types variable α : Type variable β : α → Type variable a : α variable b : β a #check sigma.mk a b #check (sigma.mk a b).1 #check (sigma.mk a b).2 #reduce (sigma.mk a b).1 #reduce (sigma.mk a b).2 end sigma_types
229ae0e83caa7535e29f7523cd0872e99113e96e
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/topology/algebra/ordered.lean
cb94b0cad78def29eaf13f17707697c7ad6527f1
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
124,991
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import tactic.tfae import order.liminf_limsup import data.set.intervals.image_preimage import data.set.intervals.ord_connected import data.set.intervals.surj_on import topology.algebra.group import topology.extend_from_subset import order.filter.interval /-! # Theory of topology on ordered spaces ## Main definitions The order topology on an ordered space is the topology generated by all open intervals (or equivalently by those of the form `(-∞, a)` and `(b, +∞)`). We define it as `preorder.topology α`. However, we do *not* register it as an instance (as many existing ordered types already have topologies, which would be equal but not definitionally equal to `preorder.topology α`). Instead, we introduce a class `order_topology α`(which is a `Prop`, also known as a mixin) saying that on the type `α` having already a topological space structure and a preorder structure, the topological structure is equal to the order topology. We also introduce another (mixin) class `order_closed_topology α` saying that the set of points `(x, y)` with `x ≤ y` is closed in the product space. This is automatically satisfied on a linear order with the order topology. We prove many basic properties of such topologies. ## Main statements This file contains the proofs of the following facts. For exact requirements (`order_closed_topology` vs `order_topology`, `preorder` vs `partial_order` vs `linear_order` etc) see their statements. ### Open / closed sets * `is_open_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open; * `is_open_Iio`, `is_open_Ioi`, `is_open_Ioo` : open intervals are open; * `is_closed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed; * `is_closed_Iic`, `is_closed_Ici`, `is_closed_Icc` : closed intervals are closed; * `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}` and `{x | f x < g x}` are included by `{x | f x = g x}`; * `exists_Ioc_subset_of_mem_nhds`, `exists_Ico_subset_of_mem_nhds` : if `x < y`, then any neighborhood of `x` includes an interval `[x, z)` for some `z ∈ (x, y]`, and any neighborhood of `y` includes an interval `(z, y]` for some `z ∈ [x, y)`. ### Convergence and inequalities * `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually `f x ≤ g x`, then `a ≤ b` * `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b` (resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a); we also provide primed versions that assume the inequalities to hold for all `x`. ### Min, max, `Sup` and `Inf` * `continuous.min`, `continuous.max`: pointwise `min`/`max` of two continuous functions is continuous. * `tendsto.min`, `tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise `min`/`max` tend to `min a b` and `max a b`, respectively. * `tendsto_of_tendsto_of_tendsto_of_le_of_le` : theorem known as squeeze theorem, sandwich theorem, theorem of Carabinieri, and two policemen (and a drunk) theorem; if `g` and `h` both converge to `a`, and eventually `g x ≤ f x ≤ h x`, then `f` converges to `a`. ### Connected sets and Intermediate Value Theorem * `is_preconnected_I??` : all intervals `I??` are preconnected, * `is_preconnected.intermediate_value`, `intermediate_value_univ` : Intermediate Value Theorem for connected sets and connected spaces, respectively; * `intermediate_value_Icc`, `intermediate_value_Icc'`: Intermediate Value Theorem for functions on closed intervals. ### Miscellaneous facts * `is_compact.exists_forall_le`, `is_compact.exists_forall_ge` : extreme value theorem, a continuous function on a compact set takes its minimum and maximum values. * `is_closed.Icc_subset_of_forall_mem_nhds_within` : “Continuous induction” principle; if `s ∩ [a, b]` is closed, `a ∈ s`, and for each `x ∈ [a, b) ∩ s` some of its right neighborhoods is included `s`, then `[a, b] ⊆ s`. * `is_closed.Icc_subset_of_forall_exists_gt`, `is_closed.mem_of_ge_of_forall_exists_gt` : two other versions of the “continuous induction” principle. ## Implementation We do _not_ register the order topology as an instance on a preorder (or even on a linear order). Indeed, on many such spaces, a topology has already been constructed in a different way (think of the discrete spaces `ℕ` or `ℤ`, or `ℝ` that could inherit a topology as the completion of `ℚ`), and is in general not defeq to the one generated by the intervals. We make it available as a definition `preorder.topology α` though, that can be registered as an instance when necessary, or for specific types. -/ open classical set filter topological_space open function (curry uncurry) open_locale topological_space classical filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin. This property is satisfied for the order topology on a linear order, but it can be satisfied more generally, and suffices to derive many interesting properties relating order and topology. -/ class order_closed_topology (α : Type*) [topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed {p:α×α | p.1 ≤ p.2}) instance : Π [topological_space α], topological_space (order_dual α) := id section order_closed_topology section preorder variables [topological_space α] [preorder α] [t : order_closed_topology α] include t lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le' lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_Iic {a : α} : is_closed (Iic a) := is_closed_le' a lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id lemma is_closed_Ici {a : α} : is_closed (Ici a) := is_closed_ge' a instance : order_closed_topology (order_dual α) := ⟨continuous_swap _ (@order_closed_topology.is_closed_le' α _ _ _)⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter is_closed_Ici is_closed_Iic @[simp] lemma closure_Icc (a b : α) : closure (Icc a b) = Icc a b := is_closed_Icc.closure_eq @[simp] lemma closure_Iic (a : α) : closure (Iic a) = Iic a := is_closed_Iic.closure_eq @[simp] lemma closure_Ici (a : α) : closure (Ici a) = Ici a := is_closed_Ici.closure_eq lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : f ≤ᶠ[b] g) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from t.is_closed_le'.mem_of_tendsto this h lemma le_of_tendsto_of_tendsto' {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ x, f x ≤ g x) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto hf hg (eventually_of_forall h) lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b := le_of_tendsto_of_tendsto lim tendsto_const_nhds h lemma le_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b := le_of_tendsto lim (eventually_of_forall h) lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a := le_of_tendsto_of_tendsto tendsto_const_nhds lim h lemma ge_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a := ge_of_tendsto lim (eventually_of_forall h) @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := (is_closed_le hf hg).closure_eq lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b < g b} ⊆ {b | f b ≤ g b} := by { rw [←closure_le_eq hf hg], exact closure_mono (λ b, le_of_lt) } lemma continuous_within_at.closure_le [topological_space β] {f g : β → α} {s : set β} {x : β} (hx : x ∈ closure s) (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) (h : ∀ y ∈ s, f y ≤ g y) : f x ≤ g x := show (f x, g x) ∈ {p : α × α | p.1 ≤ p.2}, from order_closed_topology.is_closed_le'.closure_subset ((hf.prod hg).mem_closure hx h) /-- If `s` is a closed set and two functions `f` and `g` are continuous on `s`, then the set `{x ∈ s | f x ≤ g x}` is a closed set. -/ lemma is_closed.is_closed_le [topological_space β] {f g : β → α} {s : set β} (hs : is_closed s) (hf : continuous_on f s) (hg : continuous_on g s) : is_closed {x ∈ s | f x ≤ g x} := (hf.prod hg).preimage_closed_of_closed hs order_closed_topology.is_closed_le' omit t lemma nhds_within_Ici_ne_bot {a b : α} (H₂ : a ≤ b) : 𝓝[Ici a] b ≠ ⊥ := nhds_within_ne_bot_of_mem H₂ lemma nhds_within_Ici_self_ne_bot (a : α) : 𝓝[Ici a] a ≠ ⊥ := nhds_within_Ici_ne_bot (le_refl a) lemma nhds_within_Iic_ne_bot {a b : α} (H : a ≤ b) : 𝓝[Iic b] a ≠ ⊥ := nhds_within_ne_bot_of_mem H lemma nhds_within_Iic_self_ne_bot (a : α) : 𝓝[Iic a] a ≠ ⊥ := nhds_within_Iic_ne_bot (le_refl a) end preorder section partial_order variables [topological_space α] [partial_order α] [t : order_closed_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp only [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) @[priority 90] -- see Note [lower instance priority] instance order_closed_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [order_closed_topology α] lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf variables {a b : α} lemma is_open_Iio : is_open (Iio a) := is_open_lt continuous_id continuous_const lemma is_open_Ioi : is_open (Ioi a) := is_open_lt continuous_const continuous_id lemma is_open_Ioo : is_open (Ioo a b) := is_open_inter is_open_Ioi is_open_Iio @[simp] lemma interior_Ioi : interior (Ioi a) = Ioi a := is_open_Ioi.interior_eq @[simp] lemma interior_Iio : interior (Iio a) = Iio a := is_open_Iio.interior_eq @[simp] lemma interior_Ioo : interior (Ioo a b) = Ioo a b := is_open_Ioo.interior_eq /-- Intermediate value theorem for two functions: if `f` and `g` are two continuous functions on a preconnected space and `f a ≤ g a` and `g b ≤ f b`, then for some `x` we have `f x = g x`. -/ lemma intermediate_value_univ₂ {γ : Type*} [topological_space γ] [preconnected_space γ] {a b : γ} {f g : γ → α} (hf : continuous f) (hg : continuous g) (ha : f a ≤ g a) (hb : g b ≤ f b) : ∃ x, f x = g x := begin obtain ⟨x, h, hfg, hgf⟩ : (univ ∩ {x | f x ≤ g x ∧ g x ≤ f x}).nonempty, from is_preconnected_closed_iff.1 preconnected_space.is_preconnected_univ _ _ (is_closed_le hf hg) (is_closed_le hg hf) (λ x hx, le_total _ _) ⟨a, trivial, ha⟩ ⟨b, trivial, hb⟩, exact ⟨x, le_antisymm hfg hgf⟩ end /-- Intermediate value theorem for two functions: if `f` and `g` are two functions continuous on a preconnected set `s` and for some `a b ∈ s` we have `f a ≤ g a` and `g b ≤ f b`, then for some `x ∈ s` we have `f x = g x`. -/ lemma is_preconnected.intermediate_value₂ {γ : Type*} [topological_space γ] {s : set γ} (hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f g : γ → α} (hf : continuous_on f s) (hg : continuous_on g s) (ha' : f a ≤ g a) (hb' : g b ≤ f b) : ∃ x ∈ s, f x = g x := let ⟨x, hx⟩ := @intermediate_value_univ₂ α _ _ _ s _ (subtype.preconnected_space hs) ⟨a, ha⟩ ⟨b, hb⟩ _ _ (continuous_on_iff_continuous_restrict.1 hf) (continuous_on_iff_continuous_restrict.1 hg) ha' hb' in ⟨x, x.2, hx⟩ /-- Intermediate Value Theorem for continuous functions on connected sets. -/ lemma is_preconnected.intermediate_value {γ : Type*} [topological_space γ] {s : set γ} (hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f : γ → α} (hf : continuous_on f s) : Icc (f a) (f b) ⊆ f '' s := λ x hx, mem_image_iff_bex.2 $ hs.intermediate_value₂ ha hb hf continuous_on_const hx.1 hx.2 /-- Intermediate Value Theorem for continuous functions on connected spaces. -/ lemma intermediate_value_univ {γ : Type*} [topological_space γ] [preconnected_space γ] (a b : γ) {f : γ → α} (hf : continuous f) : Icc (f a) (f b) ⊆ range f := λ x hx, intermediate_value_univ₂ hf continuous_const hx.1 hx.2 /-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/ lemma is_preconnected.Icc_subset {s : set α} (hs : is_preconnected s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : Icc a b ⊆ s := by simpa only [image_id] using hs.intermediate_value ha hb continuous_on_id /-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/ lemma is_connected.Icc_subset {s : set α} (hs : is_connected s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : Icc a b ⊆ s := hs.2.Icc_subset ha hb /-- If preconnected set in a linear order space is unbounded below and above, then it is the whole space. -/ lemma is_preconnected.eq_univ_of_unbounded {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s) (ha : ¬bdd_above s) : s = univ := begin refine eq_univ_of_forall (λ x, _), obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := not_bdd_below_iff.1 hb x, obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x, exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ end /-! ### Neighborhoods to the left and to the right on an `order_closed_topology` Limits to the left and to the right of real functions are defined in terms of neighborhoods to the left and to the right, either open or closed, i.e., members of `𝓝[Ioi a] a` and `𝓝[Ici a] a` on the right, and similarly on the left. Here we simply prove that all right-neighborhoods of a point are equal, and we'll prove later other useful characterizations which require the stronger hypothesis `order_topology α` -/ /-! #### Right neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioo a c ∈ 𝓝[Ioi b] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by rw [inter_comm, Ioi_inter_Iio]; exact Ioo_subset_Ioo_left H.1⟩ lemma Ioc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioc a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ico_self lemma Icc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ioc_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioc a b] a = 𝓝[Ioi a] a := le_antisymm (nhds_within_mono _ Ioc_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioc_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ioo_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioo a b] a = 𝓝[Ioi a] a := le_antisymm (nhds_within_mono _ Ioo_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioo_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Ioc_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Ioi h] @[simp] lemma continuous_within_at_Ioo_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioo a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Ioi h] /-! #### Left neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioo a c ∈ 𝓝[Iio b] b := by simpa only [dual_Ioo] using @Ioo_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩ lemma Ico_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ico a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ioc_self lemma Icc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ico_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ico a b] b = 𝓝[Iio b] b := by simpa only [dual_Ioc] using @nhds_within_Ioc_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h @[simp] lemma nhds_within_Ioo_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ioo a b] b = 𝓝[Iio b] b := by simpa only [dual_Ioo] using @nhds_within_Ioo_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h @[simp] lemma continuous_within_at_Ico_iff_Iio [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ico a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Iio h] @[simp] lemma continuous_within_at_Ioo_iff_Iio [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioo a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Iio h] /-! #### Right neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[Ici b] b := mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H lemma Ioc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioc a c ∈ 𝓝[Ici b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ici H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[Ici b] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by simp only [inter_comm, Ici_inter_Iio, Ico_subset_Ico_left H.1]⟩ lemma Icc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[Ici b] b := mem_sets_of_superset (Ico_mem_nhds_within_Ici H) Ico_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Icc a b] a = 𝓝[Ici a] a := le_antisymm (nhds_within_mono _ Icc_subset_Ici_self) $ nhds_within_le_of_mem $ Icc_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ico_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Ico a b] a = 𝓝[Ici a] a := le_antisymm (nhds_within_mono _ (λ x, and.left)) $ nhds_within_le_of_mem $ Ico_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Icc_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Ici h] @[simp] lemma continuous_within_at_Ico_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ico a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Ici h] /-! #### Left neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[Iic b] b := mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H lemma Ico_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ico a c ∈ 𝓝[Iic b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iic H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[Iic b] b := by simpa only [dual_Ico] using @Ico_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩ lemma Icc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[Iic b] b := mem_sets_of_superset (Ioc_mem_nhds_within_Iic H) Ioc_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Icc a b] b = 𝓝[Iic b] b := by simpa only [dual_Icc] using @nhds_within_Icc_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h @[simp] lemma nhds_within_Ioc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Ioc a b] b = 𝓝[Iic b] b := by simpa only [dual_Ico] using @nhds_within_Ico_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h @[simp] lemma continuous_within_at_Icc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Iic h] @[simp] lemma continuous_within_at_Ioc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Iic h] end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [order_closed_topology α] {f g : β → α} section variables [topological_space β] (hf : continuous f) (hg : continuous g) include hf hg lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := begin rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg], rintros b ⟨hb₁, hb₂⟩, refine le_antisymm hb₁ (closure_lt_subset_le hg hf _), convert hb₂ using 2, simp only [not_le.symm], refl end lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] @[continuity] lemma continuous.min : continuous (λb, min (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb, continuous_if this hf hg @[continuity] lemma continuous.max : continuous (λb, max (f b) (g b)) := @continuous.min (order_dual α) _ _ _ _ _ _ _ hf hg end lemma tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (max a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_fst.max continuous_snd) _ end (hf.prod_mk hg) lemma tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (min a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_fst.min continuous_snd) _ end (hf.prod_mk hg) end decidable_linear_order end order_closed_topology /-- The order topology on an ordered type is the topology generated by open intervals. We register it on a preorder, but it is mostly interesting in linear orders, where it is also order-closed. We define it as a mixin. If you want to introduce the order topology on a preorder, use `preorder.topology`. -/ class order_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a}) /-- (Order) topology on a partial order `α` generated by the subbase of open intervals `(a, ∞) = { x ∣ a < x }, (-∞ , b) = {x ∣ x < b}` for all `a, b` in `α`. We do not register it as an instance as many ordered sets are already endowed with the same topology, most often in a non-defeq way though. Register as a local instance when necessary. -/ def preorder.topology (α : Type*) [preorder α] : topological_space α := generate_from {s : set α | ∃ (a : α), s = {b : α | a < b} ∨ s = {b : α | b < a}} section order_topology instance {α : Type*} [topological_space α] [partial_order α] [order_topology α] : order_topology (order_dual α) := ⟨by convert @order_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : order_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a < x := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a ≤ x := (𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x < b := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b := (𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_order (a : α) : 𝓝 a = (⨅b ∈ Iio a, 𝓟 (Ioi b)) ⊓ (⨅b ∈ Ioi a, 𝓟 (Iio b)) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_order {f : β → α} {a : α} {x : filter β} : tendsto f x (𝓝 a) ↔ (∀ a' < a, ∀ᶠ b in x, a' < f b) ∧ (∀ a' > a, ∀ᶠ b in x, f b < a') := by simp [nhds_eq_order a, tendsto_inf, tendsto_infi, tendsto_principal] instance tendsto_Icc_class_nhds (a : α) : tendsto_Ixx_class Icc (𝓝 a) (𝓝 a) := begin simp only [nhds_eq_order, infi_subtype'], refine ((has_basis_infi_principal_finite _).inf (has_basis_infi_principal_finite _)).tendsto_Ixx_class (λ s hs, _), refine (ord_connected_bInter _).inter (ord_connected_bInter _); intros _ _, exacts [ord_connected_Ioi, ord_connected_Iio] end instance tendsto_Ico_class_nhds (a : α) : tendsto_Ixx_class Ico (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ioc_class_nhds (a : α) : tendsto_Ixx_class Ioc (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_class_nhds (a : α) : tendsto_Ixx_class Ioo (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self) instance tendsto_Ixx_nhds_within (a : α) {s t : set α} {Ixx} [tendsto_Ixx_class Ixx (𝓝 a) (𝓝 a)] [tendsto_Ixx_class Ixx (𝓟 s) (𝓟 t)]: tendsto_Ixx_class Ixx (𝓝[s] a) (𝓝[t] a) := filter.tendsto_Ixx_class_inf /-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold eventually for the filter. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le' {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : ∀ᶠ b in b, g b ≤ f b) (hfh : ∀ᶠ b in b, f b ≤ h b) : tendsto f b (𝓝 a) := tendsto_order.2 ⟨assume a' h', have ∀ᶠ b in b, a' < g b, from (tendsto_order.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have ∀ᶠ b in b, h b < a', from (tendsto_order.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ /-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold everywhere. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : g ≤ f) (hfh : f ≤ h) : tendsto f b (𝓝 a) := tendsto_of_tendsto_of_tendsto_of_le_of_le' hg hh (eventually_of_forall hgf) (eventually_of_forall hfh) lemma nhds_order_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : 𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), 𝓟 (Ioo l u)) := calc 𝓝 a = (⨅b<a, 𝓟 {c | b < c}) ⊓ (⨅b>a, 𝓟 {c | c < b}) : nhds_eq_order a ... = (⨅b<a, 𝓟 {c | b < c} ⊓ (⨅b>a, 𝓟 {c | c < b})) : binfi_inf hl ... = (⨅l<a, (⨅u>a, 𝓟 {c | c < u} ⊓ 𝓟 {c | l < c})) : begin congr, funext x, congr, funext hx, rw [inf_comm], apply binfi_inf hu end ... = _ : by simp [inter_comm]; refl lemma tendsto_order_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → ∀ᶠ b in x, l < f b ∧ f b < u) : tendsto f x (𝓝 a) := by rw [nhds_order_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order theorem induced_order_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @order_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_order (f a)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } }, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, end theorem induced_order_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @order_topology _ (induced f ta) _ := induced_order_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) /-- On an `ord_connected` subset of a linear order, the order topology for the restriction of the order is the same as the restriction to the subset of the order topology. -/ instance order_topology_of_ord_connected {α : Type u} [ta : topological_space α] [decidable_linear_order α] [order_topology α] {t : set α} [ht : ord_connected t] : order_topology t := begin letI := induced (coe : t → α) ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_order (a : α)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { refine ⟨Ioi b, _, λ _, id⟩, refine mem_inf_sets_of_left (mem_infi_sets b _), exact mem_infi_sets ab (mem_principal_self (Ioi ↑b)) }, { refine ⟨Iio b, _, λ _, id⟩, refine mem_inf_sets_of_right (mem_infi_sets b _), exact mem_infi_sets ab (mem_principal_self (Iio b)) } }, { rw [← map_le_iff_le_comap], refine le_inf _ _, { refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _), by_cases hx : x ∈ t, { refine mem_infi_sets (Ioi ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inl rfl⟩⟩ _), exact λ _, id }, simp only [set_coe.exists, mem_set_of_eq, mem_map], convert univ_sets _, suffices hx' : ∀ (y : t), ↑y ∈ Ioi x, { simp [hx'] }, intros y, revert hx, contrapose!, -- here we use the `ord_connected` hypothesis exact λ hx, ht y.2 a.2 ⟨le_of_not_gt hx, le_of_lt h⟩ }, { refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _), by_cases hx : x ∈ t, { refine mem_infi_sets (Iio ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inr rfl⟩⟩ _), exact λ _, id }, simp only [set_coe.exists, mem_set_of_eq, mem_map], convert univ_sets _, suffices hx' : ∀ (y : t), ↑y ∈ Iio x, { simp [hx'] }, intros y, revert hx, contrapose!, -- here we use the `ord_connected` hypothesis exact λ hx, ht a.2 y.2 ⟨le_of_lt h, le_of_not_gt hx⟩ } } end lemma nhds_top_order [topological_space α] [order_top α] [order_topology α] : 𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), 𝓟 (Ioi l)) := by simp [nhds_eq_order (⊤:α)] lemma nhds_bot_order [topological_space α] [order_bot α] [order_topology α] : 𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), 𝓟 (Iio l)) := by simp [nhds_eq_order (⊥:α)] section linear_order variables [topological_space α] [linear_order α] [order_topology α] lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) : ∃ l' ∈ Ico l a, Ioc l' a ⊆ s := begin rw [nhds_eq_order a] at hs, rcases hs with ⟨t₁, ht₁, t₂, ht₂, hts⟩, -- First we show that `t₂` includes `(-∞, a]`, so it suffices to show `(l', ∞) ⊆ t₁` suffices : ∃ l' ∈ Ico l a, Ioi l' ⊆ t₁, { have A : 𝓟 (Iic a) ≤ ⨅ b ∈ Ioi a, 𝓟 (Iio b), from (le_infi $ λ b, le_infi $ λ hb, principal_mono.2 $ Iic_subset_Iio.2 hb), have B : t₁ ∩ Iic a ⊆ s, from subset.trans (inter_subset_inter_right _ (A ht₂)) hts, from this.imp (λ l', Exists.imp $ λ hl' hl x hx, B ⟨hl hx.1, hx.2⟩) }, clear hts ht₂ t₂, -- Now we find `l` such that `(l', ∞) ⊆ t₁` letI := classical.DLO α, rw [mem_binfi] at ht₁, { rcases ht₁ with ⟨b, hb, hb'⟩, exact ⟨max b l, ⟨le_max_right _ _, max_lt hb hl⟩, λ x hx, hb' $ Ioi_subset_Ioi (le_max_left _ _) hx⟩ }, { intros b hb b' hb', simp only [mem_Iio] at hb hb', use [max b b', max_lt hb hb'], simp [le_refl] }, exact ⟨l, hl⟩ end lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) : ∃ u' ∈ Ioc a u, Ico a u' ⊆ s := begin convert @exists_Ioc_subset_of_mem_nhds' (order_dual α) _ _ _ _ _ hs _ hu, ext, rw [dual_Ico, dual_Ioc] end lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) : ∃ l < a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ioc_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.2, hl.snd⟩ lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) : ∃ u (_ : a < u), Ico a u ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩ lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) : s ∈ 𝓝 a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have 𝓝 a = (⨅p : {l // l < a} × {u // a < u}, 𝓟 (Ioo p.1.val p.2.val)), by simp [nhds_order_unbounded hu hl, infi_subtype, infi_prod], iff.intro (assume hs, by rw [this] at hs; from infi_sets_induct hs ⟨l, u, hl', hu', by simp⟩ begin intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩, simp [set.subset_def], intros s₁ s₂ hs₁ l' hl' u' hu' hs₂, letI := classical.DLO α, refine ⟨max l l', _, min u u', _⟩; simp [*, lt_min_iff, max_lt_iff] {contextual := tt} end (assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩)) (assume ⟨l, u, hl, hu, h⟩, by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂)) lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete a₁ a₂ with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end @[priority 100] -- see Note [lower instance priority] instance order_topology.to_order_closed_topology : order_closed_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } lemma order_topology.t2_space : t2_space α := by apply_instance @[priority 100] -- see Note [lower instance priority] instance order_topology.regular_space : regular_space α := { regular := assume s a hs ha, have hs' : sᶜ ∈ 𝓝 a, from mem_nhds_sets hs ha, have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ 𝓝[t] a = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := exists_Ioc_subset_of_mem_nhds hs' h in match dense_or_discrete l a with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h ⟨lt_of_lt_of_le hb₁ hbc, le_of_lt hca⟩ hcs, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, nhds_within_empty _⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ 𝓝[t] a = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := exists_Ico_subset_of_mem_nhds hs' h in match dense_or_discrete a u with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h ⟨le_of_lt hca, lt_of_le_of_lt hbc hb₂⟩ hcs, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, nhds_within_empty _⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [nhds_within_union, ht₁a, ht₂a, bot_sup_eq]⟩, ..order_topology.t2_space } /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`, provided `a` is neither a bottom element nor a top element. -/ lemma mem_nhds_iff_exists_Ioo_subset' {a l' u' : α} {s : set α} (hl' : l' < a) (hu' : a < u') : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := begin split, { assume h, rcases exists_Ico_subset_of_mem_nhds' h hu' with ⟨u, au, hu⟩, rcases exists_Ioc_subset_of_mem_nhds' h hl' with ⟨l, la, hl⟩, refine ⟨l, u, ⟨la.2, au.1⟩, λx hx, _⟩, cases le_total a x with hax hax, { exact hu ⟨hax, hx.2⟩ }, { exact hl ⟨hx.1, hax⟩ } }, { rintros ⟨l, u, ha, h⟩, apply mem_sets_of_superset (mem_nhds_sets is_open_Ioo ha) h } end /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`. -/ lemma mem_nhds_iff_exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := let ⟨l', hl'⟩ := no_bot a in let ⟨u', hu'⟩ := no_top a in mem_nhds_iff_exists_Ioo_subset' hl' hu' lemma Iio_mem_nhds {a b : α} (h : a < b) : Iio b ∈ 𝓝 a := mem_nhds_sets is_open_Iio h lemma Ioi_mem_nhds {a b : α} (h : a < b) : Ioi a ∈ 𝓝 b := mem_nhds_sets is_open_Ioi h lemma Ioo_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioo a b ∈ 𝓝 x := mem_nhds_sets is_open_Ioo ⟨ha, hb⟩ lemma disjoint_nhds_at_top [no_top_order α] (x : α) : disjoint (𝓝 x) at_top := begin rw filter.disjoint_iff, cases no_top x with a ha, use [Iio a, Ici a, Iio_mem_nhds ha, mem_at_top a], rw [inter_comm, Ici_inter_Iio, Ico_self] end @[simp] lemma inf_nhds_at_top [no_top_order α] (x : α) : 𝓝 x ⊓ at_top = ⊥ := disjoint_iff.1 (disjoint_nhds_at_top x) lemma disjoint_nhds_at_bot [no_bot_order α] (x : α) : disjoint (𝓝 x) at_bot := @disjoint_nhds_at_top (order_dual α) _ _ _ _ x @[simp] lemma inf_nhds_at_bot [no_bot_order α] (x : α) : 𝓝 x ⊓ at_bot = ⊥ := @inf_nhds_at_top (order_dual α) _ _ _ _ x lemma not_tendsto_nhds_of_tendsto_at_top [no_top_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_top) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_top x).symm lemma not_tendsto_at_top_of_tendsto_nhds [no_top_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_top := hf.not_tendsto (disjoint_nhds_at_top x) lemma not_tendsto_nhds_of_tendsto_at_bot [no_bot_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_bot) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_bot x).symm lemma not_tendsto_at_bot_of_tendsto_nhds [no_bot_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_bot := hf.not_tendsto (disjoint_nhds_at_bot x) /-! ### Neighborhoods to the left and to the right on an `order_topology` We've seen some properties of left and right neighborhood of a point in an `order_closed_topology`. In an `order_topology`, such neighborhoods can be characterized as the sets containing suitable intervals to the right or to the left of `a`. We give now these characterizations. -/ -- NB: If you extend the list, append to the end please to avoid breaking the API /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `(a, +∞)` 1. `s` is a neighborhood of `a` within `(a, b]` 2. `s` is a neighborhood of `a` within `(a, b)` 3. `s` includes `(a, u)` for some `u ∈ (a, b]` 4. `s` includes `(a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ioi {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[Ioi a] a, -- 0 : `s` is a neighborhood of `a` within `(a, +∞)` s ∈ 𝓝[Ioc a b] a, -- 1 : `s` is a neighborhood of `a` within `(a, b]` s ∈ 𝓝[Ioo a b] a, -- 2 : `s` is a neighborhood of `a` within `(a, b)` ∃ u ∈ Ioc a b, Ioo a u ⊆ s, -- 3 : `s` includes `(a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ioo a u ⊆ s] := -- 4 : `s` includes `(a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Ioc_eq_nhds_within_Ioi hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ioo_eq_nhds_within_Ioi hab], tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 1, { rintros ⟨u, hau, hu⟩, exact mem_sets_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_refl a, hau⟩) hu }, tfae_have : 1 → 4, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨hu ⟨le_of_lt hx.1, hx.2⟩, _⟩, exact hx.1 }, tfae_finish end lemma mem_nhds_within_Ioi_iff_exists_mem_Ioc_Ioo_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioc a u', Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 3 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 4 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_top_order α] {a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu' /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioc a u ⊆ s := begin rw mem_nhds_within_Ioi_iff_exists_Ioo_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b)` 1. `s` is a neighborhood of `b` within `[a, b)` 2. `s` is a neighborhood of `b` within `(a, b)` 3. `s` includes `(l, b)` for some `l ∈ [a, b)` 4. `s` includes `(l, b)` for some `l < b` -/ lemma tfae_mem_nhds_within_Iio {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[Iio b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b)` s ∈ 𝓝[Ico a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b)` s ∈ 𝓝[Ioo a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b)` ∃ l ∈ Ico a b, Ioo l b ⊆ s, -- 3 : `s` includes `(l, b)` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioo l b ⊆ s] := -- 4 : `s` includes `(l, b)` for some `l < b` begin have := @tfae_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ h s, -- If we call `convert` here, it generates wrong equations, so we need to simplify first simp only [exists_prop] at this ⊢, rw [dual_Ioi, dual_Ioc, dual_Ioo] at this, convert this; ext l; rw [dual_Ioo] end lemma mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Ico l' a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 3 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 4 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ico l a ⊆ s := begin convert @mem_nhds_within_Ioi_iff_exists_Ioc_subset (order_dual α) _ _ _ _ _ _ _, simp only [dual_Ioc], refl end /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `[a, +∞)` 1. `s` is a neighborhood of `a` within `[a, b]` 2. `s` is a neighborhood of `a` within `[a, b)` 3. `s` includes `[a, u)` for some `u ∈ (a, b]` 4. `s` includes `[a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ici {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[Ici a] a, -- 0 : `s` is a neighborhood of `a` within `[a, +∞)` s ∈ 𝓝[Icc a b] a, -- 1 : `s` is a neighborhood of `a` within `[a, b]` s ∈ 𝓝[Ico a b] a, -- 2 : `s` is a neighborhood of `a` within `[a, b)` ∃ u ∈ Ioc a b, Ico a u ⊆ s, -- 3 : `s` includes `[a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ico a u ⊆ s] := -- 4 : `s` includes `[a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Icc_eq_nhds_within_Ici hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ico_eq_nhds_within_Ici hab], tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 1, { rintros ⟨u, hau, hu⟩, exact mem_sets_of_superset (Ico_mem_nhds_within_Ici ⟨le_refl a, hau⟩) hu }, tfae_have : 1 → 4, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨hu ⟨hx.1, hx.2⟩, _⟩, exact hx.1 }, tfae_finish end lemma mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioc a u', Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_top_order α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu' /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset' [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b]` 1. `s` is a neighborhood of `b` within `[a, b]` 2. `s` is a neighborhood of `b` within `(a, b]` 3. `s` includes `(l, b]` for some `l ∈ [a, b)` 4. `s` includes `(l, b]` for some `l < b` -/ lemma tfae_mem_nhds_within_Iic {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[Iic b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b]` s ∈ 𝓝[Icc a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b]` s ∈ 𝓝[Ioc a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b]` ∃ l ∈ Ico a b, Ioc l b ⊆ s, -- 3 : `s` includes `(l, b]` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioc l b ⊆ s] := -- 4 : `s` includes `(l, b]` for some `l < b` begin have := @tfae_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ h s, -- If we call `convert` here, it generates wrong equations, so we need to simplify first simp only [exists_prop] at this ⊢, rw [dual_Icc, dual_Ioc, dual_Ioi] at this, convert this; ext l; rw [dual_Ico] end lemma mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Ico l' a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset' [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Icc l a ⊆ s := begin convert @mem_nhds_within_Ici_iff_exists_Icc_subset' (order_dual α) _ _ _ _ _ _ _, simp_rw (show ∀ u : order_dual α, @Icc (order_dual α) _ a u = @Icc α _ u a, from λ u, dual_Icc), refl, end /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u, a < u ∧ Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l, l < a ∧ Icc l a ⊆ s := begin rw mem_nhds_within_Iic_iff_exists_Ioc_subset, split, { rintros ⟨l, la, as⟩, rcases dense la with ⟨v, hv⟩, refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, }, { rintros ⟨l, la, as⟩, exact ⟨l, la, subset.trans Ioc_subset_Icc_self as⟩ } end section functions variables [topological_space β] [linear_order β] [order_topology β] /-- If `f : α → β` is strictly monotone and surjective, it is everywhere right-continuous. Superseded later in this file by `continuous_of_strict_mono_surjective` (same assumptions). -/ lemma continuous_right_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) : continuous_within_at f (Ici a) a := begin have ha : a ∈ Ici a := left_mem_Ici, intros s hs, by_cases hfa_top : ∃ p, f a < p, { obtain ⟨q, hq, hqs⟩ : ∃ q ∈ Ioi (f a), Ico (f a) q ⊆ s := exists_Ico_subset_of_mem_nhds hs hfa_top, refine mem_sets_of_superset (mem_map.2 _) hqs, have h_surj_on := surj_on_Ici_of_monotone_surjective h_mono.monotone h_surj a, rcases h_surj_on (Ioi_subset_Ici_self hq) with ⟨x, hx, rfl⟩, rcases eq_or_lt_of_le hx with rfl|hax, { exact (lt_irrefl _ hq).elim }, refine mem_sets_of_superset (Ico_mem_nhds_within_Ici (left_mem_Ico.2 hax)) _, intros z hz, exact ⟨h_mono.monotone hz.1, h_mono hz.2⟩ }, { push_neg at hfa_top, have ha_top : ∀ x : α, x ≤ a := strict_mono.top_preimage_top h_mono hfa_top, rw [Ici_singleton_of_top ha_top, nhds_within_eq_map_subtype_coe (mem_singleton a), nhds_discrete {x : α // x ∈ {a}}], { exact mem_pure_sets.mpr (mem_of_nhds hs) }, { apply_instance } } end /-- If `f : α → β` is strictly monotone and surjective, it is everywhere left-continuous. Superseded later in this file by `continuous_of_strict_mono_surjective` (same assumptions). -/ lemma continuous_left_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) : continuous_within_at f (Iic a) a := begin apply @continuous_right_of_strict_mono_surjective (order_dual α) (order_dual β), { exact λ x y hxy, h_mono hxy }, { simpa only [dual_Icc] } end end functions end linear_order section linear_ordered_ring variables [topological_space α] [linear_ordered_ring α] [order_topology α] variables {l : filter β} {f g : β → α} /- TODO The theorems in this section ought to be written in the context of linearly ordered (additive) commutative groups rather than linearly ordered rings; however, the former concept does not currently exist in mathlib. -/ /-- In a linearly ordered ring with the order topology, if `f` tends to `C` and `g` tends to `at_top` then `f + g` tends to `at_top`. -/ lemma tendsto_at_top_add_tendsto_left {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := begin obtain ⟨C', hC'⟩ : ∃ C', C' < C := no_bot C, refine tendsto_at_top_add_left_of_le' _ C' _ hg, rw tendsto_order at hf, exact (hf.1 C' hC').mp (eventually_of_forall (λ x hx, le_of_lt hx)) end /-- In a linearly ordered ring with the order topology, if `f` tends to `C` and `g` tends to `at_bot` then `f + g` tends to `at_bot`. -/ lemma tendsto_at_bot_add_tendsto_left {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := begin obtain ⟨C', hC'⟩ : ∃ C', C < C' := no_top C, refine tendsto_at_bot_add_left_of_ge' _ C' _ hg, rw tendsto_order at hf, exact (hf.2 C' hC').mp (eventually_of_forall (λ x hx, le_of_lt hx)) end /-- In a linearly ordered ring with the order topology, if `f` tends to `at_top` and `g` tends to `C` then `f + g` tends to `at_top`. -/ lemma tendsto_at_top_add_tendsto_right {C : α} (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_top := begin convert tendsto_at_top_add_tendsto_left hg hf, ext, exact add_comm _ _, end /-- In a linearly ordered ring with the order topology, if `f` tends to `at_bot` and `g` tends to `C` then `f + g` tends to `at_bot`. -/ lemma tendsto_at_bot_add_tendsto_right {C : α} (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_bot := begin convert tendsto_at_bot_add_tendsto_left hg hf, ext, exact add_comm _ _, end end linear_ordered_ring lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section topological_add_group variables [topological_space α] [ordered_add_comm_group α] [topological_add_group α] lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) := have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg, by rw [preimage_neg]; exact (subset.antisymm (image_closure_subset_closure_image continuous_neg) $ calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) : by rw [←image_comp, this, image_id] ... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) : monotone_image $ image_closure_subset_closure_image continuous_neg ... = _ : by rw [←image_comp, this, image_id]) end topological_add_group section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [order_topology α] [order_topology β] lemma is_lub.nhds_within_ne_bot {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ne_bot (𝓝[s] a) := let ⟨a', ha'⟩ := hs in forall_sets_nonempty_iff_ne_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left ‹a' ∈ s›) this.symm, let ⟨l, hl, hlt₁⟩ := exists_Ioc_subset_of_mem_nhds ht₁ ⟨a', this⟩ in have ∃a'∈s, l < a', from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a', have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ l < a, from not_lt.2 $ ha.right this, this ‹l < a›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hlt₁ ⟨‹l < a'›, ha.left ha'⟩, ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma is_glb.nhds_within_ne_bot : ∀ {a : α} {s : set α}, is_glb s a → s.nonempty → ne_bot (𝓝[s] a) := @is_lub.nhds_within_ne_bot (order_dual α) _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) [ne_bot (f ⊓ 𝓝 a)] : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := nonempty_of_mem_sets this in have b < b, from lt_of_lt_of_le hxb $ hb hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → ne_bot (f ⊓ 𝓝 a) → is_glb s a := @is_lub_of_mem_nhds (order_dual α) _ _ _ lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s.nonempty) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : is_lub (f '' s) b := have hnbot : ne_bot (𝓝[s] a), from ha.nhds_within_ne_bot hs, have ∀a'∈s, ¬ b < f a', from assume a' ha' h, have ∀ᶠ x in 𝓝 b, x < f a', from mem_nhds_sets (is_open_gt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a < f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left ha') h.symm, have {x | a' < x} ∈ 𝓝 a, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ 𝓝 a, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ 𝓝[s] a, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := hnbot.nonempty_of_mem this in have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_le_of_lt ha'x hxa')), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', by exactI (le_of_tendsto hb $ mem_inf_sets_of_right $ assume x hx, hb' $ mem_image_of_mem _ hx)) lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b (λ x hx y hy, hf y hy x hx) lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_lub (f '' s) b := @is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : a ∈ closure s := by rw closure_eq_cluster_pts; exact ha.nhds_within_ne_bot hs lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := by rw ←sc.closure_eq; exact mem_closure_of_is_lub ha hs lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : a ∈ closure s := by rw closure_eq_cluster_pts; exact ha.nhds_within_ne_bot hs lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := by rw ←sc.closure_eq; exact mem_closure_of_is_glb ha hs /-- A compact set is bounded below -/ lemma is_compact.bdd_below {α : Type u} [topological_space α] [linear_order α] [order_closed_topology α] [nonempty α] {s : set α} (hs : is_compact s) : bdd_below s := begin by_contra H, letI := classical.DLO α, rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _ with ⟨t, st, ft, ht⟩, { refine H (ft.bdd_below.imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma is_compact.bdd_above {α : Type u} [topological_space α] [linear_order α] [order_topology α] : Π [nonempty α] {s : set α}, is_compact s → bdd_above s := @is_compact.bdd_below (order_dual α) _ _ _ end order_topology section linear_order variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α] /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top element. -/ lemma closure_Ioi' {a b : α} (hab : a < b) : closure (Ioi a) = Ici a := begin apply subset.antisymm, { exact closure_minimal Ioi_subset_Ici_self is_closed_Ici }, { assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_glb is_glb_Ioi ⟨_, hab⟩ }, { exact subset_closure (lt_of_le_of_ne hx (ne.symm h)) } } end /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/ @[simp] lemma closure_Ioi (a : α) [no_top_order α] : closure (Ioi a) = Ici a := let ⟨b, hb⟩ := no_top a in closure_Ioi' hb /-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom element. -/ lemma closure_Iio' {a b : α} (hab : b < a) : closure (Iio a) = Iic a := begin apply subset.antisymm, { exact closure_minimal Iio_subset_Iic_self is_closed_Iic }, { assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_lub is_lub_Iio ⟨_, hab⟩ }, { apply subset_closure, by simpa [h] using lt_or_eq_of_le hx } } end /-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/ @[simp] lemma closure_Iio (a : α) [no_bot_order α] : closure (Iio a) = Iic a := let ⟨b, hb⟩ := no_bot a in closure_Iio' hb /-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioo {a b : α} (hab : a < b) : closure (Ioo a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioo_subset_Icc_self is_closed_Icc }, { have hab' : (Ioo a b).nonempty, from nonempty_Ioo.2 hab, assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_glb (is_glb_Ioo hab) hab' }, by_cases h' : x = b, { rw h', refine mem_closure_of_is_lub (is_lub_Ioo hab) hab' }, exact subset_closure ⟨lt_of_le_of_ne hx.1 (ne.symm h), by simpa [h'] using lt_or_eq_of_le hx.2⟩ } end /-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioc {a b : α} (hab : a < b) : closure (Ioc a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioc_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ioc_self), rw closure_Ioo hab } end /-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ico {a b : α} (hab : a < b) : closure (Ico a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ico_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ico_self), rw closure_Ioo hab } end @[simp] lemma interior_Ici [no_bot_order α] {a : α} : interior (Ici a) = Ioi a := by rw [← compl_Iio, interior_compl, closure_Iio, compl_Iic] @[simp] lemma interior_Iic [no_top_order α] {a : α} : interior (Iic a) = Iio a := by rw [← compl_Ioi, interior_compl, closure_Ioi, compl_Ici] @[simp] lemma interior_Icc [no_bot_order α] [no_top_order α] {a b : α}: interior (Icc a b) = Ioo a b := by rw [← Ici_inter_Iic, interior_inter, interior_Ici, interior_Iic, Ioi_inter_Iio] @[simp] lemma interior_Ico [no_bot_order α] {a b : α} : interior (Ico a b) = Ioo a b := by rw [← Ici_inter_Iio, interior_inter, interior_Ici, interior_Iio, Ioi_inter_Iio] @[simp] lemma interior_Ioc [no_top_order α] {a b : α} : interior (Ioc a b) = Ioo a b := by rw [← Ioi_inter_Iic, interior_inter, interior_Ioi, interior_Iic, Ioi_inter_Iio] @[simp] lemma frontier_Ici [no_bot_order α] {a : α} : frontier (Ici a) = {a} := by simp [frontier] @[simp] lemma frontier_Iic [no_top_order α] {a : α} : frontier (Iic a) = {a} := by simp [frontier] @[simp] lemma frontier_Ioi [no_top_order α] {a : α} : frontier (Ioi a) = {a} := by simp [frontier] @[simp] lemma frontier_Iio [no_bot_order α] {a : α} : frontier (Iio a) = {a} := by simp [frontier] @[simp] lemma frontier_Icc [no_bot_order α] [no_top_order α] {a b : α} (h : a < b) : frontier (Icc a b) = {a, b} := by simp [frontier, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ioo {a b : α} (h : a < b) : frontier (Ioo a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ico [no_bot_order α] {a b : α} (h : a < b) : frontier (Ico a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ioc [no_top_order α] {a b : α} (h : a < b) : frontier (Ioc a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] lemma nhds_within_Ioi_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : a ≤ b) : ne_bot (𝓝[Ioi a] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Ioi' H₁], exact H₂ } lemma nhds_within_Ioi_ne_bot [no_top_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Ioi a] b) := let ⟨c, hc⟩ := no_top a in nhds_within_Ioi_ne_bot' hc H lemma nhds_within_Ioi_self_ne_bot' {a b : α} (H : a < b) : ne_bot (𝓝[Ioi a] a) := nhds_within_Ioi_ne_bot' H (le_refl a) @[instance] lemma nhds_within_Ioi_self_ne_bot [no_top_order α] (a : α) : ne_bot (𝓝[Ioi a] a) := nhds_within_Ioi_ne_bot (le_refl a) lemma nhds_within_Iio_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : b ≤ c) : ne_bot (𝓝[Iio c] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Iio' H₁], exact H₂ } lemma nhds_within_Iio_ne_bot [no_bot_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Iio b] a) := let ⟨c, hc⟩ := no_bot b in nhds_within_Iio_ne_bot' hc H lemma nhds_within_Iio_self_ne_bot' {a b : α} (H : a < b) : ne_bot (𝓝[Iio b] b) := nhds_within_Iio_ne_bot' H (le_refl b) @[instance] lemma nhds_within_Iio_self_ne_bot [no_bot_order α] (a : α) : ne_bot (𝓝[Iio a] a) := nhds_within_Iio_ne_bot (le_refl a) end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [order_topology α] [densely_ordered α] /-- The `at_top` filter for an open interval `Ioo a b` comes from the left-neighbourhoods filter at the right endpoint in the ambient order. -/ lemma Ioo_at_top_eq_nhds_within {a b : α} (h : a < b) : (at_top : filter (Ioo a b)) = comap (coe : Ioo a b → α) (𝓝[Iio b] b) := begin haveI : nonempty (Ioo a b) := nonempty_Ioo_subtype h, ext, split, { intros hs, obtain ⟨x, hx⟩ : ∃ x : (Ioo a b), ∀ z : (Ioo a b), z ≥ x → z ∈ s := mem_at_top_sets.mp hs, refine ⟨Ioo x b, Ioo_mem_nhds_within_Iio (right_mem_Ioc.mpr x.2.2), _⟩, intros z hz, simpa using hx z (le_of_lt hz.1) }, { rintros ⟨t, ht, hts⟩, obtain ⟨x, hx, hxt⟩ : ∃ x ∈ Iio b, Ioo x b ⊆ t := (mem_nhds_within_Iio_iff_exists_Ioo_subset' h).mp ht, obtain ⟨y, hay, hyb⟩ : ∃ y, max a x < y ∧ y < b := dense (max_lt_iff.mpr ⟨h, hx⟩), refine mem_at_top_sets.mpr ⟨⟨y, (max_lt_iff.mp hay).1, hyb⟩, _⟩, intros z hz, exact hts (hxt ⟨lt_of_lt_of_le (lt_of_le_of_lt (le_max_right a x) hay) hz, z.2.2⟩) } end /-- The `at_bot` filter for an open interval `Ioo a b` comes from the right-neighbourhoods filter at the left endpoint in the ambient order. -/ lemma Ioo_at_bot_eq_nhds_within {a b : α} (h : a < b) : (at_bot : filter (Ioo a b)) = comap (coe : Ioo a b → α) (𝓝[Ioi a] a) := begin haveI : nonempty (Ioo a b) := nonempty_Ioo_subtype h, ext, split, { intros hs, obtain ⟨x, hx⟩ : ∃ x : (Ioo a b), ∀ z : (Ioo a b), z ≤ x → z ∈ s := mem_at_bot_sets.mp hs, refine ⟨Ioo a x, Ioo_mem_nhds_within_Ioi (left_mem_Ico.mpr x.2.1), _⟩, intros z hz, simpa using hx z (le_of_lt hz.2) }, { rintros ⟨t, ht, hts⟩, obtain ⟨x, hx, hxt⟩ : ∃ x ∈ Ioi a, Ioo a x ⊆ t := (mem_nhds_within_Ioi_iff_exists_Ioo_subset' h).mp ht, obtain ⟨y, hay, hyb⟩ : ∃ y, a < y ∧ y < min b x := dense (lt_min_iff.mpr ⟨h, hx⟩), refine mem_at_bot_sets.mpr ⟨⟨y, hay, (lt_min_iff.mp hyb).1⟩, _⟩, intros z hz, exact hts (hxt ⟨z.2.1, lt_of_le_of_lt hz (lt_of_lt_of_le hyb (min_le_right b x))⟩) } end end decidable_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] [complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_Sup _) hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_Inf _) hs lemma is_closed.Sup_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_Sup _) hs hc lemma is_closed.Inf_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_Inf _) hs hc /-- A monotone function continuous at the supremum of a nonempty set sends this supremum to the supremum of the image of this set. -/ lemma map_Sup_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (hs : s.nonempty) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub_of_is_lub_of_tendsto (is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Mf xy) (is_lub_Sup _) hs $ Cf.mono_left inf_le_left).Sup_eq.symm /-- A monotone function `s` sending `bot` to `bot` and continuous at the supremum of a set sends this supremum to the supremum of the image of this set. -/ lemma map_Sup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (Sup s) = Sup (f '' s) := begin cases s.eq_empty_or_nonempty with h h, { simp [h, fbot] }, { exact map_Sup_of_continuous_at_of_monotone' Cf Mf h } end /-- A monotone function continuous at the indexed supremum over a nonempty `Sort` sends this indexed supremum to the indexed supremum of the composition. -/ lemma map_supr_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_Sup_of_continuous_at_of_monotone' Cf Mf (range_nonempty g), ← range_comp, supr] /-- If a monotone function sending `bot` to `bot` is continuous at the indexed supremum over a `Sort`, then it sends this indexed supremum to the indexed supremum of the composition. -/ lemma map_supr_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_Sup_of_continuous_at_of_monotone Cf Mf fbot, ← range_comp, supr] /-- A monotone function continuous at the infimum of a nonempty set sends this infimum to the infimum of the image of this set. -/ lemma map_Inf_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := @map_Sup_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual hs /-- A monotone function `s` sending `top` to `top` and continuous at the infimum of a set sends this infimum to the infimum of the image of this set. -/ lemma map_Inf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (Inf s) = Inf (f '' s) := @map_Sup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual ftop /-- A monotone function continuous at the indexed infimum over a nonempty `Sort` sends this indexed infimum to the indexed infimum of the composition. -/ lemma map_infi_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) : f (⨅ i, g i) = ⨅ i, f (g i) := @map_supr_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ ι _ f g Cf Mf.order_dual /-- If a monotone function sending `top` to `top` is continuous at the indexed infimum over a `Sort`, then it sends this indexed infimum to the indexed infimum of the composition. -/ lemma map_infi_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (infi g) = infi (f ∘ g) := @map_supr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ ι f g Cf Mf.order_dual ftop end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ] lemma cSup_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_cSup hs B) hs lemma cInf_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_cInf hs B) hs lemma is_closed.cSup_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc lemma is_closed.cInf_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc /-- If a monotone function is continuous at the supremum of a nonempty bounded above set `s`, then it sends this supremum to the supremum of the image of `s`. -/ lemma map_cSup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine ((is_lub_cSup (ne.image f) (Mf.map_bdd_above H)).unique _).symm, refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Mf xy) (is_lub_cSup ne H) ne _, exact Cf.mono_left inf_le_left end /-- If a monotone function is continuous at the indexed supremum of a bounded function on a nonempty `Sort`, then it sends this supremum to the supremum of the composition. -/ lemma map_csupr_of_continuous_at_of_monotone {f : α → β} {g : γ → α} (Cf : continuous_at f (⨆ i, g i)) (Mf : monotone f) (H : bdd_above (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_cSup_of_continuous_at_of_monotone Cf Mf (range_nonempty _) H, ← range_comp, supr] /-- If a monotone function is continuous at the infimum of a nonempty bounded below set `s`, then it sends this infimum to the infimum of the image of `s`. -/ lemma map_cInf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := @map_cSup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual ne H /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete linear order, under a boundedness assumption. -/ lemma map_cinfi_of_continuous_at_of_monotone {f : α → β} {g : γ → α} (Cf : continuous_at f (⨅ i, g i)) (Mf : monotone f) (H : bdd_below (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := @map_csupr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ _ _ _ _ Cf Mf.order_dual H /-- A bounded connected subset of a conditionally complete linear order includes the open interval `(Inf s, Sup s)`. -/ lemma is_connected.Ioo_cInf_cSup_subset {s : set α} (hs : is_connected s) (hb : bdd_below s) (ha : bdd_above s) : Ioo (Inf s) (Sup s) ⊆ s := λ x hx, let ⟨y, ys, hy⟩ := (is_glb_lt_iff (is_glb_cInf hs.nonempty hb)).1 hx.1 in let ⟨z, zs, hz⟩ := (lt_is_lub_iff (is_lub_cSup hs.nonempty ha)).1 hx.2 in hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ lemma eq_Icc_cInf_cSup_of_connected_bdd_closed {s : set α} (hc : is_connected s) (hb : bdd_below s) (ha : bdd_above s) (hcl : is_closed s) : s = Icc (Inf s) (Sup s) := subset.antisymm (subset_Icc_cInf_cSup hb ha) $ hc.Icc_subset (hcl.cInf_mem hc.nonempty hb) (hcl.cSup_mem hc.nonempty ha) lemma is_preconnected.Ioi_cInf_subset {s : set α} (hs : is_preconnected s) (hb : bdd_below s) (ha : ¬bdd_above s) : Ioi (Inf s) ⊆ s := begin have sne : s.nonempty := @nonempty_of_not_bdd_above α _ s ⟨Inf ∅⟩ ha, intros x hx, obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := (is_glb_lt_iff (is_glb_cInf sne hb)).1 hx, obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x, exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ end lemma is_preconnected.Iio_cSup_subset {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s) (ha : bdd_above s) : Iio (Sup s) ⊆ s := @is_preconnected.Ioi_cInf_subset (order_dual α) _ _ _ s hs ha hb /-- A preconnected set in a conditionally complete linear order is either one of the intervals `[Inf s, Sup s]`, `[Inf s, Sup s)`, `(Inf s, Sup s]`, `(Inf s, Sup s)`, `[Inf s, +∞)`, `(Inf s, +∞)`, `(-∞, Sup s]`, `(-∞, Sup s)`, `(-∞, +∞)`, or `∅`. The converse statement requires `α` to be densely ordererd. -/ lemma is_preconnected.mem_intervals {s : set α} (hs : is_preconnected s) : s ∈ ({Icc (Inf s) (Sup s), Ico (Inf s) (Sup s), Ioc (Inf s) (Sup s), Ioo (Inf s) (Sup s), Ici (Inf s), Ioi (Inf s), Iic (Sup s), Iio (Sup s), univ, ∅} : set (set α)) := begin rcases s.eq_empty_or_nonempty with rfl|hne, { apply_rules [or.inr, mem_singleton] }, have hs' : is_connected s := ⟨hne, hs⟩, by_cases hb : bdd_below s; by_cases ha : bdd_above s, { rcases mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset (hs'.Ioo_cInf_cSup_subset hb ha) (subset_Icc_cInf_cSup hb ha) with hs|hs|hs|hs, { exact (or.inl hs) }, { exact (or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inr $ or.inl hs) } }, { refine (or.inr $ or.inr $ or.inr $ or.inr _), cases mem_Ici_Ioi_of_subset_of_subset (hs.Ioi_cInf_subset hb ha) (λ x hx, cInf_le hb hx) with hs hs, { exact or.inl hs }, { exact or.inr (or.inl hs) } }, { iterate 6 { apply or.inr }, cases mem_Iic_Iio_of_subset_of_subset (hs.Iio_cSup_subset hb ha) (λ x hx, le_cSup ha hx) with hs hs, { exact or.inl hs }, { exact or.inr (or.inl hs) } }, { iterate 8 { apply or.inr }, exact or.inl (hs.eq_univ_of_unbounded hb ha) } end /-- A preconnected set is either one of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, or `univ`, or `∅`. The converse statement requires `α` to be densely ordererd. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve readability. -/ lemma set_of_is_preconnected_subset_of_ordered : {s : set α | is_preconnected s} ⊆ -- bounded intervals (range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪ -- unbounded intervals and `univ` (range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) := begin intros s hs, rcases hs.mem_intervals with hs|hs|hs|hs|hs|hs|hs|hs|hs|hs, { exact (or.inl $ or.inl $ or.inl $ or.inl ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inl ⟨Inf s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inr ⟨Inf s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) }, { exact (or.inr $ or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inr hs) } end /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and the set `s ∩ [a, b)` has no maximal point, then `b ∈ s`. -/ lemma is_closed.mem_of_ge_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hab : a ≤ b) (hgt : ∀ x ∈ s ∩ Ico a b, (s ∩ Ioc x b).nonempty) : b ∈ s := begin let S := s ∩ Icc a b, replace ha : a ∈ S, from ⟨ha, left_mem_Icc.2 hab⟩, have Sbd : bdd_above S, from ⟨b, λ z hz, hz.2.2⟩, let c := Sup (s ∩ Icc a b), have c_mem : c ∈ S, from hs.cSup_mem ⟨_, ha⟩ Sbd, have c_le : c ≤ b, from cSup_le ⟨_, ha⟩ (λ x hx, hx.2.2), cases eq_or_lt_of_le c_le with hc hc, from hc ▸ c_mem.1, exfalso, rcases hgt c ⟨c_mem.1, c_mem.2.1, hc⟩ with ⟨x, xs, cx, xb⟩, exact not_lt_of_le (le_cSup Sbd ⟨xs, le_trans (le_cSup Sbd ha) (le_of_lt cx), xb⟩) cx end /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and for any `a ≤ x < y ≤ b`, `x ∈ s`, the set `s ∩ (x, y]` is not empty, then `[a, b] ⊆ s`. -/ lemma is_closed.Icc_subset_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, ∀ y ∈ Ioi x, (s ∩ Ioc x y).nonempty) : Icc a b ⊆ s := begin assume y hy, have : is_closed (s ∩ Icc a y), { suffices : s ∩ Icc a y = s ∩ Icc a b ∩ Icc a y, { rw this, exact is_closed_inter hs is_closed_Icc }, rw [inter_assoc], congr, exact (inter_eq_self_of_subset_right $ Icc_subset_Icc_right hy.2).symm }, exact is_closed.mem_of_ge_of_forall_exists_gt this ha hy.1 (λ x hx, hgt x ⟨hx.1, Ico_subset_Ico_right hy.2 hx.2⟩ y hx.2.2) end section densely_ordered variables [densely_ordered α] {a b : α} /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and for any `x ∈ s ∩ [a, b)` the set `s` includes some open neighborhood of `x` within `(x, +∞)`, then `[a, b] ⊆ s`. -/ lemma is_closed.Icc_subset_of_forall_mem_nhds_within {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, s ∈ 𝓝[Ioi x] x) : Icc a b ⊆ s := begin apply hs.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxs, hxab⟩ y hyxb, have : s ∩ Ioc x y ∈ 𝓝[Ioi x] x, from inter_mem_sets (hgt x ⟨hxs, hxab⟩) (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hyxb⟩), exact (nhds_within_Ioi_self_ne_bot' hxab.2).nonempty_of_mem this end /-- A closed interval in a densely ordered conditionally complete linear order is preconnected. -/ lemma is_preconnected_Icc : is_preconnected (Icc a b) := is_preconnected_closed_iff.2 begin rintros s t hs ht hab ⟨x, hx⟩ ⟨y, hy⟩, wlog hxy : x ≤ y := le_total x y using [x y s t, y x t s], have xyab : Icc x y ⊆ Icc a b := Icc_subset_Icc hx.1.1 hy.1.2, by_contradiction hst, suffices : Icc x y ⊆ s, from hst ⟨y, xyab $ right_mem_Icc.2 hxy, this $ right_mem_Icc.2 hxy, hy.2⟩, apply (is_closed_inter hs is_closed_Icc).Icc_subset_of_forall_mem_nhds_within hx.2, rintros z ⟨zs, hz⟩, have zt : z ∈ tᶜ, from λ zt, hst ⟨z, xyab $ Ico_subset_Icc_self hz, zs, zt⟩, have : tᶜ ∩ Ioc z y ∈ 𝓝[Ioi z] z, { rw [← nhds_within_Ioc_eq_nhds_within_Ioi hz.2], exact mem_nhds_within.2 ⟨tᶜ, ht, zt, subset.refl _⟩}, apply mem_sets_of_superset this, have : Ioc z y ⊆ s ∪ t, from λ w hw, hab (xyab ⟨le_trans hz.1 (le_of_lt hw.1), hw.2⟩), exact λ w ⟨wt, wzy⟩, (this wzy).elim id (λ h, (wt h).elim) end lemma is_preconnected_interval : is_preconnected (interval a b) := is_preconnected_Icc lemma is_preconnected_iff_ord_connected {s : set α} : is_preconnected s ↔ ord_connected s := ⟨λ h x hx y hy, h.Icc_subset hx hy, λ h, is_preconnected_of_forall_pair $ λ x y hx hy, ⟨interval x y, h.interval_subset hx hy, left_mem_interval, right_mem_interval, is_preconnected_interval⟩⟩ alias is_preconnected_iff_ord_connected ↔ is_preconnected.ord_connected set.ord_connected.is_preconnected lemma is_preconnected_Ici : is_preconnected (Ici a) := ord_connected_Ici.is_preconnected lemma is_preconnected_Iic : is_preconnected (Iic a) := ord_connected_Iic.is_preconnected lemma is_preconnected_Iio : is_preconnected (Iio a) := ord_connected_Iio.is_preconnected lemma is_preconnected_Ioi : is_preconnected (Ioi a) := ord_connected_Ioi.is_preconnected lemma is_preconnected_Ioo : is_preconnected (Ioo a b) := ord_connected_Ioo.is_preconnected lemma is_preconnected_Ioc : is_preconnected (Ioc a b) := ord_connected_Ioc.is_preconnected lemma is_preconnected_Ico : is_preconnected (Ico a b) := ord_connected_Ico.is_preconnected @[priority 100] instance ordered_connected_space : preconnected_space α := ⟨ord_connected_univ.is_preconnected⟩ /-- In a dense conditionally complete linear order, the set of preconnected sets is exactly the set of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, `(-∞, +∞)`, or `∅`. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve readability. -/ lemma set_of_is_preconnected_eq_of_ordered : {s : set α | is_preconnected s} = -- bounded intervals (range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪ -- unbounded intervals and `univ` (range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) := begin refine subset.antisymm set_of_is_preconnected_subset_of_ordered _, simp only [subset_def, -mem_range, forall_range_iff, uncurry, or_imp_distrib, forall_and_distrib, mem_union, mem_set_of_eq, insert_eq, mem_singleton_iff, forall_eq, forall_true_iff, and_true, is_preconnected_Icc, is_preconnected_Ico, is_preconnected_Ioc, is_preconnected_Ioo, is_preconnected_Ioi, is_preconnected_Iio, is_preconnected_Ici, is_preconnected_Iic, is_preconnected_univ, is_preconnected_empty], end /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≤ t ≤ f b`.-/ lemma intermediate_value_Icc {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) : Icc (f a) (f b) ⊆ f '' (Icc a b) := is_preconnected_Icc.intermediate_value (left_mem_Icc.2 hab) (right_mem_Icc.2 hab) hf /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≥ t ≥ f b`.-/ lemma intermediate_value_Icc' {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) : Icc (f b) (f a) ⊆ f '' (Icc a b) := is_preconnected_Icc.intermediate_value (right_mem_Icc.2 hab) (left_mem_Icc.2 hab) hf /-- A continuous function which tendsto `at_top` `at_top` and to `at_bot` `at_bot` is surjective. -/ lemma surjective_of_continuous {f : α → β} (hf : continuous f) (h_top : tendsto f at_top at_top) (h_bot : tendsto f at_bot at_bot) : function.surjective f := begin intros p, obtain ⟨b, hb⟩ : ∃ b, p ≤ f b, { rcases ((tendsto_at_top_at_top _).mp h_top) p with ⟨b, hb⟩, exact ⟨b, hb b rfl.ge⟩ }, obtain ⟨a, hab, ha⟩ : ∃ a, a ≤ b ∧ f a ≤ p, { rcases ((tendsto_at_bot_at_bot _).mp h_bot) p with ⟨x, hx⟩, exact ⟨min x b, min_le_right x b, hx (min x b) (min_le_left x b)⟩ }, rcases intermediate_value_Icc hab hf.continuous_on ⟨ha, hb⟩ with ⟨x, _, hx⟩, exact ⟨x, hx⟩ end /-- A continuous function which tendsto `at_bot` `at_top` and to `at_top` `at_bot` is surjective. -/ lemma surjective_of_continuous' {f : α → β} (hf : continuous f) (h_top : tendsto f at_bot at_top) (h_bot : tendsto f at_top at_bot) : function.surjective f := @surjective_of_continuous (order_dual α) β _ _ _ _ _ _ _ _ hf h_top h_bot end densely_ordered lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Inf s ∈ s := hs.is_closed.cInf_mem ne_s hs.bdd_below lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Sup s ∈ s := @is_compact.Inf_mem (order_dual α) _ _ _ _ hs ne_s lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_glb s (Inf s) := is_glb_cInf ne_s hs.bdd_below lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_lub s (Sup s) := @is_compact.is_glb_Inf (order_dual α) _ _ _ _ hs ne_s lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_least s (Inf s) := ⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩ lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_greatest s (Sup s) := @is_compact.is_least_Inf (order_dual α) _ _ _ _ hs ne_s lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_least s x := ⟨_, hs.is_least_Inf ne_s⟩ lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_greatest s x := ⟨_, hs.is_greatest_Sup ne_s⟩ lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_glb s x := ⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩ lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_lub s x := ⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩ lemma is_compact.exists_Inf_image_eq {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) : ∃ x ∈ s, Inf (f '' s) = f x := let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f) in ⟨x, hxs, hx.symm⟩ /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma is_compact.exists_forall_le {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) : ∃x∈s, ∀y∈s, f x ≤ f y := begin rcases hs.exists_Inf_image_eq ne_s hf with ⟨x, hxs, hx⟩, refine ⟨x, hxs, λ y hy, _⟩, rw ← hx, exact ((hs.image_of_continuous_on hf).is_glb_Inf (ne_s.image f)).1 (mem_image_of_mem _ hy) end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma is_compact.exists_forall_ge {α : Type u} [topological_space α]: ∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s → ∃x∈s, ∀y∈s, f y ≤ f x := @is_compact.exists_forall_le (order_dual β) _ _ _ _ _ lemma is_compact.exists_Sup_image_eq {α : Type u} [topological_space α]: ∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s → ∃ x ∈ s, Sup (f '' s) = f x := @is_compact.exists_Inf_image_eq (order_dual β) _ _ _ _ _ lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) : s = Icc (Inf s) (Sup s) := eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed end conditionally_complete_linear_order section liminf_limsup section order_closed_topology variables [semilattice_sup α] [topological_space α] [order_topology α] lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, eventually_of_forall h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma filter.tendsto.is_bounded_under_le {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u := (is_bounded_le_nhds a).mono h lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) := (is_bounded_le_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_ge {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u := h.is_bounded_under_le.is_cobounded_flip end order_closed_topology section order_closed_topology variables [semilattice_inf α] [topological_space α] [order_topology α] lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) := @is_bounded_le_nhds (order_dual α) _ _ _ a lemma filter.tendsto.is_bounded_under_ge {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u := (is_bounded_ge_nhds a).mono h lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) := (is_bounded_ge_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_le {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u := h.is_bounded_under_ge.is_cobounded_flip end order_closed_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : ∀ᶠ a in f, a < b := let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → b < f.Liminf → ∀ᶠ a in f, b < a := @lt_mem_sets_of_Limsup_lt (order_dual α) _ variables [topological_space α] [order_topology α] /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ 𝓝 a := tendsto_order.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a := cInf_intro (is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from match dense_or_discrete a b with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from (is_bounded_ge_nhds a).mono h, have hb_le : is_bounded (≤) f, from (is_bounded_le_nhds a).mono h, le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hb_le hb_ge ... ≤ (𝓝 a).Limsup : Limsup_le_Limsup_of_le h hb_ge.is_cobounded_flip (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) hb_le.is_cobounded_flip) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α} [ne_bot f], f ≤ 𝓝 a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ /-- If a function has a limit, then its limsup coincides with its limit. -/ theorem filter.tendsto.limsup_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : limsup f u = a := Limsup_eq_of_le_nhds h /-- If a function has a limit, then its liminf coincides with its limit. -/ theorem filter.tendsto.liminf_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : liminf f u = a := Liminf_eq_of_le_nhds h end conditionally_complete_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] -- In complete_linear_order, the above theorems take a simpler form /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (hinf : liminf f u = a) (hsup : limsup f u = a) : tendsto u f (𝓝 a) := le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot hsup hinf /-- If a number `a` is less than or equal to the `liminf` of a function `f` at some filter and is greater than or equal to the `limsup` of `f`, then `f` tends to `a` along this filter. -/ theorem tendsto_of_le_liminf_of_limsup_le {f : filter β} {u : β → α} {a : α} (hinf : a ≤ liminf f u) (hsup : limsup f u ≤ a) : tendsto u f (𝓝 a) := if hf : f = ⊥ then hf.symm ▸ tendsto_bot else by haveI : ne_bot f := hf; exact tendsto_of_liminf_eq_limsup (le_antisymm (le_trans liminf_le_limsup hsup) hinf) (le_antisymm hsup (le_trans hinf liminf_le_limsup)) end complete_linear_order end liminf_limsup end order_topology lemma order_topology_of_nhds_abs {α : Type*} [decidable_linear_ordered_add_comm_group α] [topological_space α] (h_nhds : ∀a:α, 𝓝 a = (⨅r>0, 𝓟 {b | abs (a - b) < r})) : order_topology α := order_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr begin simp [infi_and, topological_space.nhds_generate_from, h_nhds, le_infi_iff, -le_principal_iff, and_comm], refine ⟨λ s ha b hs, _, λ r hr, _⟩, { rcases hs with rfl | rfl, { refine infi_le_of_le (a - b) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _), have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc, exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) }, { refine infi_le_of_le (b - a) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _), have : abs (c - a) < b - a, {rw abs_sub; simpa using hc}, have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this, exact lt_of_add_lt_add_right this } }, { have h : {b | abs (a - b) < r} = {b | a - r < b} ∩ {b | b < a + r}, from set.ext (assume b, by simp [abs_lt, sub_lt, lt_sub_iff_add_lt, sub_lt_iff_lt_add']; cc), rw [h, ← inf_principal], apply le_inf _ _, { exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $ infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) }, { exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $ infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } } end lemma tendsto_at_top_supr_nat [topological_space α] [complete_linear_order α] [order_topology α] (f : ℕ → α) (hf : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_order.2 $ and.intro (assume a ha, let ⟨n, hn⟩ := lt_supr_iff.1 ha in mem_at_top_sets.2 ⟨n, assume i hi, lt_of_lt_of_le hn (hf hi)⟩) (assume a ha, univ_mem_sets' (assume n, lt_of_le_of_lt (le_supr _ n) ha)) lemma tendsto_at_top_infi_nat [topological_space α] [complete_linear_order α] [order_topology α] (f : ℕ → α) (hf : ∀{n m}, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 (⨅i, f i)) := @tendsto_at_top_supr_nat (order_dual α) _ _ _ _ @hf lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α] {f : ℕ → α} {a : α} (hf : monotone f) : tendsto f at_top (𝓝 a) → supr f = a := tendsto_nhds_unique (tendsto_at_top_supr_nat f hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α] {f : ℕ → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 a) → infi f = a := tendsto_nhds_unique (tendsto_at_top_infi_nat f hf) /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_top_at_top [decidable_linear_ordered_add_comm_group α] : tendsto (abs : α → α) at_top at_top := tendsto_at_top_mono (λ n, le_abs_self _) tendsto_id local notation `|` x `|` := abs x lemma decidable_linear_ordered_add_comm_group.tendsto_nhds [decidable_linear_ordered_add_comm_group α] [topological_space α] [order_topology α] {β : Type*} (f : β → α) (x : filter β) (a : α) : filter.tendsto f x (nhds a) ↔ ∀ ε > (0 : α), ∀ᶠ b in x, |f b - a| < ε := begin rw (show _, from @tendsto_order α), -- does not work without `show` for some reason split, { rintros ⟨hyp_lt_a, hyp_gt_a⟩ ε ε_pos, suffices : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff], have set1 : {b : β | a - f b < ε} ∈ x, { have : {b : β | a - ε < f b} ∈ x, from hyp_lt_a (a - ε) (sub_lt_self a ε_pos), have : ∀ b, a - f b < ε ↔ a - ε < f b, by { intro _, exact sub_lt }, simpa only [this] }, have set2 : {b : β | f b - a < ε} ∈ x, { have : {b : β | a + ε > f b} ∈ x, from hyp_gt_a (a + ε) (lt_add_of_pos_right a ε_pos), have : ∀ b, f b - a < ε ↔ a + ε > f b, by { intro _, exact sub_lt_iff_lt_add' }, simpa only [this] }, exact (x.inter_sets set2 set1) }, { assume hyp_ε_pos, split, { assume a' a'_lt_a, let ε := a - a', have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_lt_a), have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this, have : {b : β | a - f b < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_right _ _), have : ∀ b, a' < f b ↔ a - f b < ε, by {intro b, rw [sub_lt, sub_sub_self] }, simpa only [this] }, { assume a' a'_gt_a, let ε := a' - a, have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_gt_a), have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this, have : {b : β | f b - a < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_left _ _), have : ∀ b, f b < a' ↔ f b - a < ε, by { intro b, simp [lt_sub_iff_add_lt] }, simpa only [this] }} end /-! Here is a counter-example to a version of the following with `conditionally_complete_lattice α`. Take `α = [0, 1) → ℝ` with the natural lattice structure, `ι = ℕ`. Put `f n x = -x^n`. Then `⨆ n, f n = 0` while none of `f n` is strictly greater than the constant function `-0.5`. -/ lemma tendsto_at_top_csupr {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) (hbdd : bdd_above $ range f) : tendsto f at_top (𝓝 (⨆i, f i)) := begin by_cases hi : nonempty ι, { resetI, rw tendsto_order, split, { intros a h, cases exists_lt_of_lt_csupr h with N hN, apply eventually.mono (mem_at_top N), exact λ i hi, lt_of_lt_of_le hN (h_mono hi) }, { exact λ a h, eventually_of_forall (λ n, lt_of_le_of_lt (le_csupr hbdd n) h) } }, { exact tendsto_of_not_nonempty hi } end lemma tendsto_at_top_supr {ι α : Type*} [preorder ι] [topological_space α] [complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_at_top_csupr h_mono (order_top.bdd_above _) lemma tendsto_of_monotone {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) : tendsto f at_top at_top ∨ (∃ l, tendsto f at_top (𝓝 l)) := if H : bdd_above (range f) then or.inr ⟨_, tendsto_at_top_csupr h_mono H⟩ else or.inl $ tendsto_at_top_at_top_of_monotone' h_mono H @[to_additive] lemma tendsto_inv_nhds_within_Ioi [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ioi a] a) (𝓝[Iio (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iio [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iio a] a) (𝓝[Ioi (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ioi (a⁻¹)] (a⁻¹)) (𝓝[Iio a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iio_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iio (a⁻¹)] (a⁻¹)) (𝓝[Ioi a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Ici [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ici a] a) (𝓝[Iic (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iic [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iic a] a) (𝓝[Ici (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ici_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ici (a⁻¹)] (a⁻¹)) (𝓝[Iic a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iic_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iic (a⁻¹)] (a⁻¹)) (𝓝[Ici a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹) lemma nhds_left_sup_nhds_right (a : α) [topological_space α] [linear_order α] : nhds_within a (Iic a) ⊔ nhds_within a (Ici a) = 𝓝 a := by rw [← nhds_within_union, Iic_union_Ici, nhds_within_univ] lemma nhds_left'_sup_nhds_right (a : α) [topological_space α] [linear_order α] : nhds_within a (Iio a) ⊔ nhds_within a (Ici a) = 𝓝 a := by rw [← nhds_within_union, Iio_union_Ici, nhds_within_univ] lemma nhds_left_sup_nhds_right' (a : α) [topological_space α] [linear_order α] : nhds_within a (Iic a) ⊔ nhds_within a (Ioi a) = 𝓝 a := by rw [← nhds_within_union, Iic_union_Ioi, nhds_within_univ] lemma continuous_at_iff_continuous_left_right [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_at f a ↔ continuous_within_at f (Iic a) a ∧ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, continuous_at, ← tendsto_sup, nhds_left_sup_nhds_right] lemma continuous_on_Icc_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {la lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) (hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Icc a b) := begin apply continuous_on_extend_from, { rw closure_Ioo hab, }, { intros x x_in, rcases mem_Ioo_or_eq_endpoints_of_mem_Icc x_in with rfl | rfl | h, { use la, simpa [hab] }, { use lb, simpa [hab] }, { use [f x, hf x h] } } end lemma eq_lim_at_left_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α} {la : β} (hab : a < b) (ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) : extend_from (Ioo a b) f a = la := begin apply extend_from_eq, { rw closure_Ioo hab, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma eq_lim_at_right_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α} {lb : β} (hab : a < b) (hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) : extend_from (Ioo a b) f b = lb := begin apply extend_from_eq, { rw closure_Ioo hab, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma continuous_on_Ico_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {la : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) : continuous_on (extend_from (Ioo a b) f) (Ico a b) := begin apply continuous_on_extend_from, { rw [closure_Ioo hab], exact Ico_subset_Icc_self, }, { intros x x_in, rcases mem_Ioo_or_eq_left_of_mem_Ico x_in with rfl | h, { use la, simpa [hab] }, { use [f x, hf x h] } } end lemma continuous_on_Ioc_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Ioc a b) := begin have := @continuous_on_Ico_extend_from_Ioo (order_dual α) _ _ _ _ _ _ _ f _ _ _ hab, erw [dual_Ico, dual_Ioi, dual_Ioo] at this, exact this hf hb end lemma continuous_within_at_Ioi_iff_Ici {α β : Type*} [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_within_at f (Ioi a) a ↔ continuous_within_at f (Ici a) a := begin split, { intros h s hs, specialize h hs, rw [mem_map, mem_nhds_within_iff_exists_mem_nhds_inter] at *, rcases h with ⟨u, huna, hu⟩, use [u, huna], { intros x hx, cases hx with hxu hx, by_cases h : x = a, { rw [h, mem_set_of_eq], exact mem_of_nhds hs, }, exact hu ⟨hxu, lt_of_le_of_ne hx (ne_comm.2 h)⟩ } }, { intros h, exact h.mono Ioi_subset_Ici_self } end lemma continuous_within_at_Iio_iff_Iic {α β : Type*} [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_within_at f (Iio a) a ↔ continuous_within_at f (Iic a) a := begin have := @continuous_within_at_Ioi_iff_Ici (order_dual α) _ _ _ _ _ f, erw [dual_Ici, dual_Ioi] at this, exact this, end lemma continuous_at_iff_continuous_left'_right' [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_at f a ↔ continuous_within_at f (Iio a) a ∧ continuous_within_at f (Ioi a) a := by rw [continuous_within_at_Ioi_iff_Ici, continuous_within_at_Iio_iff_Iic, continuous_at_iff_continuous_left_right] section homeomorphisms variables [topological_space α] [topological_space β] section linear_order variables [linear_order α] [order_topology α] variables [linear_order β] [order_topology β] /-- If `f : α → β` is strictly monotone and surjective, it is everywhere continuous. -/ lemma continuous_at_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) : continuous_at f a := continuous_at_iff_continuous_left_right.mpr ⟨continuous_left_of_strict_mono_surjective h_mono h_surj a, continuous_right_of_strict_mono_surjective h_mono h_surj a⟩ /-- If `f : α → β` is strictly monotone and surjective, it is continuous. -/ lemma continuous_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) : continuous f := continuous_iff_continuous_at.mpr (continuous_at_of_strict_mono_surjective h_mono h_surj) /-- If `f : α ≃ β` is strictly monotone, its inverse is continuous. -/ lemma continuous_inv_of_strict_mono_equiv (e : α ≃ β) (h_mono : strict_mono e.to_fun) : continuous e.inv_fun := begin have hinv_mono : strict_mono e.inv_fun, { intros x y hxy, rw [← h_mono.lt_iff_lt, e.right_inv, e.right_inv], exact hxy }, have hinv_surj : function.surjective e.inv_fun, { intros x, exact ⟨e.to_fun x, e.left_inv x⟩ }, exact continuous_of_strict_mono_surjective hinv_mono hinv_surj end /-- If `f : α → β` is strictly monotone and surjective, it is a homeomorphism. -/ noncomputable def homeomorph_of_strict_mono_surjective (f : α → β) (h_mono : strict_mono f) (h_surj : function.surjective f) : homeomorph α β := { to_equiv := equiv.of_bijective f ⟨strict_mono.injective h_mono, h_surj⟩, continuous_to_fun := continuous_of_strict_mono_surjective h_mono h_surj, continuous_inv_fun := continuous_inv_of_strict_mono_equiv (equiv.of_bijective f ⟨strict_mono.injective h_mono, h_surj⟩) h_mono } @[simp] lemma coe_homeomorph_of_strict_mono_surjective (f : α → β) (h_mono : strict_mono f) (h_surj : function.surjective f) : (homeomorph_of_strict_mono_surjective f h_mono h_surj : α → β) = f := rfl end linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [densely_ordered α] [order_topology α] variables [conditionally_complete_linear_order β] [order_topology β] /-- If `f : α → β` is strictly monotone and continuous, and tendsto `at_top` `at_top` and to `at_bot` `at_bot`, then it is a homeomorphism. -/ noncomputable def homeomorph_of_strict_mono_continuous (f : α → β) (h_mono : strict_mono f) (h_cont : continuous f) (h_top : tendsto f at_top at_top) (h_bot : tendsto f at_bot at_bot) : homeomorph α β := homeomorph_of_strict_mono_surjective f h_mono (surjective_of_continuous h_cont h_top h_bot) @[simp] lemma coe_homeomorph_of_strict_mono_continuous (f : α → β) (h_mono : strict_mono f) (h_cont : continuous f) (h_top : tendsto f at_top at_top) (h_bot : tendsto f at_bot at_bot) : (homeomorph_of_strict_mono_continuous f h_mono h_cont h_top h_bot : α → β) = f := rfl /- Now we prove a relative version of the above result. This (`Ioo` to `univ`) is provided as a sample; there are at least 16 possible variations with open intervals (`univ` to `Ioo`, `Ioi` to `univ`, ...), not to mention the possibilities with closed or half-closed intervals. -/ variables {a b : α} /-- If `f : α → β` is strictly monotone and continuous on the interval `Ioo a b` of `α`, and tends to `at_top` within `𝓝[Iio b] b` and to `at_bot` within `𝓝[Ioi a] a`, then it restricts to a homeomorphism from `Ioo a b` to `β`. -/ noncomputable def homeomorph_of_strict_mono_continuous_Ioo (f : α → β) (h : a < b) (h_mono : ∀ ⦃x y : α⦄, a < x → y < b → x < y → f x < f y) (h_cont : continuous_on f (Ioo a b)) (h_top : tendsto f (𝓝[Iio b] b) at_top) (h_bot : tendsto f (𝓝[Ioi a] a) at_bot) : homeomorph (Ioo a b) β := @homeomorph_of_strict_mono_continuous _ _ _ _ (@ord_connected_subset_conditionally_complete_linear_order α (Ioo a b) _ ⟨classical.choice (nonempty_Ioo_subtype h)⟩ _) _ _ _ _ (restrict f (Ioo a b)) (λ x y, h_mono x.2.1 y.2.2) (continuous_on_iff_continuous_restrict.mp h_cont) begin rw [restrict_eq f (Ioo a b), Ioo_at_top_eq_nhds_within h], exact h_top.comp tendsto_comap end begin rw [restrict_eq f (Ioo a b), Ioo_at_bot_eq_nhds_within h], exact h_bot.comp tendsto_comap end @[simp] lemma coe_homeomorph_of_strict_mono_continuous_Ioo (f : α → β) (h : a < b) (h_mono : ∀ ⦃x y : α⦄, a < x → y < b → x < y → f x < f y) (h_cont : continuous_on f (Ioo a b)) (h_top : tendsto f (𝓝[Iio b] b) at_top) (h_bot : tendsto f (𝓝[Ioi a] a) at_bot) : (homeomorph_of_strict_mono_continuous_Ioo f h h_mono h_cont h_top h_bot : Ioo a b → β) = restrict f (Ioo a b) := rfl end conditionally_complete_linear_order end homeomorphisms
ad050810f24cbb2c23501cbfcefefe2886da85e8
dc253be9829b840f15d96d986e0c13520b085033
/colimit/seq_colim.hlean
84de093863c7df9dd8f15d09644687992f2d0bea
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
37,716
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, Egbert Rijke -/ import hit.colimit .sequence cubical.squareover types.arrow types.equiv cubical.pathover2 open eq nat sigma sigma.ops quotient equiv pi is_trunc is_equiv fiber function trunc namespace seq_colim -- note: this clashes with the abbreviation defined in namespace "colimit" abbreviation ι [constructor] := @inclusion abbreviation ι' [constructor] [parsing_only] {A} (f n) := @inclusion A f n universe variable v variables {A A' A'' : ℕ → Type} (f : seq_diagram A) (f' : seq_diagram A') (f'' : seq_diagram A'') (τ τ₂ : Π⦃n⦄, A n → A' n) (p : Π⦃n⦄ (a : A n), τ (f a) = f' (τ a)) (p₂ : Π⦃n⦄ (a : A n), τ₂ (f a) = f' (τ₂ a)) (τ' : Π⦃n⦄, A' n → A'' n) (p' : Π⦃n⦄ (a' : A' n), τ' (f' a') = f'' (τ' a')) {P : Π⦃n⦄, A n → Type.{v}} (g : seq_diagram_over f P) {n : ℕ} {a : A n} definition lrep_glue {n m : ℕ} (H : n ≤ m) (a : A n) : ι f (lrep f H a) = ι f a := begin induction H with m H p, { reflexivity }, { exact glue f (lrep f H a) ⬝ p } end definition colim_back [unfold 4] [H : is_equiseq f] : seq_colim f → A 0 := begin intro x, induction x with k a k a, { exact lrep_back f (zero_le k) a}, rexact ap (lrep_back f (zero_le k)) (left_inv (@f k) a), end section variable {f} local attribute is_equiv_lrep [instance] --[priority 500] definition is_equiv_inclusion0 (H : is_equiseq f) : is_equiv (ι' f 0) := begin fapply adjointify, { exact colim_back f}, { intro x, induction x with k a k a, { refine (lrep_glue f (zero_le k) (lrep_back f (zero_le k) a))⁻¹ ⬝ _, exact ap (ι f) (right_inv (lrep f (zero_le k)) a)}, apply eq_pathover_id_right, refine (ap_compose (ι f) (colim_back f) _) ⬝ph _, refine ap02 _ _ ⬝ph _, rotate 1, { rexact elim_glue f _ _ a }, refine _ ⬝pv ((natural_square (lrep_glue f (zero_le k)) (ap (lrep_back f (zero_le k)) (left_inv (@f k) a)))⁻¹ʰ ⬝h _), { exact (glue f _)⁻¹ ⬝ ap (ι f) (right_inv (lrep f (zero_le (succ k))) (f a)) }, { rewrite [-con.assoc, -con_inv] }, refine !ap_compose⁻¹ ⬝ ap_compose (ι f) _ _ ⬝ph _, refine dconcat (aps (ι' f k) (natural_square (right_inv (lrep f (zero_le k))) (left_inv (@f _) a))) _, apply move_top_of_left, apply move_left_of_bot, refine ap02 _ (whisker_left _ (adj (@f _) a)) ⬝pv _, rewrite [-+ap_con, ap_compose', ap_id], apply natural_square_tr }, { intro a, reflexivity } end definition equiv_of_is_equiseq [constructor] (H : is_equiseq f) : seq_colim f ≃ A 0 := (equiv.mk _ (is_equiv_inclusion0 H))⁻¹ᵉ variable (f) end section definition rep_glue (k : ℕ) (a : A n) : ι f (rep f k a) = ι f a := begin induction k with k IH, { reflexivity}, { exact glue f (rep f k a) ⬝ IH} end /- functorial action and equivalences -/ section functor variables {f f' f''} include p definition seq_colim_functor [unfold 7] : seq_colim f → seq_colim f' := begin intro x, induction x with n a n a, { exact ι f' (τ a)}, { exact ap (ι f') (p a) ⬝ glue f' (τ a)} end omit p theorem seq_colim_functor_glue {n : ℕ} (a : A n) : ap (seq_colim_functor τ p) (glue f a) = ap (ι f') (p a) ⬝ glue f' (τ a) := !elim_glue definition seq_colim_functor_compose [constructor] (x : seq_colim f) : seq_colim_functor (λn x, τ' (τ x)) (λn, hvconcat (@p n) (@p' n)) x = seq_colim_functor τ' p' (seq_colim_functor τ p x) := begin induction x, reflexivity, apply eq_pathover, apply hdeg_square, refine !seq_colim_functor_glue ⬝ _ ⬝ (ap_compose (seq_colim_functor _ _) _ _)⁻¹, refine _ ⬝ (ap02 _ proof !seq_colim_functor_glue qed ⬝ !ap_con)⁻¹, refine _ ⬝ (proof !ap_compose' ⬝ ap_compose (ι f'') _ _ qed ◾ proof !seq_colim_functor_glue qed)⁻¹, exact whisker_right _ !ap_con ⬝ !con.assoc end variable (f) definition seq_colim_functor_id [constructor] (x : seq_colim f) : seq_colim_functor (λn, id) (λn, homotopy.rfl) x = x := begin induction x, reflexivity, apply eq_pathover, apply hdeg_square, exact !seq_colim_functor_glue ⬝ !idp_con ⬝ !ap_id⁻¹, end variables {f τ τ₂ p p₂} definition seq_colim_functor_homotopy [constructor] (q : τ ~2 τ₂) (r : Π⦃n⦄ (a : A n), square (q (n+1) (f a)) (ap (@f' n) (q n a)) (p a) (p₂ a)) (x : seq_colim f) : seq_colim_functor τ p x = seq_colim_functor τ₂ p₂ x := begin induction x, exact ap (ι f') (q n a), apply eq_pathover, refine !seq_colim_functor_glue ⬝ph _ ⬝hp !seq_colim_functor_glue⁻¹, refine aps (ι f') (r a) ⬝v !ap_compose⁻¹ ⬝pv natural_square_tr (glue f') (q n a), end variables (τ τ₂ p p₂) definition is_equiv_seq_colim_functor [constructor] [H : Πn, is_equiv (@τ n)] : is_equiv (seq_colim_functor @τ p) := adjointify _ (seq_colim_functor (λn, (@τ _)⁻¹) (λn a, inv_commute' τ f f' p a)) abstract begin intro x, refine !seq_colim_functor_compose⁻¹ ⬝ seq_colim_functor_homotopy _ _ x ⬝ !seq_colim_functor_id, { intro n a, exact right_inv (@τ n) a }, { intro n a, refine whisker_right _ !ap_inv_commute' ⬝ !inv_con_cancel_right ⬝ whisker_left _ !ap_inv ⬝ph _, apply whisker_bl, apply whisker_tl, exact ids } end end abstract begin intro x, refine !seq_colim_functor_compose⁻¹ ⬝ seq_colim_functor_homotopy _ _ x ⬝ !seq_colim_functor_id, { intro n a, exact left_inv (@τ n) a }, { intro n a, esimp [hvconcat], refine whisker_left _ (!inv_commute'_fn ⬝ !con.assoc) ⬝ !con_inv_cancel_left ⬝ph _, apply whisker_bl, apply whisker_tl, exact ids } end end definition seq_colim_equiv [constructor] (τ : Π{n}, A n ≃ A' n) (p : Π⦃n⦄ (a : A n), τ (f a) = f' (τ a)) : seq_colim f ≃ seq_colim f' := equiv.mk _ (is_equiv_seq_colim_functor @τ p) definition seq_colim_rec_unc [unfold 4] {P : seq_colim f → Type} (v : Σ(Pincl : Π ⦃n : ℕ⦄ (a : A n), P (ι f a)), Π ⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue f a] Pincl a) : Π(x : seq_colim f), P x := by induction v with Pincl Pglue; exact seq_colim.rec f Pincl Pglue definition is_equiv_seq_colim_rec (P : seq_colim f → Type) : is_equiv (seq_colim_rec_unc : (Σ(Pincl : Π ⦃n : ℕ⦄ (a : A n), P (ι f a)), Π ⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue f a] Pincl a) → (Π (aa : seq_colim f), P aa)) := begin fapply adjointify, { intro s, exact ⟨λn a, s (ι f a), λn a, apd s (glue f a)⟩}, { intro s, apply eq_of_homotopy, intro x, induction x, { reflexivity}, { apply eq_pathover_dep, esimp, apply hdeg_squareover, apply rec_glue}}, { intro v, induction v with Pincl Pglue, fapply ap (sigma.mk _), apply eq_of_homotopy2, intros n a, apply rec_glue}, end /- universal property -/ definition equiv_seq_colim_rec (P : seq_colim f → Type) : (Σ(Pincl : Π ⦃n : ℕ⦄ (a : A n), P (ι f a)), Π ⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue f a] Pincl a) ≃ (Π (aa : seq_colim f), P aa) := equiv.mk _ !is_equiv_seq_colim_rec end functor definition shift_up [unfold 3] (x : seq_colim f) : seq_colim (shift_diag f) := begin induction x, { exact ι' (shift_diag f) n (f a)}, { exact glue (shift_diag f) (f a)} end definition shift_down [unfold 3] (x : seq_colim (shift_diag f)) : seq_colim f := begin induction x, { exact ι' f (n+1) a}, { exact glue f a} end end definition shift_equiv [constructor] : seq_colim f ≃ seq_colim (shift_diag f) := equiv.MK (shift_up f) (shift_down f) abstract begin intro x, induction x, { exact glue _ a }, { apply eq_pathover, rewrite [▸*, ap_id, ap_compose (shift_up f) (shift_down f), ↑shift_down, elim_glue], apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹ } end end abstract begin intro x, induction x, { exact glue _ a }, { apply eq_pathover, rewrite [▸*, ap_id, ap_compose (shift_down f) (shift_up f), ↑shift_up, elim_glue], apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹ } end end /- todo: define functions back and forth explicitly -/ definition kshift'_equiv (k : ℕ) : seq_colim f ≃ seq_colim (kshift_diag' f k) := begin induction k with k IH, { reflexivity }, { exact IH ⬝e shift_equiv (kshift_diag' f k) ⬝e seq_colim_equiv (λn, equiv_ap A (succ_add n k)) (λn a, proof !tr_inv_tr ⬝ !transport_lemma⁻¹ qed) } end definition kshift_equiv_inv (k : ℕ) : seq_colim (kshift_diag f k) ≃ seq_colim f := begin induction k with k IH, { exact seq_colim_equiv (λn, equiv_ap A (nat.zero_add n)) (λn a, !transport_lemma2) }, { exact seq_colim_equiv (λn, equiv_ap A (succ_add k n)) (λn a, transport_lemma2 (succ_add k n) f a) ⬝e (shift_equiv (kshift_diag f k))⁻¹ᵉ ⬝e IH } end definition kshift_equiv [constructor] (k : ℕ) : seq_colim f ≃ seq_colim (kshift_diag f k) := (kshift_equiv_inv f k)⁻¹ᵉ -- definition kshift_equiv2 [constructor] (k : ℕ) : seq_colim f ≃ seq_colim (kshift_diag f k) := -- begin -- refine equiv_change_fun (kshift_equiv f k) _, -- end variable {f} definition seq_colim_constant_seq [constructor] (X : Type) : seq_colim (constant_seq X) ≃ X := equiv_of_is_equiseq (λn, !is_equiv_id) variable (f) definition is_contr_seq_colim {A : ℕ → Type} (f : seq_diagram A) [Πk, is_contr (A k)] : is_contr (seq_colim f) := begin refine is_contr_is_equiv_closed (ι' f 0) _ _, apply is_equiv_inclusion0, intro n, exact is_equiv_of_is_contr _ _ _ end definition seq_colim_equiv_of_is_equiv [constructor] {n : ℕ} (H : Πk, k ≥ n → is_equiv (@f k)) : seq_colim f ≃ A n := kshift_equiv f n ⬝e equiv_of_is_equiseq (λk, H (n+k) !le_add_right) /- colimits of dependent sequences, sigma's commute with colimits -/ section over variable {f} definition rep_f_equiv_natural {k : ℕ} (p : P (rep f k (f a))) : transporto P (rep_f f (succ k) a) (g p) = g (transporto P (rep_f f k a) p) := (fn_tro_eq_tro_fn2 (rep_f f k a) g p)⁻¹ variable (a) definition over_f_equiv [constructor] : seq_colim (seq_diagram_of_over g (f a)) ≃ seq_colim (shift_diag (seq_diagram_of_over g a)) := seq_colim_equiv (rep_f_equiv f P a) (λk p, rep_f_equiv_natural g p) definition seq_colim_over_equiv : seq_colim (seq_diagram_of_over g (f a)) ≃ seq_colim (seq_diagram_of_over g a) := over_f_equiv g a ⬝e (shift_equiv (seq_diagram_of_over g a))⁻¹ᵉ definition seq_colim_over_equiv_glue {k : ℕ} (x : P (rep f k (f a))) : ap (seq_colim_over_equiv g a) (glue (seq_diagram_of_over g (f a)) x) = ap (ι' (seq_diagram_of_over g a) (k+2)) (rep_f_equiv_natural g x) ⬝ glue (seq_diagram_of_over g a) (rep_f f k a ▸o x) := begin refine ap_compose (shift_down (seq_diagram_of_over g a)) _ _ ⬝ _, exact ap02 _ !elim_glue ⬝ !ap_con ⬝ !ap_compose' ◾ !elim_glue end variable {a} include g definition seq_colim_over [unfold 5] (x : seq_colim f) : Type.{v} := begin refine seq_colim.elim_type f _ _ x, { intro n a, exact seq_colim (seq_diagram_of_over g a)}, { intro n a, exact seq_colim_over_equiv g a } end omit g definition ιo [constructor] (p : P a) : seq_colim_over g (ι f a) := ι' _ 0 p variable {P} theorem seq_colim_over_glue /- r -/ (x : seq_colim_over g (ι f (f a))) : transport (seq_colim_over g) (glue f a) x = shift_down _ (over_f_equiv g a x) := ap10 (elim_type_glue _ _ _ a) x theorem seq_colim_over_glue_inv (x : seq_colim_over g (ι f a)) : transport (seq_colim_over g) (glue f a)⁻¹ x = to_inv (over_f_equiv g a) (shift_up _ x) := ap10 (elim_type_glue_inv _ _ _ a) x definition glue_over (p : P (f a)) : pathover (seq_colim_over g) (ιo g p) (glue f a) (ι' _ 1 p) := pathover_of_tr_eq !seq_colim_over_glue -- we can define a function from the colimit of total spaces to the total space of the colimit. definition glue' (p : P a) : ⟨ι f (f a), ιo g (g p)⟩ = ⟨ι f a, ιo g p⟩ := sigma_eq (glue f a) (glue_over g (g p) ⬝op glue (seq_diagram_of_over g a) p) definition glue_star (k : ℕ) (x : P (rep f k (f a))) : ⟨ι f (f a), ι (seq_diagram_of_over g (f a)) x⟩ = ⟨ι f a, ι (seq_diagram_of_over g a) (to_fun (rep_f_equiv f P a k) x)⟩ :> sigma (seq_colim_over g) := begin apply dpair_eq_dpair (glue f a), apply pathover_of_tr_eq, refine seq_colim_over_glue g (ι (seq_diagram_of_over g (f a)) x) end definition sigma_colim_of_colim_sigma [unfold 5] (a : seq_colim (seq_diagram_sigma g)) : Σ(x : seq_colim f), seq_colim_over g x := begin induction a with n v n v, { induction v with a p, exact ⟨ι f a, ιo g p⟩}, { induction v with a p, exact glue' g p } end definition colim_sigma_triangle [unfold 5] (a : seq_colim (seq_diagram_sigma g)) : (sigma_colim_of_colim_sigma g a).1 = seq_colim_functor (λn, sigma.pr1) (λn, homotopy.rfl) a := begin induction a with n v n v, { induction v with a p, reflexivity }, { induction v with a p, apply eq_pathover, apply hdeg_square, refine ap_compose sigma.pr1 _ _ ⬝ ap02 _ !elim_glue ⬝ _ ⬝ !elim_glue⁻¹, exact !sigma_eq_pr1 ⬝ !idp_con⁻¹ } end -- we now want to show that this function is an equivalence. /- Proof of the induction principle of colim-sigma for sigma-colim. It's a double induction, so we have 4 cases: point-point, point-path, path-point and path-path. The main idea of the proof is that for the path-path case you need to fill a square, but we can define the point-path case as a filler for this square. -/ open sigma /- dictionary: Kristina | Lean VARIABLE NAMES (A, P, k, n, e, w are the same) x : A_n | a : A n a : A_n → A_{n+1} | f : A n → A (n+1) y : P(n, x) | x : P a (maybe other variables) f : P(n, x) → P(n+1, a_n x) | g : P a → P (f a) DEFINITION NAMES κ | glue U | rep_f_equiv : P (n+1+k, rep f k (f x)) ≃ P (n+k+1, rep f (k+1) x) δ | rep_f_equiv_natural F | over_f_equiv g a ⬝e (shift_equiv (λk, P (rep f k a)) (seq_diagram_of_over g a))⁻¹ᵉ g_* | g_star g | sigma_colim_rec_point -/ definition glue_star_eq (k : ℕ) (x : P (rep f k (f a))) : glue_star g k x = dpair_eq_dpair (glue f a) (pathover_tr (glue f a) (ι (seq_diagram_of_over g (f a)) x)) ⬝ ap (dpair (ι f a)) (seq_colim_over_glue g (ι (seq_diagram_of_over g (f a)) x)) := ap (sigma_eq _) !pathover_of_tr_eq_eq_concato ⬝ !sigma_eq_con ⬝ whisker_left _ !ap_dpair⁻¹ definition g_star_step {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Πn (a : A n) (x : P a), E ⟨ι f a, ιo g x⟩) {k : ℕ} (IH : Π{n} {a : A n} (x : P (rep f k a)), E ⟨ι f a, ι (seq_diagram_of_over g a) x⟩) : Σ(gs : Π⦃n : ℕ⦄ {a : A n} (x : P (rep f (k+1) a)), E ⟨ι f a, ι (seq_diagram_of_over g a) x⟩), Π⦃n : ℕ⦄ {a : A n} (x : P (rep f k (f a))), pathover E (IH x) (glue_star g k x) (gs (transporto P (rep_f f k a) x)) := begin fconstructor, { intro n a, refine equiv_rect (rep_f_equiv f P a k) _ _, intro z, refine transport E _ (IH z), exact glue_star g k z }, { intro n a x, exact !pathover_tr ⬝op !equiv_rect_comp⁻¹ } end definition g_star /- g_* -/ {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Πn (a : A n) (x : P a), E ⟨ι f a, ιo g x⟩) {k : ℕ} : Π {n : ℕ} {a : A n} (x : P (rep f k a)), E ⟨ι f a, ι (seq_diagram_of_over g a) x⟩ := begin induction k with k IH: intro n a x, { exact e n a x }, { apply (g_star_step g e @IH).1 } end definition g_star_path_left {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) {k : ℕ} {n : ℕ} {a : A n} (x : P (rep f k (f a))) : pathover E (g_star g e x) (glue_star g k x) (g_star g e (transporto P (rep_f f k a) x)) := by apply (g_star_step g e (@(g_star g e) k)).2 /- this is the bottom of the square we have to fill in the end -/ definition bottom_square {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) (k : ℕ) {n : ℕ} {a : A n} (x : P (rep f k (f a))) := move_top_of_right (natural_square (λ b, dpair_eq_dpair (glue f a) (pathover_tr (glue f a) b) ⬝ ap (dpair (ι f a)) (seq_colim_over_glue g b)) (glue (seq_diagram_of_over g (f a)) x) ⬝hp ap_compose (dpair (ι f a)) (to_fun (seq_colim_over_equiv g a)) (glue (seq_diagram_of_over g (f a)) x) ⬝hp (ap02 (dpair (ι f a)) (seq_colim_over_equiv_glue g a x)⁻¹)⁻¹ ⬝hp ap_con (dpair (ι f a)) (ap (λx, shift_down (seq_diagram_of_over g a) (ι (shift_diag (seq_diagram_of_over g a)) x)) (rep_f_equiv_natural g x)) (glue (seq_diagram_of_over g a) (to_fun (rep_f_equiv f P a k) x))) /- this is the composition + filler -/ definition g_star_path_right_step {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) (k : ℕ) {n : ℕ} {a : A n} (x : P (rep f k (f a))) (IH : Π(n : ℕ) (a : A n) (x : P (rep f k a)), pathover E (g_star g e (seq_diagram_of_over g a x)) (ap (dpair (ι f a)) (glue (seq_diagram_of_over g a) x)) (g_star g e x)) := squareover_fill_r (bottom_square g e w k x) (change_path (glue_star_eq g (succ k) (g x)) (g_star_path_left g e w (g x)) ⬝o pathover_ap E (dpair (ι f a)) (pathover_ap (λ (b : seq_colim (seq_diagram_of_over g a)), E ⟨ι f a, b⟩) (ι (seq_diagram_of_over g a)) (apd (g_star g e) (rep_f_equiv_natural g x)))) (change_path (glue_star_eq g k x) (g_star_path_left g e w x)) (IH (n+1) (f a) x) /- this is just the composition -/ definition g_star_path_right_step1 {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) (k : ℕ) {n : ℕ} {a : A n} (x : P (rep f k (f a))) (IH : Π(n : ℕ) (a : A n) (x : P (rep f k a)), pathover E (g_star g e (seq_diagram_of_over g a x)) (ap (dpair (ι f a)) (glue (seq_diagram_of_over g a) x)) (g_star g e x)) := (g_star_path_right_step g e w k x IH).1 definition g_star_path_right {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) (k : ℕ) {n : ℕ} {a : A n} (x : P (rep f k a)) : pathover E (g_star g e (seq_diagram_of_over g a x)) (ap (dpair (ι f a)) (glue (seq_diagram_of_over g a) x)) (g_star g e x) := begin revert n a x, induction k with k IH: intro n a x, { exact abstract begin refine pathover_cancel_left !pathover_tr⁻¹ᵒ (change_path _ (w x)), apply sigma_eq_concato_eq end end }, { revert x, refine equiv_rect (rep_f_equiv f P a k) _ _, intro x, exact g_star_path_right_step1 g e w k x IH } end definition sigma_colim_rec_point [unfold 10] /- g -/ {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) {n : ℕ} {a : A n} (x : seq_colim_over g (ι f a)) : E ⟨ι f a, x⟩ := begin induction x with k x k x, { exact g_star g e x }, { apply pathover_of_pathover_ap E (dpair (ι f a)), exact g_star_path_right g e w k x } end definition sigma_colim_rec {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) (v : Σ(x : seq_colim f), seq_colim_over g x) : E v := begin induction v with x y, induction x with n a n a, { exact sigma_colim_rec_point g e w y }, { apply pi_pathover_left, intro x, refine change_path (whisker_left _ !ap_inv ⬝ !con_inv_cancel_right) (_ ⬝o pathover_ap E (dpair _) (apd (sigma_colim_rec_point g e w) !seq_colim_over_glue⁻¹)), /- we can simplify the squareover we need to fill a bit if we apply this rule here -/ -- refine change_path (ap (sigma_eq (glue f a)) !pathover_of_tr_eq_eq_concato ⬝ !sigma_eq_con ⬝ whisker_left _ !ap_dpair⁻¹) _, induction x with k x k x, { exact change_path !glue_star_eq (g_star_path_left g e w x) }, -- { exact g_star_path_left g e w x }, { apply pathover_pathover, esimp, refine _ ⬝hop (ap (pathover_ap E _) (apd_compose2 (sigma_colim_rec_point g e w) _ _) ⬝ pathover_ap_pathover_of_pathover_ap E (dpair (ι f a)) (seq_colim_over_equiv g a) _)⁻¹, apply squareover_change_path_right', refine _ ⬝hop !pathover_ap_change_path⁻¹ ⬝ ap (pathover_ap E _) (apd02 _ !seq_colim_over_equiv_glue⁻¹), apply squareover_change_path_right, refine _ ⬝hop (ap (pathover_ap E _) (!apd_con ⬝ (!apd_ap ◾o idp)) ⬝ !pathover_ap_cono)⁻¹, apply squareover_change_path_right', apply move_right_of_top_over, refine _ ⬝hop (ap (pathover_ap E _) !rec_glue ⬝ to_right_inv !pathover_compose _)⁻¹, refine ap (pathover_ap E _) !rec_glue ⬝ to_right_inv !pathover_compose _ ⬝pho _, refine _ ⬝hop !equiv_rect_comp⁻¹, exact (g_star_path_right_step g e w k x @(g_star_path_right g e w k)).2 }} end /- We now define the map back, and show using this induction principle that the composites are the identity -/ variable {P} definition colim_sigma_of_sigma_colim_constructor [unfold 7] (p : seq_colim_over g (ι f a)) : seq_colim (seq_diagram_sigma g) := begin induction p with k p k p, { exact ι _ ⟨rep f k a, p⟩}, { apply glue} end definition colim_sigma_of_sigma_colim_path1 /- μ -/ {k : ℕ} (p : P (rep f k (f a))) : ι (seq_diagram_sigma g) ⟨rep f k (f a), p⟩ = ι (seq_diagram_sigma g) ⟨rep f (succ k) a, transporto P (rep_f f k a) p⟩ := begin apply apd0111 (λn a p, ι' (seq_diagram_sigma g) n ⟨a, p⟩) (succ_add n k) (rep_f f k a), apply pathover_tro end definition colim_sigma_of_sigma_colim_path2 {k : ℕ} (p : P (rep f k (f a))) : square (colim_sigma_of_sigma_colim_path1 g (g p)) (colim_sigma_of_sigma_colim_path1 g p) (ap (colim_sigma_of_sigma_colim_constructor g) (glue (seq_diagram_of_over g (f a)) p)) (ap (λx, colim_sigma_of_sigma_colim_constructor g (shift_down (seq_diagram_of_over g a) (seq_colim_functor (λk, transporto P (rep_f f k a)) (λk p, rep_f_equiv_natural g p) x))) (glue (seq_diagram_of_over g (f a)) p)) := begin refine !elim_glue ⬝ph _, refine _ ⬝hp (ap_compose' (colim_sigma_of_sigma_colim_constructor g) _ _), refine _ ⬝hp ap02 _ !seq_colim_over_equiv_glue⁻¹, refine _ ⬝hp !ap_con⁻¹, refine _ ⬝hp !ap_compose ◾ !elim_glue⁻¹, refine _ ⬝pv whisker_rt _ (natural_square0111 P (pathover_tro (rep_f f k a) p) g (λn a p, glue (seq_diagram_sigma g) ⟨a, p⟩)), refine _ ⬝ whisker_left _ (ap02 _ !inv_inv⁻¹ ⬝ !ap_inv), symmetry, apply apd0111_precompose end definition colim_sigma_of_sigma_colim [unfold 5] (v : Σ(x : seq_colim f), seq_colim_over g x) : seq_colim (seq_diagram_sigma g) := begin induction v with x p, induction x with n a n a, { exact colim_sigma_of_sigma_colim_constructor g p }, apply arrow_pathover_constant_right, intro x, esimp at x, refine _ ⬝ ap (colim_sigma_of_sigma_colim_constructor g) !seq_colim_over_glue⁻¹, induction x with k p k p, { exact colim_sigma_of_sigma_colim_path1 g p }, apply eq_pathover, apply colim_sigma_of_sigma_colim_path2 end definition colim_sigma_of_sigma_colim_glue' [unfold 5] (p : P a) : ap (colim_sigma_of_sigma_colim g) (glue' g p) = glue (seq_diagram_sigma g) ⟨a, p⟩ := begin refine !ap_dpair_eq_dpair ⬝ _, refine !apd011_eq_apo11_apd ⬝ _, refine ap (λx, apo11_constant_right x _) !rec_glue ⬝ _, refine !apo11_arrow_pathover_constant_right ⬝ _, esimp, refine whisker_right _ !idp_con ⬝ _, rewrite [▸*, tr_eq_of_pathover_concato_eq, ap_con, ↑glue_over, to_right_inv !pathover_equiv_tr_eq, ap_inv, inv_con_cancel_left], apply elim_glue end theorem colim_sigma_of_sigma_colim_of_colim_sigma (a : seq_colim (seq_diagram_sigma g)) : colim_sigma_of_sigma_colim g (sigma_colim_of_colim_sigma g a) = a := begin induction a with n v n v, { induction v with a p, reflexivity }, { induction v with a p, esimp, apply eq_pathover_id_right, apply hdeg_square, refine ap_compose (colim_sigma_of_sigma_colim g) _ _ ⬝ _, refine ap02 _ !elim_glue ⬝ _, exact colim_sigma_of_sigma_colim_glue' g p } end theorem sigma_colim_of_colim_sigma_of_sigma_colim (v : Σ(x : seq_colim f), seq_colim_over g x) : sigma_colim_of_colim_sigma g (colim_sigma_of_sigma_colim g v) = v := begin revert v, refine sigma_colim_rec _ _ _, { intro n a x, reflexivity }, { intro n a x, apply eq_pathover_id_right, apply hdeg_square, refine ap_compose (sigma_colim_of_colim_sigma g) _ _ ⬝ _, refine ap02 _ (colim_sigma_of_sigma_colim_glue' g x) ⬝ _, apply elim_glue } end variable (P) definition sigma_seq_colim_over_equiv [constructor] : (Σ(x : seq_colim f), seq_colim_over g x) ≃ seq_colim (seq_diagram_sigma g) := equiv.MK (colim_sigma_of_sigma_colim g) (sigma_colim_of_colim_sigma g) (colim_sigma_of_sigma_colim_of_colim_sigma g) (sigma_colim_of_colim_sigma_of_sigma_colim g) end over definition seq_colim_id_equiv_seq_colim_id0 (a₀ a₁ : A 0) : seq_colim (id_seq_diagram f 0 a₀ a₁) ≃ seq_colim (id0_seq_diagram f a₀ a₁) := seq_colim_equiv (λn, !lrep_eq_lrep_irrel (nat.zero_add n)) (λn p, !lrep_eq_lrep_irrel_natural) definition kshift_equiv_inv_incl_kshift_diag {n k : ℕ} (x : A (n + k)) : kshift_equiv_inv f n (ι' (kshift_diag f n) k x) = ι f x := begin revert A f k x, induction n with n IH: intro A f k x, { exact apd011 (ι' f) !nat.zero_add⁻¹ !pathover_tr⁻¹ᵒ }, { exact !IH ⬝ apd011 (ι' f) !succ_add⁻¹ !pathover_tr⁻¹ᵒ } end definition incl_kshift_diag {n k : ℕ} (x : A (n + k)) : ι' (kshift_diag f n) k x = kshift_equiv f n (ι f x) := eq_inv_of_eq (kshift_equiv_inv_incl_kshift_diag f x) definition incl_kshift_diag0 {n : ℕ} (x : A n) : ι' (kshift_diag f n) 0 x = kshift_equiv f n (ι f x) := incl_kshift_diag f x definition seq_colim_eq_equiv0' (a₀ a₁ : A 0) : ι f a₀ = ι f a₁ ≃ seq_colim (id_seq_diagram f 0 a₀ a₁) := begin refine total_space_method (ι f a₀) (seq_colim_over (id0_seq_diagram_over f a₀)) _ _ (ι f a₁) ⬝e _, { apply @(is_trunc_equiv_closed_rev _ (sigma_seq_colim_over_equiv _ _)), apply is_contr_seq_colim }, { exact ιo _ idp }, /- In the next equivalence we have to show that seq_colim_over (id0_seq_diagram_over f a₀) (ι f a₁) ≃ seq_colim (id_seq_diagram f 0 a₀ a₁). This looks trivial, because both of them reduce to seq_colim (f^{0 ≤ 0+k}(a₀) = f^{0 ≤ 0+k}(a₁), ap_f). However, not all proofs of these inequalities are definitionally equal. 3 of them are proven by zero_le : 0 ≤ n, but one of them (the RHS of seq_colim_over (id0_seq_diagram_over f a₀) (ι f a₁)) uses le_add_right : n ≤ n+k Alternatively, we could redefine le_add_right so that for n=0, it reduces to `zero_le (0+k)`. -/ { refine seq_colim_equiv (λn, eq_equiv_eq_closed !lrep_irrel idp) _, intro n p, refine whisker_right _ (!lrep_irrel2⁻² ⬝ !ap_inv⁻¹) ⬝ !ap_con⁻¹ } end -- definition seq_colim_eq_equiv0'_natural {a₀ a₁ : A 0} {a₀' a₁' : A' 0} (p₀ : τ a₀ = a₀') -- (p₁ : τ a₁ = a₁') : -- hsquare (seq_colim_eq_equiv0' f a₀ a₁) (seq_colim_eq_equiv0' f' a₀' a₁') -- (pointed.ap1_gen (seq_colim_functor τ p) (ap (ι' f' 0) p₀) (ap (ι' f' 0) p₁)) -- (seq_colim_functor (λn, pointed.ap1_gen (@τ _)) _) := -- _ definition seq_colim_eq_equiv0 (a₀ a₁ : A 0) : ι f a₀ = ι f a₁ ≃ seq_colim (id0_seq_diagram f a₀ a₁) := seq_colim_eq_equiv0' f a₀ a₁ ⬝e seq_colim_id_equiv_seq_colim_id0 f a₀ a₁ definition seq_colim_eq_equiv {n : ℕ} (a₀ a₁ : A n) : ι f a₀ = ι f a₁ ≃ seq_colim (id_seq_diagram f n a₀ a₁) := eq_equiv_fn_eq (kshift_equiv f n) (ι f a₀) (ι f a₁) ⬝e eq_equiv_eq_closed (incl_kshift_diag0 f a₀)⁻¹ (incl_kshift_diag0 f a₁)⁻¹ ⬝e seq_colim_eq_equiv0' (kshift_diag f n) a₀ a₁ ⬝e @seq_colim_equiv _ _ _ (λk, ap (@f _)) (λm, eq_equiv_eq_closed !lrep_kshift_diag !lrep_kshift_diag) (λm p, whisker_right _ (whisker_right _ !ap_inv⁻¹ ⬝ !ap_con⁻¹) ⬝ !ap_con⁻¹) ⬝e seq_colim_equiv (λm, !lrep_eq_lrep_irrel (ap (add n) (nat.zero_add m))) begin intro m q, refine _ ⬝ lrep_eq_lrep_irrel_natural f (le_add_right n m) (ap (add n) (nat.zero_add m)) q, exact ap (λx, lrep_eq_lrep_irrel f _ _ _ _ x _) !is_prop.elim end open algebra theorem is_trunc_seq_colim [instance] (k : ℕ₋₂) [H : Πn, is_trunc k (A n)] : is_trunc k (seq_colim f) := begin revert A f H, induction k with k IH: intro A f H, { apply is_contr_seq_colim }, { apply is_trunc_succ_intro, intro x y, induction x using seq_colim.rec_prop with n a, induction y using seq_colim.rec_prop with m a', apply is_trunc_equiv_closed, exact eq_equiv_eq_closed (lrep_glue _ (le_max_left n m) _) (lrep_glue _ (le_max_right n m) _), apply is_trunc_equiv_closed_rev, apply seq_colim_eq_equiv, apply IH, intro l, apply is_trunc_eq } end definition seq_colim_trunc_of_trunc_seq_colim [unfold 4] (k : ℕ₋₂) (x : trunc k (seq_colim f)) : seq_colim (trunc_diagram k f) := begin induction x with x, exact seq_colim_functor (λn, tr) (λn y, idp) x end definition trunc_seq_colim_of_seq_colim_trunc [unfold 4] (k : ℕ₋₂) (x : seq_colim (trunc_diagram k f)) : trunc k (seq_colim f) := begin induction x with n x n x, { induction x with a, exact tr (ι f a) }, { induction x with a, exact ap tr (glue f a) } end definition trunc_seq_colim_equiv [constructor] (k : ℕ₋₂) : trunc k (seq_colim f) ≃ seq_colim (trunc_diagram k f) := equiv.MK (seq_colim_trunc_of_trunc_seq_colim f k) (trunc_seq_colim_of_seq_colim_trunc f k) abstract begin intro x, induction x with n x n x, { induction x with a, reflexivity }, { induction x with a, apply eq_pathover_id_right, apply hdeg_square, refine ap_compose (seq_colim_trunc_of_trunc_seq_colim f k) _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_compose' ⬝ !elim_glue ⬝ _, exact !idp_con } end end abstract begin intro x, induction x with x, induction x with n a n a, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose (trunc_seq_colim_of_seq_colim_trunc f k) _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_compose' ⬝ !elim_glue } end end theorem is_conn_seq_colim [instance] (k : ℕ₋₂) [H : Πn, is_conn k (A n)] : is_conn k (seq_colim f) := is_trunc_equiv_closed_rev -2 (trunc_seq_colim_equiv f k) _ /- the colimit of a sequence of fibers is the fiber of the functorial action of the colimit -/ definition domain_seq_colim_functor {A A' : ℕ → Type} {f : seq_diagram A} {f' : seq_diagram A'} (τ : Πn, A' n → A n) (p : Π⦃n⦄, τ (n+1) ∘ @f' n ~ @f n ∘ @τ n) : (Σ(x : seq_colim f), seq_colim_over (seq_diagram_over_fiber τ p) x) ≃ seq_colim f' := begin transitivity seq_colim (seq_diagram_sigma (seq_diagram_over_fiber τ p)), exact sigma_seq_colim_over_equiv _ (seq_diagram_over_fiber τ p), exact seq_colim_equiv (λn, sigma_fiber_equiv (τ n)) (λn x, idp) end definition fiber_seq_colim_functor {A A' : ℕ → Type} {f : seq_diagram A} {f' : seq_diagram A'} (τ : Πn, A' n → A n) (p : Π⦃n⦄, τ (n+1) ∘ @f' n ~ @f n ∘ @τ n) {n : ℕ} (a : A n) : fiber (seq_colim_functor τ p) (ι f a) ≃ seq_colim (seq_diagram_fiber τ p a) := begin refine _ ⬝e fiber_pr1 (seq_colim_over (seq_diagram_over_fiber τ p)) (ι f a), apply fiber_equiv_of_triangle (domain_seq_colim_functor τ p)⁻¹ᵉ, refine _ ⬝hty λx, (colim_sigma_triangle _ _)⁻¹, apply homotopy_inv_of_homotopy_pre (seq_colim_equiv _ _) (seq_colim_functor _ _) (seq_colim_functor _ _), refine (λx, !seq_colim_functor_compose⁻¹) ⬝hty _, refine seq_colim_functor_homotopy _ _, intro n x, exact point_eq x.2, intro n x, induction x with x y, induction y with y q, induction q, apply square_of_eq, refine !idp_con⁻¹ end definition fiber_seq_colim_functor0 {A A' : ℕ → Type} {f : seq_diagram A} {f' : seq_diagram A'} (τ : Πn, A' n → A n) (p : Π⦃n⦄, τ (n+1) ∘ @f' n ~ @f n ∘ @τ n) (a : A 0) : fiber (seq_colim_functor τ p) (ι f a) ≃ seq_colim (seq_diagram_fiber0 τ p a) := fiber_seq_colim_functor τ p a ⬝e seq_colim_equiv (λn, equiv_apd011 (λx y, fiber (τ x) y) (rep_pathover_rep0 f a)) (λn x, sorry) -- maybe use fn_tro_eq_tro_fn2 variables {f f'} definition fiber_inclusion (x : seq_colim f) : fiber (ι' f 0) x ≃ fiber (seq_colim_functor (rep0 f) (λn a, idp)) x := fiber_equiv_of_triangle (seq_colim_constant_seq (A 0))⁻¹ᵉ homotopy.rfl theorem is_trunc_fun_seq_colim_functor (k : ℕ₋₂) (H : Πn, is_trunc_fun k (@τ n)) : is_trunc_fun k (seq_colim_functor τ p) := begin intro x, induction x using seq_colim.rec_prop, exact is_trunc_equiv_closed_rev k (fiber_seq_colim_functor τ p a) _ end open is_conn theorem is_conn_fun_seq_colim_functor (k : ℕ₋₂) (H : Πn, is_conn_fun k (@τ n)) : is_conn_fun k (seq_colim_functor τ p) := begin intro x, induction x using seq_colim.rec_prop, exact is_conn_equiv_closed_rev k (fiber_seq_colim_functor τ p a) _ end variables (f f') theorem is_trunc_fun_inclusion (k : ℕ₋₂) (H : Πn, is_trunc_fun k (@f n)) : is_trunc_fun k (ι' f 0) := begin intro x, apply is_trunc_equiv_closed_rev k (fiber_inclusion x), apply is_trunc_fun_seq_colim_functor, intro n, apply is_trunc_fun_lrep, exact H end theorem is_conn_fun_inclusion (k : ℕ₋₂) (H : Πn, is_conn_fun k (@f n)) : is_conn_fun k (ι' f 0) := begin intro x, apply is_conn_equiv_closed_rev k (fiber_inclusion x), apply is_conn_fun_seq_colim_functor, intro n, apply is_conn_fun_lrep, exact H end /- the sequential colimit of standard finite types is ℕ -/ open fin definition nat_of_seq_colim_fin [unfold 1] (x : seq_colim seq_diagram_fin) : ℕ := begin induction x with n x n x, { exact x }, { reflexivity } end definition seq_colim_fin_of_nat (n : ℕ) : seq_colim seq_diagram_fin := ι' _ (n+1) (fin.mk n (self_lt_succ n)) definition lrep_seq_diagram_fin {n : ℕ} (x : fin n) : lrep seq_diagram_fin (is_lt x) (fin.mk x (self_lt_succ x)) = x := begin induction x with k H, esimp, induction H with n H p, reflexivity, exact ap (@lift_succ _) p end definition lrep_seq_diagram_fin_lift_succ {n : ℕ} (x : fin n) : lrep_seq_diagram_fin (lift_succ x) = ap (@lift_succ _) (lrep_seq_diagram_fin x) := begin induction x with k H, reflexivity end definition seq_colim_fin_equiv [constructor] : seq_colim seq_diagram_fin ≃ ℕ := equiv.MK nat_of_seq_colim_fin seq_colim_fin_of_nat abstract begin intro n, reflexivity end end abstract begin intro x, induction x with n x n x, { esimp, refine (lrep_glue _ (is_lt x) _)⁻¹ ⬝ ap (ι _) (lrep_seq_diagram_fin x), }, { apply eq_pathover_id_right, refine ap_compose seq_colim_fin_of_nat _ _ ⬝ ap02 _ !elim_glue ⬝ph _, esimp, refine (square_of_eq !con_idp)⁻¹ʰ ⬝h _, refine _ ⬝pv natural_square_tr (@glue _ (seq_diagram_fin) n) (lrep_seq_diagram_fin x), refine ap02 _ !lrep_seq_diagram_fin_lift_succ ⬝ !ap_compose⁻¹ } end end /- the sequential colimit of embeddings is an embedding -/ definition seq_colim_eq_equiv0'_inv_refl (a₀ : A 0) : (seq_colim_eq_equiv0' f a₀ a₀)⁻¹ᵉ (ι' (id_seq_diagram f 0 a₀ a₀) 0 proof (refl a₀) qed) = refl (ι f a₀) := begin apply inv_eq_of_eq, reflexivity, end definition is_embedding_ι (H : Πn, is_embedding (@f n)) : is_embedding (ι' f 0) := begin intro x y, fapply is_equiv_of_equiv_of_homotopy, { symmetry, refine seq_colim_eq_equiv0' f x y ⬝e _, apply equiv_of_is_equiseq, intro n, apply H }, { intro p, induction p, apply seq_colim_eq_equiv0'_inv_refl } end -- print axioms sigma_seq_colim_over_equiv -- print axioms seq_colim_eq_equiv -- print axioms fiber_seq_colim_functor -- print axioms is_trunc_seq_colim -- print axioms trunc_seq_colim_equiv -- print axioms is_conn_seq_colim -- print axioms is_trunc_fun_seq_colim_functor -- print axioms is_conn_fun_seq_colim_functor -- print axioms is_trunc_fun_inclusion -- print axioms is_conn_fun_inclusion end seq_colim
350c63a2b964f70b43d1eb55564cef57346b7c26
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/equiv/transfer_instance.lean
285ca153bc9ad53dad5475e864184fb49917869d
[ "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
13,461
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.algebra.basic import algebra.field.basic import algebra.group.type_tags import ring_theory.ideal.local_ring import data.equiv.basic /-! # Transfer algebraic structures across `equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. Note that most of these constructions can also be obtained using the `transport` tactic. ## Tags equiv, group, ring, field, module, algebra -/ universes u v variables {α : Type u} {β : Type v} namespace equiv section instances variables (e : α ≃ β) /-- Transfer `has_one` across an `equiv` -/ @[to_additive "Transfer `has_zero` across an `equiv`"] protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ @[to_additive] lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl /-- Transfer `has_mul` across an `equiv` -/ @[to_additive "Transfer `has_add` across an `equiv`"] protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ @[to_additive] lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl /-- Transfer `has_div` across an `equiv` -/ @[to_additive "Transfer `has_sub` across an `equiv`"] protected def has_div [has_div β] : has_div α := ⟨λ x y, e.symm (e x / e y)⟩ @[to_additive] lemma div_def [has_div β] (x y : α) : @has_div.div _ (equiv.has_div e) x y = e.symm (e x / e y) := rfl /-- Transfer `has_inv` across an `equiv` -/ @[to_additive "Transfer `has_neg` across an `equiv`"] protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ @[to_additive] lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl /-- Transfer `has_scalar` across an `equiv` -/ protected def has_scalar {R : Type*} [has_scalar R β] : has_scalar R α := ⟨λ r x, e.symm (r • (e x))⟩ lemma smul_def {R : Type*} [has_scalar R β] (r : R) (x : α) : @has_scalar.smul _ _ (equiv.has_scalar e) r x = e.symm (r • (e x)) := rfl /-- An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β` where the multiplicative structure on `α` is the one obtained by transporting a multiplicative structure on `β` back along `e`. -/ @[to_additive "An equivalence `e : α ≃ β` gives a additive equivalence `α ≃+ β` where the additive structure on `α` is the one obtained by transporting an additive structure on `β` back along `e`."] def mul_equiv (e : α ≃ β) [has_mul β] : by { letI := equiv.has_mul e, exact α ≃* β } := begin introsI, exact { map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp, to_additive] lemma mul_equiv_apply (e : α ≃ β) [has_mul β] (a : α) : (mul_equiv e) a = e a := rfl @[to_additive] lemma mul_equiv_symm_apply (e : α ≃ β) [has_mul β] (b : β) : by { letI := equiv.has_mul e, exact (mul_equiv e).symm b = e.symm b } := begin intros, refl, end /-- An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β` where the ring structure on `α` is the one obtained by transporting a ring structure on `β` back along `e`. -/ def ring_equiv (e : α ≃ β) [has_add β] [has_mul β] : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact α ≃+* β } := begin introsI, exact { map_add' := λ x y, by { apply e.symm.injective, simp, refl, }, map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp] lemma ring_equiv_apply (e : α ≃ β) [has_add β] [has_mul β] (a : α) : (ring_equiv e) a = e a := rfl lemma ring_equiv_symm_apply (e : α ≃ β) [has_add β] [has_mul β] (b : β) : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact (ring_equiv e).symm b = e.symm b } := begin intros, refl, end /-- Transfer `semigroup` across an `equiv` -/ @[to_additive "Transfer `add_semigroup` across an `equiv`"] protected def semigroup [semigroup β] : semigroup α := let mul := e.has_mul in by resetI; apply e.injective.semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `semigroup_with_zero` across an `equiv` -/ protected def semigroup_with_zero [semigroup_with_zero β] : semigroup_with_zero α := let mul := e.has_mul, zero := e.has_zero in by resetI; apply e.injective.semigroup_with_zero _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semigroup` across an `equiv` -/ @[to_additive "Transfer `add_comm_semigroup` across an `equiv`"] protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := let mul := e.has_mul in by resetI; apply e.injective.comm_semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_class` across an `equiv` -/ protected def mul_zero_class [mul_zero_class β] : mul_zero_class α := let zero := e.has_zero, mul := e.has_mul in by resetI; apply e.injective.mul_zero_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_one_class` across an `equiv` -/ @[to_additive "Transfer `add_zero_class` across an `equiv`"] protected def mul_one_class [mul_one_class β] : mul_one_class α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.mul_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_one_class` across an `equiv` -/ protected def mul_zero_one_class [mul_zero_one_class β] : mul_zero_one_class α := let zero := e.has_zero, one := e.has_one,mul := e.has_mul in by resetI; apply e.injective.mul_zero_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `monoid` across an `equiv` -/ @[to_additive "Transfer `add_monoid` across an `equiv`"] protected def monoid [monoid β] : monoid α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_monoid` across an `equiv` -/ @[to_additive "Transfer `add_comm_monoid` across an `equiv`"] protected def comm_monoid [comm_monoid β] : comm_monoid α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.comm_monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `group` across an `equiv` -/ @[to_additive "Transfer `add_group` across an `equiv`"] protected def group [group β] : group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.group _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_group` across an `equiv` -/ @[to_additive "Transfer `add_comm_group` across an `equiv`"] protected def comm_group [comm_group β] : comm_group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.comm_group _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_non_assoc_semiring` across an `equiv` -/ protected def non_unital_non_assoc_semiring [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul in by resetI; apply e.injective.non_unital_non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_semiring` across an `equiv` -/ protected def non_unital_semiring [non_unital_semiring β] : non_unital_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul in by resetI; apply e.injective.non_unital_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_assoc_semiring` across an `equiv` -/ protected def non_assoc_semiring [non_assoc_semiring β] : non_assoc_semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `semiring` across an `equiv` -/ protected def semiring [semiring β] : semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semiring` across an `equiv` -/ protected def comm_semiring [comm_semiring β] : comm_semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.comm_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_non_assoc_ring` across an `equiv` -/ protected def non_unital_non_assoc_ring [non_unital_non_assoc_ring β] : non_unital_non_assoc_ring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.non_unital_non_assoc_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `ring` across an `equiv` -/ protected def ring [ring β] : ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.ring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_ring` across an `equiv` -/ protected def comm_ring [comm_ring β] : comm_ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.comm_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `nontrivial` across an `equiv` -/ protected theorem nontrivial [nontrivial β] : nontrivial α := e.surjective.nontrivial /-- Transfer `is_domain` across an `equiv` -/ protected theorem is_domain [ring α] [ring β] [is_domain β] (e : α ≃+* β) : is_domain α := function.injective.is_domain e.to_ring_hom e.injective /-- Transfer `division_ring` across an `equiv` -/ protected def division_ring [division_ring β] : division_ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.division_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `field` across an `equiv` -/ protected def field [field β] : field α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.field _; intros; exact e.apply_symm_apply _ section R variables (R : Type*) include R section variables [monoid R] /-- Transfer `mul_action` across an `equiv` -/ protected def mul_action (e : α ≃ β) [mul_action R β] : mul_action R α := { one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_smul], ..equiv.has_scalar e } /-- Transfer `distrib_mul_action` across an `equiv` -/ protected def distrib_mul_action (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [distrib_mul_action R β], distrib_mul_action R α end := begin intros, letI := equiv.add_comm_monoid e, exact ( { smul_zero := by simp [zero_def, smul_def], smul_add := by simp [add_def, smul_def, smul_add], ..equiv.mul_action R e } : distrib_mul_action R α) end end section variables [semiring R] /-- Transfer `module` across an `equiv` -/ protected def module (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [module R β], module R α end := begin introsI, exact ( { zero_smul := by simp [zero_def, smul_def], add_smul := by simp [add_def, smul_def, add_smul], ..equiv.distrib_mul_action R e } : module R α) end /-- An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β` where the `R`-module structure on `α` is the one obtained by transporting an `R`-module structure on `β` back along `e`. -/ def linear_equiv (e : α ≃ β) [add_comm_monoid β] [module R β] : begin letI := equiv.add_comm_monoid e, letI := equiv.module R e, exact α ≃ₗ[R] β end := begin introsI, exact { map_smul' := λ r x, by { apply e.symm.injective, simp, refl, }, ..equiv.add_equiv e } end end section variables [comm_semiring R] /-- Transfer `algebra` across an `equiv` -/ protected def algebra (e : α ≃ β) [semiring β] : begin letI := equiv.semiring e, exact Π [algebra R β], algebra R α end := begin introsI, fapply ring_hom.to_algebra', { exact ((ring_equiv e).symm : β →+* α).comp (algebra_map R β), }, { intros r x, simp only [function.comp_app, ring_hom.coe_comp], have p := ring_equiv_symm_apply e, dsimp at p, erw p, clear p, apply (ring_equiv e).injective, simp only [(ring_equiv e).map_mul], simp [algebra.commutes], } end /-- An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β` where the `R`-algebra structure on `α` is the one obtained by transporting an `R`-algebra structure on `β` back along `e`. -/ def alg_equiv (e : α ≃ β) [semiring β] [algebra R β] : begin letI := equiv.semiring e, letI := equiv.algebra R e, exact α ≃ₐ[R] β end := begin introsI, exact { commutes' := λ r, by { apply e.symm.injective, simp, refl, }, ..equiv.ring_equiv e } end end end R end instances end equiv namespace ring_equiv protected lemma local_ring {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] (e : A ≃+* B) : local_ring B := begin haveI := e.symm.to_equiv.nontrivial, refine @local_of_surjective A B _ _ _ _ e e.to_equiv.surjective, end end ring_equiv
16a0e85920304d68e96309c312fcb2db1f36c199
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/exponent.lean
b7a8183ec252662d90536a627914c1814a4509ed
[ "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
11,489
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import group_theory.order_of_element import algebra.gcd_monoid.finset import algebra.punit_instances import data.nat.factorization.basic import tactic.by_contra /-! # Exponent of a group This file defines the exponent of a group, or more generally a monoid. For a group `G` it is defined to be the minimal `n≥1` such that `g ^ n = 1` for all `g ∈ G`. For a finite group `G`, it is equal to the lowest common multiple of the order of all elements of the group `G`. ## Main definitions * `monoid.exponent_exists` is a predicate on a monoid `G` saying that there is some positive `n` such that `g ^ n = 1` for all `g ∈ G`. * `monoid.exponent` defines the exponent of a monoid `G` as the minimal positive `n` such that `g ^ n = 1` for all `g ∈ G`, by convention it is `0` if no such `n` exists. * `add_monoid.exponent_exists` the additive version of `monoid.exponent_exists`. * `add_monoid.exponent` the additive version of `monoid.exponent`. ## Main results * `monoid.lcm_order_eq_exponent`: For a finite left cancel monoid `G`, the exponent is equal to the `finset.lcm` of the order of its elements. * `monoid.exponent_eq_supr_order_of(')`: For a commutative cancel monoid, the exponent is equal to `⨆ g : G, order_of g` (or zero if it has any order-zero elements). ## TODO * Refactor the characteristic of a ring to be the exponent of its underlying additive group. -/ universe u variable {G : Type u} open_locale classical namespace monoid section monoid variables (G) [monoid G] /--A predicate on a monoid saying that there is a positive integer `n` such that `g ^ n = 1` for all `g`.-/ @[to_additive "A predicate on an additive monoid saying that there is a positive integer `n` such that `n • g = 0` for all `g`."] def exponent_exists := ∃ n, 0 < n ∧ ∀ g : G, g ^ n = 1 /--The exponent of a group is the smallest positive integer `n` such that `g ^ n = 1` for all `g ∈ G` if it exists, otherwise it is zero by convention.-/ @[to_additive "The exponent of an additive group is the smallest positive integer `n` such that `n • g = 0` for all `g ∈ G` if it exists, otherwise it is zero by convention."] noncomputable def exponent := if h : exponent_exists G then nat.find h else 0 variable {G} @[to_additive] lemma exponent_exists_iff_ne_zero : exponent_exists G ↔ exponent G ≠ 0 := begin rw [exponent], split_ifs, { simp [h, @not_lt_zero' ℕ] }, --if this isn't done this way, `to_additive` freaks { tauto }, end @[to_additive] lemma exponent_eq_zero_iff : exponent G = 0 ↔ ¬ exponent_exists G := by simp only [exponent_exists_iff_ne_zero, not_not] @[to_additive] lemma exponent_eq_zero_of_order_zero {g : G} (hg : order_of g = 0) : exponent G = 0 := exponent_eq_zero_iff.mpr $ λ ⟨n, hn, hgn⟩, order_of_eq_zero_iff'.mp hg n hn $ hgn g @[to_additive exponent_nsmul_eq_zero] lemma pow_exponent_eq_one (g : G) : g ^ exponent G = 1 := begin by_cases exponent_exists G, { simp_rw [exponent, dif_pos h], exact (nat.find_spec h).2 g }, { simp_rw [exponent, dif_neg h, pow_zero] } end @[to_additive] lemma pow_eq_mod_exponent {n : ℕ} (g : G): g ^ n = g ^ (n % exponent G) := calc g ^ n = g ^ (n % exponent G + exponent G * (n / exponent G)) : by rw [nat.mod_add_div] ... = g ^ (n % exponent G) : by simp [pow_add, pow_mul, pow_exponent_eq_one] @[to_additive] lemma exponent_pos_of_exists (n : ℕ) (hpos : 0 < n) (hG : ∀ g : G, g ^ n = 1) : 0 < exponent G := begin have h : ∃ n, 0 < n ∧ ∀ g : G, g ^ n = 1 := ⟨n, hpos, hG⟩, rw [exponent, dif_pos], exact (nat.find_spec h).1, end @[to_additive] lemma exponent_min' (n : ℕ) (hpos : 0 < n) (hG : ∀ g : G, g ^ n = 1) : exponent G ≤ n := begin rw [exponent, dif_pos], { apply nat.find_min', exact ⟨hpos, hG⟩ }, { exact ⟨n, hpos, hG⟩ }, end @[to_additive] lemma exponent_min (m : ℕ) (hpos : 0 < m) (hm : m < exponent G) : ∃ g : G, g ^ m ≠ 1 := begin by_contra' h, have hcon : exponent G ≤ m := exponent_min' m hpos h, linarith, end @[simp, to_additive] lemma exp_eq_one_of_subsingleton [subsingleton G] : exponent G = 1 := begin apply le_antisymm, { apply exponent_min' _ nat.one_pos, simp }, { apply nat.succ_le_of_lt, apply exponent_pos_of_exists 1 (nat.one_pos), simp }, end @[to_additive add_order_dvd_exponent] lemma order_dvd_exponent (g : G) : (order_of g) ∣ exponent G := order_of_dvd_of_pow_eq_one $ pow_exponent_eq_one g variable (G) @[to_additive] lemma exponent_dvd_of_forall_pow_eq_one (G) [monoid G] (n : ℕ) (hG : ∀ g : G, g ^ n = 1) : exponent G ∣ n := begin rcases n.eq_zero_or_pos with rfl | hpos, { exact dvd_zero _ }, apply nat.dvd_of_mod_eq_zero, by_contradiction h, have h₁ := nat.pos_of_ne_zero h, have h₂ : n % exponent G < exponent G := nat.mod_lt _ (exponent_pos_of_exists n hpos hG), have h₃ : exponent G ≤ n % exponent G, { apply exponent_min' _ h₁, simp_rw ←pow_eq_mod_exponent, exact hG }, linarith, end @[to_additive lcm_add_order_of_dvd_exponent] lemma lcm_order_of_dvd_exponent [fintype G] : (finset.univ : finset G).lcm order_of ∣ exponent G := begin apply finset.lcm_dvd, intros g hg, exact order_dvd_exponent g end @[to_additive exists_order_of_eq_pow_padic_val_nat_add_exponent] lemma _root_.nat.prime.exists_order_of_eq_pow_factorization_exponent {p : ℕ} (hp : p.prime) : ∃ g : G, order_of g = p ^ (exponent G).factorization p := begin haveI := fact.mk hp, rcases eq_or_ne ((exponent G).factorization p) 0 with h | h, { refine ⟨1, by rw [h, pow_zero, order_of_one]⟩ }, have he : 0 < exponent G := ne.bot_lt (λ ht, by {rw ht at h, apply h, rw [bot_eq_zero, nat.factorization_zero, finsupp.zero_apply] }), rw ← finsupp.mem_support_iff at h, obtain ⟨g, hg⟩ : ∃ (g : G), g ^ (exponent G / p) ≠ 1, { suffices key : ¬ exponent G ∣ exponent G / p, { simpa using mt (exponent_dvd_of_forall_pow_eq_one G (exponent G / p)) key }, exact λ hd, hp.one_lt.not_le ((mul_le_iff_le_one_left he).mp $ nat.le_of_dvd he $ nat.mul_dvd_of_dvd_div (nat.dvd_of_mem_factorization h) hd) }, obtain ⟨k, hk : exponent G = p ^ _ * k⟩ := nat.ord_proj_dvd _ _, obtain ⟨t, ht⟩ := nat.exists_eq_succ_of_ne_zero (finsupp.mem_support_iff.mp h), refine ⟨g ^ k, _⟩, rw ht, apply order_of_eq_prime_pow, { rwa [hk, mul_comm, ht, pow_succ', ←mul_assoc, nat.mul_div_cancel _ hp.pos, pow_mul] at hg }, { rw [←nat.succ_eq_add_one, ←ht, ←pow_mul, mul_comm, ←hk], exact pow_exponent_eq_one g }, end variable {G} @[to_additive] lemma exponent_ne_zero_iff_range_order_of_finite (h : ∀ g : G, 0 < order_of g) : exponent G ≠ 0 ↔ (set.range (order_of : G → ℕ)).finite := begin refine ⟨λ he, _, λ he, _⟩, { by_contra h, obtain ⟨m, ⟨t, rfl⟩, het⟩ := set.infinite.exists_nat_lt h (exponent G), exact pow_ne_one_of_lt_order_of' he het (pow_exponent_eq_one t) }, { lift (set.range order_of) to finset ℕ using he with t ht, have htpos : 0 < t.prod id, { refine finset.prod_pos (λ a ha, _), rw [←finset.mem_coe, ht] at ha, obtain ⟨k, rfl⟩ := ha, exact h k }, suffices : exponent G ∣ t.prod id, { intro h, rw [h, zero_dvd_iff] at this, exact htpos.ne' this }, refine exponent_dvd_of_forall_pow_eq_one _ _ (λ g, _), rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd, pow_zero g], apply finset.dvd_prod_of_mem, rw [←finset.mem_coe, ht], exact set.mem_range_self g }, end @[to_additive] lemma exponent_eq_zero_iff_range_order_of_infinite (h : ∀ g : G, 0 < order_of g) : exponent G = 0 ↔ (set.range (order_of : G → ℕ)).infinite := have _ := exponent_ne_zero_iff_range_order_of_finite h, by rwa [ne.def, not_iff_comm, iff.comm] at this @[to_additive lcm_add_order_eq_exponent] lemma lcm_order_eq_exponent [fintype G] : (finset.univ : finset G).lcm order_of = exponent G := begin apply nat.dvd_antisymm (lcm_order_of_dvd_exponent G), refine exponent_dvd_of_forall_pow_eq_one G _ (λ g, _), obtain ⟨m, hm⟩ : order_of g ∣ finset.univ.lcm order_of := finset.dvd_lcm (finset.mem_univ g), rw [hm, pow_mul, pow_order_of_eq_one, one_pow] end end monoid section left_cancel_monoid variable [left_cancel_monoid G] @[to_additive] lemma exponent_ne_zero_of_finite [finite G] : exponent G ≠ 0 := by { casesI nonempty_fintype G, simpa [←lcm_order_eq_exponent, finset.lcm_eq_zero_iff] using λ x, (order_of_pos x).ne' } end left_cancel_monoid section comm_monoid variable [comm_monoid G] @[to_additive] lemma exponent_eq_supr_order_of (h : ∀ g : G, 0 < order_of g) : exponent G = ⨆ g : G, order_of g := begin rw supr, rcases eq_or_ne (exponent G) 0 with he | he, { rw [he, set.infinite.nat.Sup_eq_zero $ (exponent_eq_zero_iff_range_order_of_infinite h).1 he] }, have hne : (set.range (order_of : G → ℕ)).nonempty := ⟨1, 1, order_of_one⟩, have hfin : (set.range (order_of : G → ℕ)).finite, { rwa [← exponent_ne_zero_iff_range_order_of_finite h] }, obtain ⟨t, ht⟩ := hne.cSup_mem hfin, apply nat.dvd_antisymm _, { rw ←ht, apply order_dvd_exponent }, refine nat.dvd_of_factors_subperm he _, rw list.subperm_ext_iff, by_contra' h, obtain ⟨p, hp, hpe⟩ := h, replace hp := nat.prime_of_mem_factors hp, simp only [nat.factors_count_eq] at hpe, set k := (order_of t).factorization p with hk, obtain ⟨g, hg⟩ := hp.exists_order_of_eq_pow_factorization_exponent G, suffices : order_of t < order_of (t ^ (p ^ k) * g), { rw ht at this, exact this.not_le (le_cSup hfin.bdd_above $ set.mem_range_self _) }, have hpk : p ^ k ∣ order_of t := nat.ord_proj_dvd _ _, have hpk' : order_of (t ^ p ^ k) = order_of t / p ^ k, { rw [order_of_pow' t (pow_ne_zero k hp.ne_zero), nat.gcd_eq_right hpk] }, obtain ⟨a, ha⟩ := nat.exists_eq_add_of_lt hpe, have hcoprime : (order_of (t ^ p ^ k)).coprime (order_of g), { rw [hg, nat.coprime_pow_right_iff (pos_of_gt hpe), nat.coprime_comm], apply or.resolve_right (nat.coprime_or_dvd_of_prime hp _), nth_rewrite 0 ←pow_one p, convert nat.pow_succ_factorization_not_dvd (h $ t ^ p ^ k).ne' hp, rw [hpk', nat.factorization_div hpk], simp [hp] }, rw [(commute.all _ g).order_of_mul_eq_mul_order_of_of_coprime hcoprime, hpk', hg, ha, ←ht, ←hk, pow_add, pow_add, pow_one, ←mul_assoc, ←mul_assoc, nat.div_mul_cancel, mul_assoc, lt_mul_iff_one_lt_right $ h t, ←pow_succ'], exact one_lt_pow hp.one_lt a.succ_ne_zero, exact hpk end @[to_additive] lemma exponent_eq_supr_order_of' : exponent G = if ∃ g : G, order_of g = 0 then 0 else ⨆ g : G, order_of g := begin split_ifs, { obtain ⟨g, hg⟩ := h, exact exponent_eq_zero_of_order_zero hg }, { have := not_exists.mp h, exact exponent_eq_supr_order_of (λ g, ne.bot_lt $ this g) } end end comm_monoid section cancel_comm_monoid variables [cancel_comm_monoid G] @[to_additive] lemma exponent_eq_max'_order_of [fintype G] : exponent G = ((@finset.univ G _).image order_of).max' ⟨1, by simp⟩ := begin rw [←finset.nonempty.cSup_eq_max', finset.coe_image, finset.coe_univ, set.image_univ, ← supr], exact exponent_eq_supr_order_of order_of_pos end end cancel_comm_monoid end monoid
a8235ca0b06bd43564b6148d58aa60616ce784cd
618003631150032a5676f229d13a079ac875ff77
/src/order/zorn.lean
b64091ad37c9b1ed9d0f6e88dacb69576c05d931
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
12,915
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 Zorn's lemmas. Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel). -/ import data.set.lattice noncomputable theory universes u open set classical open_locale classical namespace zorn section chain parameters {α : Type u} (r : α → α → Prop) local infix ` ≺ `:50 := r /-- A chain is a subset `c` satisfying `x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/ def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x) parameters {r} theorem chain.total_of_refl [is_refl α r] {c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) : x ≺ y ∨ y ≺ x := if e : x = y then or.inl (e ▸ refl _) else H _ hx _ hy e theorem chain.mono {c c'} : c' ⊆ c → chain c → chain c' := pairwise_on.mono theorem chain.directed_on [is_refl α r] {c} (H : chain c) : directed_on (≺) c := assume x hx y hy, match H.total_of_refl hx hy with | or.inl h := ⟨y, hy, h, refl _⟩ | or.inr h := ⟨x, hx, refl _, h⟩ end theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _)) /-- `super_chain c₁ c₂` means that `c₂ is a chain that strictly includes `c₁`. -/ def super_chain (c₁ c₂ : set α) : Prop := chain c₂ ∧ c₁ ⊂ c₂ /-- A chain `c` is a maximal chain if there does not exists a chain strictly including `c`. -/ def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c') /-- Given a set `c`, if there exists a chain `c'` strictly including `c`, then `succ_chain c` is one of these chains. Otherwise it is `c`. -/ def succ_chain (c : set α) : set α := if h : ∃c', chain c ∧ super_chain c c' then some h else c theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λc', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂, cases hc₂.neg_resolve_left hc₁ with c' hc', exact succ_spec ⟨c', hc₁, hc'⟩ end theorem succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] /-- Set of sets reachable from `∅` using `succ_chain` and `⋃₀`. -/ inductive chain_closure : set α → Prop | succ : ∀{s}, chain_closure s → chain_closure (succ_chain s) | union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s) theorem chain_closure_empty : chain_closure ∅ := have chain_closure (⋃₀ ∅), from chain_closure.union $ assume a h, h.rec _, by simp at this; assumption theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) := chain_closure.union $ assume s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case succ : c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact or.inr (h ▸ subset.refl _) }, { exact or.inl h } }, { exact or.inr (subset.trans ih succ_increasing) } }, case union : s hs ih { refine (classical.or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _), apply (ih a ha).resolve_right, apply mt (λ h, _) hn, exact subset.trans h (subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case succ : c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case union : s hs ih { apply or.imp_left (assume h', subset.antisymm h' h), apply classical.by_contradiction, simp [not_or_distrib, sUnion_subset_iff, classical.not_forall], intros c₃ hc₃ h₁ h₂, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₁ $ h' ▸ subset.refl _) }, { exact (h₂ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₁ $ subset.trans succ_increasing h) } } end theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁, from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂, or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case succ : c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case union : s hs ih { exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) } end theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀ chain_closure := ⟨assume h, subset.antisymm (subset_sUnion_of_mem hc) (chain_closure_succ_fixpoint chain_closure_closure hc h), assume : c = ⋃₀{c : set α | chain_closure c}, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : this.symm) succ_increasing⟩ theorem chain_chain_closure (hc : chain_closure c) : chain c := begin induction hc, case succ : c hc h { exact chain_succ h }, case union : s hs h { have h : ∀c∈s, zorn.chain c := h, exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq) (assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) } end /-- `max_chain` is the union of all sets in the chain closure. -/ def max_chain := ⋃₀ chain_closure /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ theorem max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ assume : ¬ is_max_chain (⋃₀ chain_closure), have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)), from super_of_not_max (chain_chain_closure chain_closure_closure) this, let ⟨h₁, H⟩ := this, ⟨h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := ssubset_iff_subset_ne.1 H in have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure), from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl, h₃ this.symm /-- Zorn's lemma If every chain has an upper bound, then there is a maximal element -/ theorem exists_maximal_of_chains_bounded (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃m, ∀a, m ≺ a → a ≺ m := have ∃ub, ∀a∈max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in ⟨ub, assume a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ assume h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ end chain theorem zorn_partial_order {α : Type u} [partial_order α] (h : ∀c:set α, chain (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m := let ⟨m, hm⟩ := @exists_maximal_of_chains_bounded α (≤) h (assume a b c, le_trans) in ⟨m, assume a ha, le_antisymm (hm a ha) ha⟩ theorem zorn_partial_order₀ {α : Type u} [partial_order α] (s : set α) (ih : ∀ c ⊆ s, chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) : ∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z = m := let ⟨⟨m, hms, hxm⟩, h⟩ := @zorn_partial_order {m // m ∈ s ∧ x ≤ m} _ (λ c hc, c.eq_empty_or_nonempty.elim (assume hce, hce.symm ▸ ⟨⟨x, hxs, le_refl _⟩, λ _, false.elim⟩) (assume ⟨m, hmc⟩, let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (image_subset_iff.2 $ λ z hzc, z.2.1) (by rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq; exact hc p hpc q hqc (mt (by rintro rfl; refl) hpq)) m.1 (mem_image_of_mem _ hmc) in ⟨⟨ub, hubs, le_trans m.2.2 $ hub m.1 $ mem_image_of_mem _ hmc⟩, λ a hac, hub a.1 ⟨a, hac, rfl⟩⟩)) in ⟨m, hms, hxm, λ z hzs hmz, congr_arg subtype.val $ h ⟨z, hzs, le_trans hxm hmz⟩ hmz⟩ theorem zorn_subset {α : Type u} (S : set (set α)) (h : ∀c ⊆ S, chain (⊆) c → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) : ∃ m ∈ S, ∀a ∈ S, m ⊆ a → a = m := begin letI : partial_order S := partial_order.lift subtype.val (λ _ _, subtype.eq') (by apply_instance), have : ∀c:set S, @chain S (≤) c → ∃ub, ∀a∈c, a ≤ ub, { intros c hc, rcases h (subtype.val '' c) (image_subset_iff.2 _) _ with ⟨s, sS, hs⟩, { exact ⟨⟨s, sS⟩, λ ⟨x, hx⟩ H, hs _ (mem_image_of_mem _ H)⟩ }, { rintro ⟨x, hx⟩ _, exact hx }, { rintro _ ⟨x, cx, rfl⟩ _ ⟨y, cy, rfl⟩ xy, exact hc x cx y cy (mt (congr_arg _) xy) } }, rcases zorn_partial_order this with ⟨⟨m, mS⟩, hm⟩, exact ⟨m, mS, λ a aS ha, congr_arg subtype.val (hm ⟨a, aS⟩ ha)⟩ end theorem zorn_subset₀ {α : Type u} (S : set (set α)) (H : ∀c ⊆ S, chain (⊆) c → c.nonempty → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) : ∃ m ∈ S, x ⊆ m ∧ ∀a ∈ S, m ⊆ a → a = m := begin let T := {s ∈ S | x ⊆ s}, rcases zorn_subset T _ with ⟨m, ⟨mS, mx⟩, hm⟩, { exact ⟨m, mS, mx, λ a ha ha', hm a ⟨ha, subset.trans mx ha'⟩ ha'⟩ }, { intros c cT hc, cases c.eq_empty_or_nonempty with c0 c0, { rw c0, exact ⟨x, ⟨hx, subset.refl _⟩, λ _, false.elim⟩ }, { rcases H _ (subset.trans cT (sep_subset _ _)) hc c0 with ⟨ub, us, h⟩, refine ⟨ub, ⟨us, _⟩, h⟩, rcases c0 with ⟨s, hs⟩, exact subset.trans (cT hs).2 (h _ hs) } } end theorem chain.total {α : Type u} [preorder α] {c : set α} (H : chain (≤) c) : ∀ {x y}, x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x := λ x y, H.total_of_refl theorem chain.image {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) (f : α → β) (h : ∀ x y, r x y → s (f x) (f y)) {c : set α} (hrc : chain r c) : chain s (f '' c) := λ x ⟨a, ha₁, ha₂⟩ y ⟨b, hb₁, hb₂⟩, ha₂ ▸ hb₂ ▸ λ hxy, (hrc a ha₁ b hb₁ (mt (congr_arg f) $ hxy)).elim (or.inl ∘ h _ _) (or.inr ∘ h _ _) end zorn theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩))
63a40c90efc3aaa7a7c92c25ded05e809d59d131
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/topology/algebra/multilinear.lean
f5d8e035af7ee0fe2d5ae13c84306281c2fb865b
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
12,858
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.algebra.module import linear_algebra.multilinear /-! # Continuous multilinear maps We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear and continuous, by extending the space of multilinear maps with a continuity assumption. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these spaces are also topological spaces. ## Main definitions * `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from `Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module. ## Implementation notes We mostly follow the API of multilinear maps. ## Notation We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from `M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent types as the arguments of our continuous multilinear maps), but arguably the most important one, especially when defining iterated derivatives. -/ open function fin set open_locale big_operators universes u v w w₁ w₂ w₃ w₄ variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι] /-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R` with a topological structure. In applications, there will be compatibility conditions between the algebraic and the topological structures, but this is not needed for the definition. -/ structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] extends multilinear_map R M₁ M₂ := (cont : continuous to_fun) notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M' namespace continuous_multilinear_map section semiring variables [semiring R] [∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] [∀i, topological_space (M i)] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_space M₃] [topological_space M₄] (f f' : continuous_multilinear_map R M₁ M₂) instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) := ⟨_, λ f, f.to_multilinear_map.to_fun⟩ @[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl @[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := by { cases f, cases f', congr, ext x, exact H x } @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero instance : has_zero (continuous_multilinear_map R M₁ M₂) := ⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩ instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl section has_continuous_add variable [has_continuous_add M₂] instance : has_add (continuous_multilinear_map R M₁ M₂) := ⟨λ f f', {cont := f.cont.add f'.cont, ..(f.to_multilinear_map + f'.to_multilinear_map)}⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end end has_continuous_add /-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ := { cont := f.cont.comp continuous_update, ..(f.to_multilinear_map.to_linear_map m i) } /-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/ def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) : continuous_multilinear_map R M₁ (M₂ × M₃) := { cont := f.cont.prod_mk g.cont, .. f.to_multilinear_map.prod g.to_multilinear_map } @[simp] lemma prod_apply (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) : (f.prod g) m = (f m, g m) := rfl /- If `R` and `M₃` are implicit in the next definition, Lean is never able to infer them, even given `g` and `f`. Therefore, we make them explicit. -/ variables (R M₃) /-- If `g` is continuous multilinear and `f` is continuous linear, then `g (f m₁, ..., f mₙ)` is again a continuous multilinear map, that we call `g.comp_continuous_linear_map f`. -/ def comp_continuous_linear_map (g : continuous_multilinear_map R (λ (i : ι), M₃) M₄) (f : M₂ →L[R] M₃) : continuous_multilinear_map R (λ (i : ι), M₂) M₄ := { cont := g.cont.comp $ continuous_pi $ λj, f.cont.comp $ continuous_apply _, .. g.to_multilinear_map.comp_linear_map R M₃ f.to_linear_map } variables {R M₃} /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := f.to_multilinear_map.cons_add m x y /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := f.to_multilinear_map.cons_smul m c x lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := f.to_multilinear_map.map_piecewise_add _ _ _ /-- Additivity of a continuous multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := f.to_multilinear_map.map_add_univ _ _ section apply_sum open fintype finset variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) /-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum_finset _ _ /-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum _ end apply_sum end semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f f' : continuous_multilinear_map R M₁ M₂) @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := f.to_multilinear_map.map_sub _ _ _ _ section topological_add_group variable [topological_add_group M₂] instance : has_neg (continuous_multilinear_map R M₁ M₂) := ⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : add_comm_group (continuous_multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl end topological_add_group end ring section comm_ring variables [comm_ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f : continuous_multilinear_map R M₁ M₂) lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m := f.to_multilinear_map.map_piecewise_smul _ _ _ /-- Multiplicativity of a continuous multilinear map along all coordinates at the same time, writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λ i, c i • m i) = (∏ i, c i) • f m := f.to_multilinear_map.map_smul_univ _ _ variables [topological_space R] [topological_semimodule R M₂] instance : has_scalar R (continuous_multilinear_map R M₁ M₂) := ⟨λ c f, { cont := continuous.smul continuous_const f.cont, .. c • f.to_multilinear_map }⟩ @[simp] lemma smul_apply (c : R) (m : Πi, M₁ i) : (c • f) m = c • f m := rfl end comm_ring section comm_ring variables [comm_ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_add_group M₂] [topological_space R] [topological_semimodule R M₂] (f : continuous_multilinear_map R M₁ M₂) /-- The space of continuous multilinear maps is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : semimodule R (continuous_multilinear_map R M₁ M₂) := semimodule.of_core $ by refine { smul := (•), .. }; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map the corresponding multilinear map. -/ def to_multilinear_map_linear : (continuous_multilinear_map R M₁ M₂) →ₗ[R] (multilinear_map R M₁ M₂) := { to_fun := λ f, f.to_multilinear_map, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } end comm_ring end continuous_multilinear_map namespace continuous_linear_map variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_space M₃] /-- Composing a continuous multilinear map with a continuous linear map gives again a continuous multilinear map. -/ def comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : continuous_multilinear_map R M₁ M₃ := { cont := g.cont.comp f.cont, .. g.to_linear_map.comp_multilinear_map f.to_multilinear_map } @[simp] lemma comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : ((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) = (g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) := by { ext m, refl } end continuous_linear_map
3baf554d147603e101c1b42c6578a0dd43b667e2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/case.lean
76ded4bd6c98aed99b56c874fd7b1d3ead1b0452
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,826
lean
example (xs : list ℕ) : ℕ := begin induction xs, case list.cons {} end example (xs : list ℕ) : ℕ := begin cases xs, case list.cons {} end example (xs : list ℕ) : ℕ := begin induction xs, case list.cons : x xs { cases xs, case list.cons : x xs {} } end open list example (xs : list ℕ) : ℕ := begin induction xs, case cons {} end example (xs : list ℕ) : ℕ := begin cases h : xs, case list.cons : y ys {}, end example (xs : list ℕ) : ℕ := begin cases xs, case no_such_case {} end example (xs : list ℕ) : ℕ := begin cases xs, case list.cons {} end example (xs ys : list ℕ) : ℕ := begin cases xs; cases ys, case cons {} end example (xs : list ℕ) : ℕ := begin cases xs, case cons : x xs too_many_names {} end example (xs ys : list ℕ) : ℕ := begin induction xs; induction ys, case cons cons : x xs ih too_many_names {} end example (xs ys : list ℕ) : ℕ := begin with_cases { induction xs; induction ys }, case cons cons : x xs ih_xs y ys ih_ys {}, end example (xs : list ℕ) : ℕ := begin induction xs, case list.cons : x xs ih { apply ih }, case list.nil { apply 0 } end example (xs : list ℕ) : ℕ := begin cases xs, case nil { exact 0 }, case cons : x xs { exact 0 } end example (α β : Type*) (i j : α ⊕ β) : ℕ := begin with_cases {cases hi : i; cases hj : j}, case [sum.inl sum.inl, sum.inr sum.inr] { exact 1, exact 1, }, case [sum.inl sum.inr, sum.inr sum.inl] { exact 2, exact 2, }, end example (α β : Type*) (i j : α ⊕ β) : ℕ := begin with_cases {cases hi : i; cases hj : j}, case [sum.inl sum.inl : i j, sum.inr sum.inr : i j] { exact 1, exact 1, }, case [sum.inl sum.inr : i j, sum.inr sum.inl : i j] { exact 2, exact 2, }, end
ae0298b7e64c3a146bbe27de4b6f35f73a81f4a1
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/measure/open_pos.lean
acf862904523bc92617a4327e21a5ba4f2600488
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
7,309
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.measure.measure_space /-! # Measures positive on nonempty opens In this file we define a typeclass for measures that are positive on nonempty opens, see `measure_theory.measure.is_open_pos_measure`. Examples include (additive) Haar measures, as well as measures that have positive density with respect to a Haar measure. We also prove some basic facts about these measures. -/ open_locale topological_space ennreal measure_theory open set function filter namespace measure_theory namespace measure section basic variables {X Y : Type*} [topological_space X] {m : measurable_space X} [topological_space Y] [t2_space Y] (μ ν : measure X) /-- A measure is said to be `is_open_pos_measure` if it is positive on nonempty open sets. -/ class is_open_pos_measure : Prop := (open_pos : ∀ (U : set X), is_open U → U.nonempty → μ U ≠ 0) variables [is_open_pos_measure μ] {s U : set X} {x : X} lemma _root_.is_open.measure_ne_zero (hU : is_open U) (hne : U.nonempty) : μ U ≠ 0 := is_open_pos_measure.open_pos U hU hne lemma _root_.is_open.measure_pos (hU : is_open U) (hne : U.nonempty) : 0 < μ U := (hU.measure_ne_zero μ hne).bot_lt lemma _root_.is_open.measure_pos_iff (hU : is_open U) : 0 < μ U ↔ U.nonempty := ⟨λ h, nonempty_iff_ne_empty.2 $ λ he, h.ne' $ he.symm ▸ measure_empty, hU.measure_pos μ⟩ lemma _root_.is_open.measure_eq_zero_iff (hU : is_open U) : μ U = 0 ↔ U = ∅ := by simpa only [not_lt, nonpos_iff_eq_zero, not_nonempty_iff_eq_empty] using not_congr (hU.measure_pos_iff μ) lemma measure_pos_of_nonempty_interior (h : (interior s).nonempty) : 0 < μ s := (is_open_interior.measure_pos μ h).trans_le (measure_mono interior_subset) lemma measure_pos_of_mem_nhds (h : s ∈ 𝓝 x) : 0 < μ s := measure_pos_of_nonempty_interior _ ⟨x, mem_interior_iff_mem_nhds.2 h⟩ lemma is_open_pos_measure_smul {c : ℝ≥0∞} (h : c ≠ 0) : is_open_pos_measure (c • μ) := ⟨λ U Uo Une, mul_ne_zero h (Uo.measure_ne_zero μ Une)⟩ variables {μ ν} protected lemma absolutely_continuous.is_open_pos_measure (h : μ ≪ ν) : is_open_pos_measure ν := ⟨λ U ho hne h₀, ho.measure_ne_zero μ hne (h h₀)⟩ lemma _root_.has_le.le.is_open_pos_measure (h : μ ≤ ν) : is_open_pos_measure ν := h.absolutely_continuous.is_open_pos_measure lemma _root_.is_open.eq_empty_of_measure_zero (hU : is_open U) (h₀ : μ U = 0) : U = ∅ := (hU.measure_eq_zero_iff μ).mp h₀ lemma interior_eq_empty_of_null (hs : μ s = 0) : interior s = ∅ := is_open_interior.eq_empty_of_measure_zero $ measure_mono_null interior_subset hs /-- If two functions are a.e. equal on an open set and are continuous on this set, then they are equal on this set. -/ lemma eq_on_open_of_ae_eq {f g : X → Y} (h : f =ᵐ[μ.restrict U] g) (hU : is_open U) (hf : continuous_on f U) (hg : continuous_on g U) : eq_on f g U := begin replace h := ae_imp_of_ae_restrict h, simp only [eventually_eq, ae_iff, not_imp] at h, have : is_open (U ∩ {a | f a ≠ g a}), { refine is_open_iff_mem_nhds.mpr (λ a ha, inter_mem (hU.mem_nhds ha.1) _), rcases ha with ⟨ha : a ∈ U, ha' : (f a, g a) ∈ (diagonal Y)ᶜ⟩, exact (hf.continuous_at (hU.mem_nhds ha)).prod_mk_nhds (hg.continuous_at (hU.mem_nhds ha)) (is_closed_diagonal.is_open_compl.mem_nhds ha') }, replace := (this.eq_empty_of_measure_zero h).le, exact λ x hx, not_not.1 (λ h, this ⟨hx, h⟩) end /-- If two continuous functions are a.e. equal, then they are equal. -/ lemma eq_of_ae_eq {f g : X → Y} (h : f =ᵐ[μ] g) (hf : continuous f) (hg : continuous g) : f = g := suffices eq_on f g univ, from funext (λ x, this trivial), eq_on_open_of_ae_eq (ae_restrict_of_ae h) is_open_univ hf.continuous_on hg.continuous_on lemma eq_on_of_ae_eq {f g : X → Y} (h : f =ᵐ[μ.restrict s] g) (hf : continuous_on f s) (hg : continuous_on g s) (hU : s ⊆ closure (interior s)) : eq_on f g s := have interior s ⊆ s, from interior_subset, (eq_on_open_of_ae_eq (ae_restrict_of_ae_restrict_of_subset this h) is_open_interior (hf.mono this) (hg.mono this)).of_subset_closure hf hg this hU variable (μ) lemma _root_.continuous.ae_eq_iff_eq {f g : X → Y} (hf : continuous f) (hg : continuous g) : f =ᵐ[μ] g ↔ f = g := ⟨λ h, eq_of_ae_eq h hf hg, λ h, h ▸ eventually_eq.rfl⟩ end basic section linear_order variables {X Y : Type*} [topological_space X] [linear_order X] [order_topology X] {m : measurable_space X} [topological_space Y] [t2_space Y] (μ : measure X) [is_open_pos_measure μ] lemma measure_Ioi_pos [no_max_order X] (a : X) : 0 < μ (Ioi a) := is_open_Ioi.measure_pos μ nonempty_Ioi lemma measure_Iio_pos [no_min_order X] (a : X) : 0 < μ (Iio a) := is_open_Iio.measure_pos μ nonempty_Iio lemma measure_Ioo_pos [densely_ordered X] {a b : X} : 0 < μ (Ioo a b) ↔ a < b := (is_open_Ioo.measure_pos_iff μ).trans nonempty_Ioo lemma measure_Ioo_eq_zero [densely_ordered X] {a b : X} : μ (Ioo a b) = 0 ↔ b ≤ a := (is_open_Ioo.measure_eq_zero_iff μ).trans (Ioo_eq_empty_iff.trans not_lt) lemma eq_on_Ioo_of_ae_eq {a b : X} {f g : X → Y} (hfg : f =ᵐ[μ.restrict (Ioo a b)] g) (hf : continuous_on f (Ioo a b)) (hg : continuous_on g (Ioo a b)) : eq_on f g (Ioo a b) := eq_on_of_ae_eq hfg hf hg Ioo_subset_closure_interior lemma eq_on_Ioc_of_ae_eq [densely_ordered X] {a b : X} {f g : X → Y} (hfg : f =ᵐ[μ.restrict (Ioc a b)] g) (hf : continuous_on f (Ioc a b)) (hg : continuous_on g (Ioc a b)) : eq_on f g (Ioc a b) := eq_on_of_ae_eq hfg hf hg (Ioc_subset_closure_interior _ _) lemma eq_on_Ico_of_ae_eq [densely_ordered X] {a b : X} {f g : X → Y} (hfg : f =ᵐ[μ.restrict (Ico a b)] g) (hf : continuous_on f (Ico a b)) (hg : continuous_on g (Ico a b)) : eq_on f g (Ico a b) := eq_on_of_ae_eq hfg hf hg (Ico_subset_closure_interior _ _) lemma eq_on_Icc_of_ae_eq [densely_ordered X] {a b : X} (hne : a ≠ b) {f g : X → Y} (hfg : f =ᵐ[μ.restrict (Icc a b)] g) (hf : continuous_on f (Icc a b)) (hg : continuous_on g (Icc a b)) : eq_on f g (Icc a b) := eq_on_of_ae_eq hfg hf hg (closure_interior_Icc hne).symm.subset end linear_order end measure end measure_theory open measure_theory measure_theory.measure namespace metric variables {X : Type*} [pseudo_metric_space X] {m : measurable_space X} (μ : measure X) [is_open_pos_measure μ] lemma measure_ball_pos (x : X) {r : ℝ} (hr : 0 < r) : 0 < μ (ball x r) := is_open_ball.measure_pos μ (nonempty_ball.2 hr) lemma measure_closed_ball_pos (x : X) {r : ℝ} (hr : 0 < r) : 0 < μ (closed_ball x r) := (measure_ball_pos μ x hr).trans_le (measure_mono ball_subset_closed_ball) end metric namespace emetric variables {X : Type*} [pseudo_emetric_space X] {m : measurable_space X} (μ : measure X) [is_open_pos_measure μ] lemma measure_ball_pos (x : X) {r : ℝ≥0∞} (hr : r ≠ 0) : 0 < μ (ball x r) := is_open_ball.measure_pos μ ⟨x, mem_ball_self hr.bot_lt⟩ lemma measure_closed_ball_pos (x : X) {r : ℝ≥0∞} (hr : r ≠ 0) : 0 < μ (closed_ball x r) := (measure_ball_pos μ x hr).trans_le (measure_mono ball_subset_closed_ball) end emetric
ee507105eac835f9b6cac2bc364a9f6c5d93e539
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic26.lean
5dc970a342840ab470188b54d6996f2af57962bd
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
703
lean
import standard using tactic inductive sum (A : Type) (B : Type) : Type := | inl : A → sum A B | inr : B → sum A B theorem inl_inhabited {A : Type} (B : Type) (H : inhabited A) : inhabited (sum A B) := inhabited_elim H (λ a, inhabited_intro (inl B a)) theorem inr_inhabited (A : Type) {B : Type} (H : inhabited B) : inhabited (sum A B) := inhabited_elim H (λ b, inhabited_intro (inr A b)) definition my_tac := fixpoint (λ t, [ apply @inl_inhabited; t | apply @inr_inhabited; t | apply @num.inhabited_num ]) tactic_hint [inhabited] my_tac theorem T : inhabited (sum false num.num)
91e594ec445a77acd1c3930aa13b2572360c2e29
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/univ_problem.lean
5fa87dfe253f11f085fbc17d8e2206741aab1365
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,238
lean
import logic data.nat.basic data.prod data.unit open nat prod inductive vector (A : Type) : nat → Type := | vnil {} : vector A zero | vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector print definition vector.no_confusion infixr `::` := vcons namespace play section universe variables l₁ l₂ variable {A : Type.{l₁}} variable {C : Π (n : nat), vector A n → Type.{l₂+1}} definition brec_on {n : nat} (v : vector A n) (H : Π (n : nat) (v : vector A n), @vector.below A C n v → C n v) : C n v := have general : C n v × @vector.below A C n v, from vector.rec_on v (pair (H zero vnil unit.star) unit.star) (λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (r₁ : C n₁ v₁ × @vector.below A C n₁ v₁), have b : @vector.below A C _ (vcons a₁ v₁), from r₁, have c : C (succ n₁) (vcons a₁ v₁), from H (succ n₁) (vcons a₁ v₁) b, pair c b), pr₁ general end end play print "=====================" definition append {A : Type} {n m : nat} (w : vector A m) (v : vector A n) : vector A (n + m) := vector.brec_on w (λ (n : nat) (w : vector A n), vector.cases_on w (λ (B : vector.below vnil), v) (λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (B : vector.below (vcons a₁ v₁)), vcons a₁ (pr₁ B))) exit check vector.brec_on definition bw := @vector.below definition sum {n : nat} (v : vector nat n) : nat := vector.brec_on v (λ (n : nat) (v : vector nat n), vector.cases_on v (λ (B : bw vnil), zero) (λ (n₁ : nat) (a : nat) (v₁ : vector nat n₁) (B : bw (vcons a v₁)), a + pr₁ B)) example : sum (10 :: 20 :: vnil) = 30 := rfl definition addk {n : nat} (v : vector nat n) (k : nat) : vector nat n := vector.brec_on v (λ (n : nat) (v : vector nat n), vector.cases_on v (λ (B : bw vnil), vnil) (λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)), vcons (a₁+k) (pr₁ B))) example : addk (1 :: 2 :: vnil) 3 = 4 :: 5 :: vnil := rfl example : append (1 :: 2 :: vnil) (3 :: vnil) = 1 :: 2 :: 3 :: vnil := rfl definition head {A : Type} {n : nat} (v : vector A (succ n)) : A := nat.cases_on v (λ H : succ n = 0, nat.no_confusion H) (λn' h t (H : succ n = succ n'), h) rfl definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n := @nat.cases_on A (λn' v, succ n = n' → vector A (pred n')) (succ n) v (λ H : succ n = 0, nat.no_confusion H) (λ (n' : nat) (h : A) (t : vector A n') (H : succ n = succ n'), t) rfl definition add {n : nat} (w v : vector nat n) : vector nat n := @nat.brec_on nat (λ (n : nat) (v : vector nat n), vector nat n → vector nat n) n w (λ (n : nat) (w : vector nat n), vector.cases_on w (λ (B : bw vnil) (w : vector nat zero), vnil) (λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)) (v : vector nat (succ n₁)), vcons (a₁ + head v) (pr₁ B (tail v)))) v example : add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil := rfl end vector
50accfe8d923a0c8319f09203899dffc0dcf8463
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/match_tac4.lean
6ec665061f6563ed97014f2251ee92b07c6bbadc
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
736
lean
notation `⟪`:max t:(foldr `,` (e r, and.intro e r)) `⟫`:0 := t check ⟪ trivial, trivial, trivial ⟫ theorem tst (a b c d : Prop) : a ∧ b ∧ c ∧ d ↔ d ∧ c ∧ b ∧ a := begin apply iff.intro, begin intro H, match H with | ⟪ H₁, H₂, H₃, H₄ ⟫ := ⟪ H₄, H₃, H₂, H₁ ⟫ end end, begin intro H, match H with | ⟪ H₁, H₂, H₃, H₄ ⟫ := begin repeat [apply and.intro | assumption] end end end end print definition tst theorem tst2 (a b c d : Prop) : a ∧ b ∧ c ∧ d ↔ d ∧ c ∧ b ∧ a := begin apply iff.intro, repeat (intro H; repeat [cases H with [H', H] | apply and.intro | assumption]) end print definition tst2
748f6d678e4802f96508fd3401bd7d014645f3da
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/nat/parity.lean
9851b36c3f40791dad5cc61cc7da1a151d023abc
[ "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
9,631
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Benjamin Davidson -/ import data.nat.modeq import algebra.parity /-! # Parity of natural numbers This file contains theorems about the `even` and `odd` predicates on the natural numbers. ## Tags even, odd -/ namespace nat variables {m n : ℕ} @[simp] theorem mod_two_ne_one : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem mod_two_ne_zero : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] theorem even_iff : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [← two_mul, hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [← two_mul, h])⟩⟩ theorem odd_iff : odd n ↔ n % 2 = 1 := ⟨λ ⟨m, hm⟩, by norm_num [hm, add_mod], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by rw [h, add_comm])⟩⟩ lemma not_even_iff : ¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] lemma not_odd_iff : ¬ odd n ↔ n % 2 = 0 := by rw [odd_iff, mod_two_ne_one] lemma even_iff_not_odd : even n ↔ ¬ odd n := by rw [not_odd_iff, even_iff] @[simp] lemma odd_iff_not_even : odd n ↔ ¬ even n := by rw [not_even_iff, odd_iff] lemma is_compl_even_odd : is_compl {n : ℕ | even n} {n | odd n} := by simp only [←set.compl_set_of, is_compl_compl, odd_iff_not_even] lemma even_or_odd (n : ℕ) : even n ∨ odd n := or.imp_right odd_iff_not_even.2 $ em $ even n lemma even_or_odd' (n : ℕ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 := by simpa only [← two_mul, exists_or_distrib, ← odd, ← even] using even_or_odd n lemma even_xor_odd (n : ℕ) : xor (even n) (odd n) := begin cases even_or_odd n with h, { exact or.inl ⟨h, even_iff_not_odd.mp h⟩ }, { exact or.inr ⟨h, odd_iff_not_even.mp h⟩ }, end lemma even_xor_odd' (n : ℕ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) := begin rcases even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; use k, { simpa only [← two_mul, xor, true_and, eq_self_iff_true, not_true, or_false, and_false] using (succ_ne_self (2*k)).symm }, { simp only [xor, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff, one_ne_zero, and_self] }, end @[simp] theorem two_dvd_ne_zero : ¬ 2 ∣ n ↔ n % 2 = 1 := even_iff_two_dvd.symm.not.trans not_even_iff instance : decidable_pred (even : ℕ → Prop) := λ n, decidable_of_iff _ even_iff.symm instance : decidable_pred (odd : ℕ → Prop) := λ n, decidable_of_iff _ odd_iff_not_even.symm mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" @[simp] theorem not_even_one : ¬ even 1 := by rw even_iff; norm_num @[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.add_mod]; norm_num theorem even_add' : even (m + n) ↔ (odd m ↔ odd n) := by rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not] @[parity_simps] theorem even_add_one : even (n + 1) ↔ ¬ even n := by simp [even_add] @[simp] theorem not_even_bit1 (n : ℕ) : ¬ even (bit1 n) := by simp [bit1] with parity_simps lemma two_not_dvd_two_mul_add_one (n : ℕ) : ¬(2 ∣ 2 * n + 1) := by simp [add_mod] lemma two_not_dvd_two_mul_sub_one : Π {n} (w : 0 < n), ¬(2 ∣ 2 * n - 1) | (n + 1) _ := two_not_dvd_two_mul_add_one n @[parity_simps] theorem even_sub (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←tsub_add_cancel_of_le h, even_add] }, by_cases h : even n; simp [h] end theorem even_sub' (h : n ≤ m) : even (m - n) ↔ (odd m ↔ odd n) := by rw [even_sub h, even_iff_not_odd, even_iff_not_odd, not_iff_not] theorem odd.sub_odd (hm : odd m) (hn : odd n) : even (m - n) := (le_total n m).elim (λ h, by simp only [even_sub' h, *]) (λ h, by simp only [tsub_eq_zero_iff_le.mpr h, even_zero]) @[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.mul_mod]; norm_num theorem odd_mul : odd (m * n) ↔ odd m ∧ odd n := by simp [not_or_distrib] with parity_simps theorem odd.of_mul_left (h : odd (m * n)) : odd m := (odd_mul.mp h).1 theorem odd.of_mul_right (h : odd (m * n)) : odd n := (odd_mul.mp h).2 /-- If `m` and `n` are natural numbers, then the natural number `m^n` is even if and only if `m` is even and `n` is positive. -/ @[parity_simps] theorem even_pow : even (m ^ n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, pow_succ', even_mul], tauto } theorem even_pow' (h : n ≠ 0) : even (m ^ n) ↔ even m := even_pow.trans $ and_iff_left h theorem even_div : even (m / n) ↔ m % (2 * n) / n = 0 := by rw [even_iff_two_dvd, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm] @[parity_simps] theorem odd_add : odd (m + n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_add, not_iff, odd_iff_not_even] theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) := by rw [add_comm, odd_add] lemma ne_of_odd_add (h : odd (m + n)) : m ≠ n := λ hnot, by simpa [hnot] with parity_simps using h @[parity_simps] theorem odd_sub (h : n ≤ m) : odd (m - n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_sub h, not_iff, odd_iff_not_even] theorem odd.sub_even (h : n ≤ m) (hm : odd m) (hn : even n) : odd (m - n) := (odd_sub h).mpr $ iff_of_true hm hn theorem odd_sub' (h : n ≤ m) : odd (m - n) ↔ (odd n ↔ even m) := by rw [odd_iff_not_even, even_sub h, not_iff, not_iff_comm, odd_iff_not_even] theorem even.sub_odd (h : n ≤ m) (hm : even m) (hn : odd n) : odd (m - n) := (odd_sub' h).mpr $ iff_of_true hn hm lemma even_mul_succ_self (n : ℕ) : even (n * (n + 1)) := begin rw even_mul, convert n.even_or_odd, simp with parity_simps end lemma even_mul_self_pred (n : ℕ) : even (n * (n - 1)) := begin cases n, { exact even_zero }, { rw mul_comm, apply even_mul_succ_self } end lemma even_sub_one_of_prime_ne_two {p : ℕ} (hp : prime p) (hodd : p ≠ 2) : even (p - 1) := odd.sub_odd (odd_iff.2 $ hp.eq_two_or_odd.resolve_left hodd) (odd_iff.2 rfl) lemma two_mul_div_two_of_even : even n → 2 * (n / 2) = n := λ h, nat.mul_div_cancel_left' (even_iff_two_dvd.mp h) lemma div_two_mul_two_of_even : even n → n / 2 * 2 = n := --nat.div_mul_cancel λ h, nat.div_mul_cancel (even_iff_two_dvd.mp h) lemma two_mul_div_two_add_one_of_odd (h : odd n) : 2 * (n / 2) + 1 = n := by { rw mul_comm, convert nat.div_add_mod' n 2, rw odd_iff.mp h } lemma div_two_mul_two_add_one_of_odd (h : odd n) : n / 2 * 2 + 1 = n := by { convert nat.div_add_mod' n 2, rw odd_iff.mp h } lemma one_add_div_two_mul_two_of_odd (h : odd n) : 1 + n / 2 * 2 = n := by { rw add_comm, convert nat.div_add_mod' n 2, rw odd_iff.mp h } lemma bit0_div_two : bit0 n / 2 = n := by rw [←nat.bit0_eq_bit0, bit0_eq_two_mul, two_mul_div_two_of_even (even_bit0 n)] lemma bit1_div_two : bit1 n / 2 = n := by rw [←nat.bit1_eq_bit1, bit1, bit0_eq_two_mul, nat.two_mul_div_two_add_one_of_odd (odd_bit1 n)] @[simp] lemma bit0_div_bit0 : bit0 n / bit0 m = n / m := by rw [bit0_eq_two_mul m, ←nat.div_div_eq_div_mul, bit0_div_two] @[simp] lemma bit1_div_bit0 : bit1 n / bit0 m = n / m := by rw [bit0_eq_two_mul, ←nat.div_div_eq_div_mul, bit1_div_two] @[simp] lemma bit0_mod_bit0 : bit0 n % bit0 m = bit0 (n % m) := by rw [bit0_eq_two_mul n, bit0_eq_two_mul m, bit0_eq_two_mul (n % m), nat.mul_mod_mul_left] @[simp] lemma bit1_mod_bit0 : bit1 n % bit0 m = bit1 (n % m) := begin have h₁ := congr_arg bit1 (nat.div_add_mod n m), -- `∀ m n : ℕ, bit0 m * n = bit0 (m * n)` seems to be missing... rw [bit1_add, bit0_eq_two_mul, ← mul_assoc, ← bit0_eq_two_mul] at h₁, have h₂ := nat.div_add_mod (bit1 n) (bit0 m), rw [bit1_div_bit0] at h₂, exact add_left_cancel (h₂.trans h₁.symm), end -- Here are examples of how `parity_simps` can be used with `nat`. example (m n : ℕ) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even 25394535 := by simp end nat open nat variables {R : Type*} [monoid R] [has_distrib_neg R] {n : ℕ} lemma neg_one_pow_eq_one_iff_even (h : (-1 : R) ≠ 1) : (-1 : R) ^ n = 1 ↔ even n := ⟨λ h', of_not_not $ λ hn, h $ (odd.neg_one_pow $ odd_iff_not_even.mpr hn).symm.trans h', even.neg_one_pow⟩ /-- If `a` is even, then `n` is odd iff `n % a` is odd. -/ lemma odd.mod_even_iff {n a : ℕ} (ha : even a) : odd (n % a) ↔ odd n := ((even_sub' $ mod_le n a).mp $ even_iff_two_dvd.mpr $ (even_iff_two_dvd.mp ha).trans $ dvd_sub_mod n).symm /-- If `a` is even, then `n` is even iff `n % a` is even. -/ lemma even.mod_even_iff {n a : ℕ} (ha : even a) : even (n % a) ↔ even n := ((even_sub $ mod_le n a).mp $ even_iff_two_dvd.mpr $ (even_iff_two_dvd.mp ha).trans $ dvd_sub_mod n).symm /-- If `n` is odd and `a` is even, then `n % a` is odd. -/ lemma odd.mod_even {n a : ℕ} (hn : odd n) (ha : even a) : odd (n % a) := (odd.mod_even_iff ha).mpr hn /-- If `n` is even and `a` is even, then `n % a` is even. -/ lemma even.mod_even {n a : ℕ} (hn : even n) (ha : even a) : even (n % a) := (even.mod_even_iff ha).mpr hn /-- `2` is not a prime factor of an odd natural number. -/ lemma odd.factors_ne_two {n p : ℕ} (hn : odd n) (hp : p ∈ n.factors) : p ≠ 2 := by { rintro rfl, exact two_dvd_ne_zero.mpr (odd_iff.mp hn) (dvd_of_mem_factors hp) }
f48fd139b5cdfe662b2dc7262f334fac806bc4e9
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/pack_unpack3.lean
8fa55f6188c743429884588fde73c4c302a01678
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
966
lean
inductive vec (A : Type*) : nat -> Type* | vnil : vec 0 | vcons : Pi (n : nat), A -> vec n -> vec (n+1) inductive tree (A : Type*) | leaf : A -> tree | node : Pi (n : nat), vec (list (list tree)) n -> tree -- set_option trace.eqn_compiler true constant P {A : Type*} : tree A → Type constant mk1 {A : Type*} (a : A) : P (tree.leaf a) constant mk2 {A : Type*} (n : nat) (xs : vec (list (list (tree A))) n) : P (tree.node n xs) noncomputable definition bla {A : Type*} : ∀ n : tree A, P n | (tree.leaf a) := mk1 a | (tree.node n xs) := mk2 n xs check bla._main.equations._eqn_1 check bla._main.equations._eqn_2 noncomputable definition foo {A : Type*} : nat → tree A → nat | 0 _ := sorry | (n+1) (tree.leaf a) := 0 | (n+1) (tree.node m xs) := foo n (tree.node m xs) check @foo._main.equations._eqn_1 check @foo._main.equations._eqn_2 check @foo._main.equations._eqn_3
a8fbdf91e40b9aaf58456799e95e09d0d5157673
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/meta/mk_dec_eq_instance.lean
4ad4167ec32482165383bf362da765a3fb8c64d6
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
5,348
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 Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics import init.meta.rec_util init.meta.interactive namespace tactic open expr environment list /- Retrieve the name of the type we are building a decidable equality proof for. -/ private meta def get_dec_eq_type_name : tactic name := do { (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const n ls) ← return (get_app_fn b), when (n ≠ `decidable) failed, (const I ls) ← return (get_app_fn d1), return I } <|> fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)" /- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/ private meta def get_lhs_rhs : tactic (expr × expr) := do (app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case", match_eq lhs_eq_rhs private meta def find_next_target : list expr → list expr → tactic (expr × expr) | (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r) | l1 l2 := failed /- Create an inhabitant of (decidable (lhs = rhs)) -/ private meta def mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr := do lhs_type ← infer_type lhs, dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf, do { inst ← mk_instance dec_type, return $ inst lhs rhs } <|> do { f ← pp dec_type, fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) } /- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/ private meta def dec_eq_same_constructor : name → name → nat → tactic unit | I_name F_name num_rec := do (lhs, rhs) ← get_lhs_rhs, -- Try easy case first, where the proof is just reflexivity (unify lhs rhs >> right >> reflexivity) <|> do { let lhs_list := get_app_args lhs, let rhs_list := get_app_args rhs, when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"), (lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list, rec ← is_type_app_of lhs_arg I_name, inst ← if rec then do { inst_fn ← mk_brec_on_rec_value F_name num_rec, return $ app inst_fn rhs_arg } else do { mk_dec_eq_for lhs_arg rhs_arg }, `[apply @decidable.by_cases _ _ %%inst], -- discharge first (positive) case by recursion intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec then num_rec + 1 else num_rec), -- discharge second (negative) case by contradiction intro1, left, -- decidable.is_false intro1 >>= injection, intros, contradiction, return () } /- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/ private meta def dec_eq_diff_constructor : tactic unit := left >> intron 1 >> contradiction /- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number of constructors. -/ private meta def dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit := do (lhs, rhs) ← get_lhs_rhs, let lhs_fn := get_app_fn lhs, let rhs_fn := get_app_fn rhs, if lhs_fn = rhs_fn then dec_eq_same_constructor I_name F_name 0 else dec_eq_diff_constructor private meta def dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit := intro `w >>= cases >> all_goals (dec_eq_case_2 I_name F_name) meta def mk_dec_eq_instance_core : tactic unit := do I_name ← get_dec_eq_type_name, env ← get_env, let v_name := `_v, let F_name := `_F, let num_indices := inductive_num_indices env I_name, let idx_names := list.map (λ (p : name × nat), mk_num_name p.fst p.snd) (list.zip (list.repeat `idx num_indices) (list.iota num_indices)), -- Use brec_on if type is recursive. -- We store the functional in the variable F. if is_recursive env I_name then intro1 >>= (λ x, induction x (idx_names ++ [v_name, F_name]) (some $ I_name <.> "brec_on") >> return ()) else intro v_name >> return (), -- Apply cases to first element of type (I ...) get_local v_name >>= cases, all_goals (dec_eq_case_1 I_name F_name) meta def mk_dec_eq_instance : tactic unit := do env ← get_env, (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const I_name ls) ← return (get_app_fn d1), when (is_ginductive env I_name ∧ ¬ is_inductive env I_name) $ do { d1' ← whnf d1, (app I_basic_const I_idx) ← return d1', I_idx_type ← infer_type I_idx, new_goal ← to_expr ``(∀ (_idx : %%I_idx_type), decidable_eq (%%I_basic_const _idx)), assert `_basic_dec_eq new_goal, swap, to_expr `(_basic_dec_eq %%I_idx) >>= exact, intro1, return () }, mk_dec_eq_instance_core meta instance binder_info.has_decidable_eq : decidable_eq binder_info := by mk_dec_eq_instance end tactic /- instances of types in dependent files -/ instance : decidable_eq ordering := by tactic.mk_dec_eq_instance
9681ac2a92011de8d4b95c3083f79b69c525bb39
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/field_theory/adjoin.lean
e76937b4c6201e804c037d8ab1f9116ce9946707
[ "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,416
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning and Patrick Lutz -/ import deprecated.subfield import linear_algebra.finite_dimensional /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results (This is just a start; we've got more to add, including a proof of the Primitive Element Theorem.) - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining S ∪ T. ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ namespace field variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : subalgebra F E := { carrier := field.closure (set.range (algebra_map F E) ∪ S), one_mem' := is_submonoid.one_mem, mul_mem' := λ x y, is_submonoid.mul_mem, zero_mem' := is_add_submonoid.zero_mem, add_mem' := λ x y, is_add_submonoid.add_mem, algebra_map_mem' := λ x, field.mem_closure (or.inl (set.mem_range.mpr ⟨x,rfl⟩)) } lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := field.mem_closure (or.inl (set.mem_range_self x)) lemma subset_adjoin_of_subset_left {F : set E} {HF : is_subfield F} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, HT hx⟩ lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, field.mem_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} lemma adjoin.mono (T : set E) (h : S ⊆ T) : (adjoin F S : set E) ⊆ adjoin F T := field.closure_mono (set.union_subset (set.subset_union_left _ _) (set.subset_union_of_subset_right h _)) instance adjoin.is_subfield : is_subfield (adjoin F S : set E) := field.closure.is_subfield --Lean has trouble figuring this out on its own instance adjoin.is_field : field (adjoin F S) := @is_subfield.field E _ ((adjoin F S) : set E) _ lemma adjoin_contains_field_as_subfield (F : set E) {HF : is_subfield F} : F ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := begin intros x hx, exact subset_adjoin F S (H hx), end /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ⊆ K`. -/ lemma adjoin_subset_subfield {K : set E} [is_subfield K] (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S : set E) ⊆ K := begin apply field.closure_subset, rw set.union_subset_iff, exact ⟨HF, HS⟩, end /-- `S ⊆ adjoin F T` if and only if `adjoin F S ⊆ adjoin F T`. -/ lemma adjoin_subset_iff {T : set E} : S ⊆ adjoin F T ↔ (adjoin F S : set E) ⊆ adjoin F T := ⟨λ h, adjoin_subset_subfield F S (adjoin.range_algebra_map_subset F T) h, λ h, set.subset.trans (subset_adjoin F S) h⟩ lemma subfield_subset_adjoin_self {F : set E} {HF : is_subfield F} {T : set E} {HT : T ⊆ F} : T ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x,HT hx⟩ lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, field.closure_subset (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : (adjoin (adjoin F S : set E) T : set E) = adjoin F (S ∪ T) := begin apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { exact algebra.set_range_subset (adjoin.mono _ _ _ (set.subset_union_left _ _)) }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end variables (α : E) notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, set.insert h t) ∅) `⟯` := adjoin K l --unfortunately this lemma is not definitionally true lemma adjoin_singleton : F⟮α⟯ = adjoin F {α} := begin change adjoin F (insert α ∅) = adjoin F {α}, rw insert_emptyc_eq α, exact set.is_lawful_singleton, end lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := begin rw adjoin_singleton, exact subset_adjoin F {α} (set.mem_singleton α), end /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl lemma adjoin_simple_adjoin_simple (β : E) : F⟮α,β⟯ = adjoin F {α,β} := begin change adjoin F (insert α (insert β ∅)) = adjoin F _, simp only [insert_emptyc_eq], end end field
68a16ad3495b9d9b0f6ecd65fb82a8a3a3bbdea1
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/bigop.lean
2406ab4a905ebcb9ad44957ccd26d518ed86b8a5
[ "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
4,150
lean
def Sequence (α : Type) := List α def BigBody (β α) := α × (β → β → β) × Bool × β def applyBig {α β : Type} (body : BigBody β α) (x : β) : β := let (_, op, b, v) := body; if b then op v x else x def reducebig {α β : Type} (idx : β) (r : Sequence α) (body : α → BigBody β α) : β := r.foldr (applyBig ∘ body) idx def bigop := @reducebig partial def iota : Nat → Nat → List Nat | m, 0 => [] | m, n+1 => m :: iota (m+1) n def index_iota (m n : Nat) := iota m (n - m) class Enumerable (α : Type) := (elems {} : List α) instance : Enumerable Bool := { elems := [false, true] } -- instance {α β} [Enumerable α] [Enumerable β]: Enumerable (α × β) := -- { elems := do let a ← Enumerable.elems α; let b ← Enumerable.elems β; pure (a, b) } partial def finElemsAux (n : Nat) : (i : Nat) → i < n → List (Fin n) | 0, h => [⟨0, h⟩] | i+1, h => ⟨i+1, h⟩ :: finElemsAux n i (Nat.ltOfSuccLt h) partial def finElems : (n : Nat) → List (Fin n) | 0 => [] | (n+1) => finElemsAux (n+1) n (Nat.ltSuccSelf n) instance {n} : Enumerable (Fin n) := { elems := (finElems n).reverse } instance : OfNat (Fin (Nat.succ n)) m := ⟨Fin.ofNat m⟩ -- Declare a new syntax category for "indexing" big operators declare_syntax_cat index syntax term:51 "≤" ident "<" term : index syntax term:51 "≤" ident "<" term "|" term : index syntax ident "<-" term : index syntax ident "<-" term "|" term : index -- Primitive notation for big operators syntax "_big" "[" term "," term "]" "(" index ")" term : term -- We define how to expand `_bigop` with the different kinds of index macro_rules | `(_big [$op, $idx] ($i:ident <- $r | $p) $F) => `(bigop $idx $r (fun $i:ident => ($i:ident, $op, $p, $F))) | `(_big [$op, $idx] ($i:ident <- $r) $F) => `(bigop $idx $r (fun $i:ident => ($i:ident, $op, true, $F))) | `(_big [$op, $idx] ($lower:term ≤ $i:ident < $upper) $F) => `(bigop $idx (index_iota $lower $upper) (fun $i:ident => ($i:ident, $op, true, $F))) | `(_big [$op, $idx] ($lower:term ≤ $i:ident < $upper | $p) $F) => `(bigop $idx (index_iota $lower $upper) (fun $i:ident => ($i:ident, $op, $p, $F))) -- Define `Sum` syntax "Sum" "(" index ")" term : term macro_rules | `(Sum ($idx) $F) => `(_big [Add.add, 0] ($idx) $F) -- We can already use `Sum` with the different kinds of index. #check Sum (i <- [0, 2, 4] | i != 2) i #check Sum (10 ≤ i < 20 | i != 5) i+1 #check Sum (10 ≤ i < 20) i+1 -- Define `Prod` syntax "Prod" "(" index ")" term : term macro_rules | `(Prod ($idx) $F) => `(_big [Mul.mul, 1] ($idx) $F) -- The examples above now also work for `Prod` #check Prod (i <- [0, 2, 4] | i != 2) i #check Prod (10 ≤ i < 20 | i != 5) i+1 #check Prod (10 ≤ i < 20) i+1 -- We can extend our grammar for the syntax category `index`. syntax ident "|" term : index syntax ident ":" term : index syntax ident ":" term "|" term : index -- And new rules macro_rules | `(_big [$op, $idx] ($i:ident : $type) $F) => `(bigop $idx (Enumerable.elems $type) (fun $i:ident => ($i:ident, $op, true, $F))) | `(_big [$op, $idx] ($i:ident : $type | $p) $F) => `(bigop $idx (Enumerable.elems $type) (fun $i:ident => ($i:ident, $op, $p, $F))) | `(_big [$op, $idx] ($i:ident | $p) $F) => `(bigop $idx (Enumerable.elems _) (fun $i:ident => ($i:ident, $op, $p, $F))) -- The new syntax is immediately available for all big operators that we have defined def myPred (x : Fin 10) : Bool := true #check Sum (i : Fin 10) i+1 #check Sum (i : Fin 10 | i != 2) i+1 #check Sum (i | myPred i) i+i #check Prod (i : Fin 10) i+1 #check Prod (i : Fin 10 | i != 2) i+1 #check Prod (i | myPred i) i+i -- We can easily create alternative syntax for any big operator. syntax "Σ" index "=>" term : term macro_rules | `(Σ $idx => $F) => `(Prod ($idx) $F) #check Σ 10 ≤ i < 20 => i+1 -- Now, we create command for automating the generation of big operators. syntax "def_bigop" str term:max term:max : command macro_rules | `(def_bigop $head:strLit $op $unit) => `(macro $head:strLit "(" idx:index ")" F:term : term => `(_big [$op, $unit] ($$idx) $$F)) def_bigop "SUM" Nat.add 0 #check SUM (i <- [0, 1, 2]) i+1
fa49568df94eb7f2f17825738232d6b124dcbcb2
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/linarith/datatypes.lean
d6f51ad71b34e9bf1d4535a00ae48014c4bc684f
[ "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
12,768
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import meta.rb_map import tactic.ring import tactic.linarith.lemmas /-! # Datatypes for `linarith` Some of the data structures here are used in multiple parts of the tactic. We split them into their own file. This file also contains a few convenient auxiliary functions. -/ declare_trace linarith open native namespace linarith /-- A shorthand for tracing when the `trace.linarith` option is set to true. -/ meta def linarith_trace {α} [has_to_tactic_format α] (s : α) : tactic unit := tactic.when_tracing `linarith (tactic.trace s) /-- A shorthand for tracing the types of a list of proof terms when the `trace.linarith` option is set to true. -/ meta def linarith_trace_proofs (s : string := "") (l : list expr) : tactic unit := tactic.when_tracing `linarith $ do tactic.trace s, l.mmap tactic.infer_type >>= tactic.trace /-! ### Linear expressions -/ /-- A linear expression is a list of pairs of variable indices and coefficients, representing the sum of the products of each coefficient with its corresponding variable. Some functions on `linexp` assume that `n : ℕ` occurs at most once as the first element of a pair, and that the list is sorted in decreasing order of the first argument. This is not enforced by the type but the operations here preserve it. -/ @[reducible] def linexp : Type := list (ℕ × ℤ) namespace linexp /-- Add two `linexp`s together componentwise. Preserves sorting and uniqueness of the first argument. -/ meta def add : linexp → linexp → linexp | [] a := a | a [] := a | (a@(n1,z1)::t1) (b@(n2,z2)::t2) := if n1 < n2 then b::add (a::t1) t2 else if n2 < n1 then a::add t1 (b::t2) else let sum := z1 + z2 in if sum = 0 then add t1 t2 else (n1, sum)::add t1 t2 /-- `l.scale c` scales the values in `l` by `c` without modifying the order or keys. -/ def scale (c : ℤ) (l : linexp) : linexp := if c = 0 then [] else if c = 1 then l else l.map $ λ ⟨n, z⟩, (n, z*c) /-- `l.get n` returns the value in `l` associated with key `n`, if it exists, and `none` otherwise. This function assumes that `l` is sorted in decreasing order of the first argument, that is, it will return `none` as soon as it finds a key smaller than `n`. -/ def get (n : ℕ) : linexp → option ℤ | [] := none | ((a, b)::t) := if a < n then none else if a = n then some b else get t /-- `l.contains n` is true iff `n` is the first element of a pair in `l`. -/ def contains (n : ℕ) : linexp → bool := option.is_some ∘ get n /-- `l.zfind n` returns the value associated with key `n` if there is one, and 0 otherwise. -/ def zfind (n : ℕ) (l : linexp) : ℤ := match l.get n with | none := 0 | some v := v end /-- `l.vars` returns the list of variables that occur in `l`. -/ def vars (l : linexp) : list ℕ := l.map prod.fst /-- Defines a lex ordering on `linexp`. This function is performance critical. -/ def cmp : linexp → linexp → ordering | [] [] := ordering.eq | [] _ := ordering.lt | _ [] := ordering.gt | ((n1,z1)::t1) ((n2,z2)::t2) := if n1 < n2 then ordering.lt else if n2 < n1 then ordering.gt else if z1 < z2 then ordering.lt else if z2 < z1 then ordering.gt else cmp t1 t2 end linexp /-! ### Inequalities -/ /-- The three-element type `ineq` is used to represent the strength of a comparison between terms. -/ @[derive decidable_eq, derive inhabited] inductive ineq : Type | eq | le | lt namespace ineq /-- `max R1 R2` computes the strength of the sum of two inequalities. If `t1 R1 0` and `t2 R2 0`, then `t1 + t2 (max R1 R2) 0`. -/ def max : ineq → ineq → ineq | lt a := lt | a lt := lt | le a := le | a le := le | eq eq := eq /-- `ineq` is ordered `eq < le < lt`. -/ def cmp : ineq → ineq → ordering | eq eq := ordering.eq | eq _ := ordering.lt | le le := ordering.eq | le lt := ordering.lt | lt lt := ordering.eq | _ _ := ordering.gt /-- Prints an `ineq` as the corresponding infix symbol. -/ def to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" /-- Finds the name of a multiplicative lemma corresponding to an inequality strength. -/ meta def to_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq instance : has_to_string ineq := ⟨ineq.to_string⟩ meta instance : has_to_format ineq := ⟨λ i, ineq.to_string i⟩ end ineq /-! ### Comparisons with 0 -/ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is `coeffs.sum (λ ⟨k, v⟩, v * Var[k])`. str determines the strength of the comparison -- is it < 0, ≤ 0, or = 0? -/ @[derive inhabited] structure comp : Type := (str : ineq) (coeffs : linexp) /-- `c.vars` returns the list of variables that appear in the linear expression contained in `c`. -/ def comp.vars : comp → list ℕ := linexp.vars ∘ comp.coeffs /-- `comp.coeff_of c a` projects the coefficient of variable `a` out of `c`. -/ def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a /-- `comp.scale c n` scales the coefficients of `c` by `n`. -/ def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.scale n } /-- `comp.add c1 c2` adds the expressions represented by `c1` and `c2`. The coefficient of variable `a` in `c1.add c2` is the sum of the coefficients of `a` in `c1` and `c2`. -/ meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ /-- `comp` has a lex order. First the `ineq`s are compared, then the `coeff`s. -/ meta def comp.cmp : comp → comp → ordering | ⟨str1, coeffs1⟩ ⟨str2, coeffs2⟩ := match str1.cmp str2 with | ordering.lt := ordering.lt | ordering.gt := ordering.gt | ordering.eq := coeffs1.cmp coeffs2 end /-- A `comp` represents a contradiction if its expression has no coefficients and its strength is <, that is, it represents the fact `0 < 0`. -/ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs ++ to_string p.str ++ "0"⟩ /-! ### Parsing into linear form -/ /-! ### Control -/ /-- A preprocessor transforms a proof of a proposition into a proof of a different propositon. The return type is `list expr`, since some preprocessing steps may create multiple new hypotheses, and some may remove a hypothesis from the list. A "no-op" preprocessor should return its input as a singleton list. -/ meta structure preprocessor : Type := (name : string) (transform : expr → tactic (list expr)) /-- Some preprocessors need to examine the full list of hypotheses instead of working item by item. As with `preprocessor`, the input to a `global_preprocessor` is replaced by, not added to, its output. -/ meta structure global_preprocessor : Type := (name : string) (transform : list expr → tactic (list expr)) /-- Some preprocessors perform branching case splits. A `branch` is used to track one of these case splits. The first component, an `expr`, is the goal corresponding to this branch of the split, given as a metavariable. The `list expr` component is the list of hypotheses for `linarith` in this branch. Every `expr` in this list should be type correct in the context of the associated goal. -/ meta def branch : Type := expr × list expr /-- Some preprocessors perform branching case splits. A `global_branching_preprocessor` produces a list of branches to run. Each branch is independent, so hypotheses that appear in multiple branches should be duplicated. The preprocessor is responsible for making sure that each branch contains the correct goal metavariable. -/ meta structure global_branching_preprocessor : Type := (name : string) (transform : list expr → tactic (list branch)) /-- A `preprocessor` lifts to a `global_preprocessor` by folding it over the input list. -/ meta def preprocessor.globalize (pp : preprocessor) : global_preprocessor := { name := pp.name, transform := list.mfoldl (λ ret e, do l' ← pp.transform e, return (l' ++ ret)) [] } /-- A `global_preprocessor` lifts to a `global_branching_preprocessor` by producing only one branch. -/ meta def global_preprocessor.branching (pp : global_preprocessor) : global_branching_preprocessor := { name := pp.name, transform := λ l, do g ← tactic.get_goal, singleton <$> prod.mk g <$> pp.transform l } /-- `process pp l` runs `pp.transform` on `l` and returns the result, tracing the result if `trace.linarith` is on. -/ meta def global_branching_preprocessor.process (pp : global_branching_preprocessor) (l : list expr) : tactic (list branch) := do l ← pp.transform l, when (l.length > 1) $ linarith_trace format!"Preprocessing: {pp.name} has branched, with branches:", l.mmap' $ λ l, tactic.set_goals [l.1] >> linarith_trace_proofs (to_string format!"Preprocessing: {pp.name}") l.2, return l meta instance preprocessor_to_gb_preprocessor : has_coe preprocessor global_branching_preprocessor := ⟨global_preprocessor.branching ∘ preprocessor.globalize⟩ meta instance global_preprocessor_to_gb_preprocessor : has_coe global_preprocessor global_branching_preprocessor := ⟨global_preprocessor.branching⟩ /-- A `certificate_oracle` is a function `produce_certificate : list comp → ℕ → tactic (rb_map ℕ ℕ)`. `produce_certificate hyps max_var` tries to derive a contradiction from the comparisons in `hyps` by eliminating all variables ≤ `max_var`. If successful, it returns a map `coeff : ℕ → ℕ` as a certificate. This map represents that we can find a contradiction by taking the sum `∑ (coeff i) * hyps[i]`. The default `certificate_oracle` used by `linarith` is `linarith.fourier_motzkin.produce_certificate` -/ meta def certificate_oracle : Type := list comp → ℕ → tactic (rb_map ℕ ℕ) /-- A configuration object for `linarith`. -/ meta structure linarith_config : Type := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . tactic.apply_instance) (exfalso : bool := tt) (transparency : tactic.transparency := reducible) (split_hypotheses : bool := tt) (split_ne : bool := ff) (preprocessors : option (list global_branching_preprocessor) := none) (oracle : option certificate_oracle := none) /-- `cfg.update_reducibility reduce_semi` will change the transparency setting of `cfg` to `semireducible` if `reduce_semi` is true. In this case, it also sets the discharger to `ring!`, since this is typically needed when using stronger unification. -/ meta def linarith_config.update_reducibility (cfg : linarith_config) (reduce_semi : bool) : linarith_config := if reduce_semi then { cfg with transparency := semireducible, discharger := `[ring!] } else cfg /-! ### Auxiliary functions These functions are used by multiple modules, so we put them here for accessibility. -/ open tactic /-- `get_rel_sides e` returns the left and right hand sides of `e` if `e` is a comparison, and fails otherwise. This function is more naturally in the `option` monad, but it is convenient to put in `tactic` for compositionality. -/ meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := tactic.failed /-- `parse_into_comp_and_expr e` checks if `e` is of the form `t < 0`, `t ≤ 0`, or `t = 0`. If it is, it returns the comparison along with `t`. -/ meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none /-- `mk_single_comp_zero_pf c h` assumes that `h` is a proof of `t R 0`. It produces a pair `(R', h')`, where `h'` is a proof of `c*t R' 0`. Typically `R` and `R'` will be the same, except when `c = 0`, in which case `R'` is `=`. If `c = 1`, `h'` is the same as `h` -- specifically, it does *not* change the type to `1*t R 0`. -/ meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (ineq.eq, e') else if c = 1 then return (iq, h) else do tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, c ← tp.of_nat c, cpos ← to_expr ``(%%c > 0), (_, ex) ← solve_aux cpos `[norm_num, done], e' ← mk_app iq.to_const_mul_nm [h, ex], return (iq, e') end linarith
e50ff62a398dd9b4eea61a0eb5a1eb1e70f1f9b9
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/group_theory/subgroup.lean
a267e1e784de103de4450f5b70bcc0811fa7a6cf
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,673
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, Mitchell Rowett, Scott Morrison -/ import group_theory.submonoid open set function variables {α : Type*} {β : Type*} {s : set α} {a a₁ a₂ b c: α} section group variable [group α] lemma injective_mul {a : α} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ class is_subgroup [group α] (s : set α) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) instance subtype.group {s : set α} [is_subgroup s] : group s := { inv := λa, ⟨(a.1)⁻¹, is_subgroup.inv_mem a.2⟩, mul_left_inv := assume ⟨a, _⟩, subtype.eq $ mul_left_inv _, .. subtype.monoid } theorem is_subgroup.of_div [group α] (s : set α) (one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s): is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } def gpowers (x : α) : set α := {y | ∃i:ℤ, x^i = y} instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩ end group namespace is_subgroup open is_submonoid variable (s) variables [group α] [is_subgroup s] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := iff.intro (assume h, have a⁻¹⁻¹ ∈ s, from inv_mem h, by simpa) inv_mem lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := iff.intro (assume hba, have (b * a) * a⁻¹ ∈ s, from mul_mem hba (inv_mem h), by simpa) (assume hb, mul_mem hb h) lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := iff.intro (assume hab, have a⁻¹ * (a * b) ∈ s, from mul_mem (inv_mem h) hab, by simpa) (mul_mem h) end is_subgroup namespace group open is_submonoid is_subgroup variable [group α] inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : α} : in_closure a → in_closure a⁻¹ | mul {a b : α} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := {a | in_closure s a } lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic instance closure.is_subgroup (s : set α) : is_subgroup (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } theorem subset_closure {s : set α} : s ⊆ closure s := assume a, in_closure.basic theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} := subset.antisymm (assume x h, match x, h with _, ⟨i, rfl⟩ := gpow_mem (mem_closure $ by simp) end) (closure_subset $ by simp [mem_gpowers]) end group class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s) namespace is_subgroup variable [group α] -- Normal subgroup properties lemma mem_norm_comm {a b : α} {s : set α} [normal_subgroup s] (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h lemma mem_norm_comm_iff {a b : α} {s : set α} [normal_subgroup s] : a * b ∈ s ↔ b * a ∈ s := iff.intro mem_norm_comm mem_norm_comm /-- The trivial subgroup -/ def trivial (α : Type*) [group α] : set α := {1} @[simp] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 := by simp [trivial] instance trivial_normal : normal_subgroup (trivial α) := by refine {..}; simp [trivial] {contextual := tt} lemma trivial_eq_closure : trivial α = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) instance univ_subgroup : normal_subgroup (@univ α) := by refine {..}; simp def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g} lemma mem_center {a : α} : a ∈ center α ↔ (∀g, g * a = a * g) := iff.refl _ instance center_normal : normal_subgroup (center α) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } end is_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup variables [group α] [group β] def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β) lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 := mem_trivial lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [mul f, inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←inv f, ←mul f] at this lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, mul f]⟩, one_mem := ⟨1, one_mem s, one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw inv f; simp *⟩ } instance range_subgroup (f : α → β) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [mul f, one f, inv f, @inv_mem β _ _ s] {contextual:=tt} instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [mul f, inv f] {contextual:=tt}⟩ instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial β) lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) : function.injective f := begin intros a₁ a₂ hfa, simp [set_eq_def, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) : ker f = trivial α := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.one f] {contextual := tt}) lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] : function.injective f ↔ ker f = trivial α := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ end is_group_hom
96b154f55909cce148c899e92096f8bc3ff6f26d
c777c32c8e484e195053731103c5e52af26a25d1
/src/control/monad/basic.lean
916599b5d74d17933258ebdb0603a8855f7ac89d
[ "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
2,832
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import logic.equiv.defs import tactic.basic /-! # Monad > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Attributes * ext * functor_norm * monad_norm ## Implementation Details Set of rewrite rules and automation for monads in general and `reader_t`, `state_t`, `except_t` and `option_t` in particular. The rewrite rules for monads are carefully chosen so that `simp with functor_norm` will not introduce monadic vocabulary in a context where applicatives would do just fine but will handle monadic notation already present in an expression. In a context where monadic reasoning is desired `simp with monad_norm` will translate functor and applicative notation into monad notation and use regular `functor_norm` rules as well. ## Tags functor, applicative, monad, simp -/ mk_simp_attribute monad_norm none with functor_norm attribute [ext] reader_t.ext state_t.ext except_t.ext option_t.ext attribute [functor_norm] bind_assoc pure_bind bind_pure attribute [monad_norm] seq_eq_bind_map universes u v @[monad_norm] lemma map_eq_bind_pure_comp (m : Type u → Type v) [monad m] [is_lawful_monad m] {α β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f := by rw bind_pure_comp_eq_map /-- run a `state_t` program and discard the final state -/ def state_t.eval {m : Type u → Type v} [functor m] {σ α} (cmd : state_t σ m α) (s : σ) : m α := prod.fst <$> cmd.run s universes u₀ u₁ v₀ v₁ /-- reduce the equivalence between two state monads to the equivalence between their respective function spaces -/ def state_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ σ₁ : Type u₀} {α₂ σ₂ : Type u₁} (F : (σ₁ → m₁ (α₁ × σ₁)) ≃ (σ₂ → m₂ (α₂ × σ₂))) : state_t σ₁ m₁ α₁ ≃ state_t σ₂ m₂ α₂ := { to_fun := λ ⟨f⟩, ⟨F f⟩, inv_fun := λ ⟨f⟩, ⟨F.symm f⟩, left_inv := λ ⟨f⟩, congr_arg state_t.mk $ F.left_inv _, right_inv := λ ⟨f⟩, congr_arg state_t.mk $ F.right_inv _ } /-- reduce the equivalence between two reader monads to the equivalence between their respective function spaces -/ def reader_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ ρ₁ : Type u₀} {α₂ ρ₂ : Type u₁} (F : (ρ₁ → m₁ α₁) ≃ (ρ₂ → m₂ α₂)) : reader_t ρ₁ m₁ α₁ ≃ reader_t ρ₂ m₂ α₂ := { to_fun := λ ⟨f⟩, ⟨F f⟩, inv_fun := λ ⟨f⟩, ⟨F.symm f⟩, left_inv := λ ⟨f⟩, congr_arg reader_t.mk $ F.left_inv _, right_inv := λ ⟨f⟩, congr_arg reader_t.mk $ F.right_inv _ }
67e4d991cc00ed95b0f2b162e8faae29baecfce5
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0720.lean
fa0822493965df63d16af6f66d1b159ccaaa1a94
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
554
lean
import data.list.basic open list universe u variables {α : Type} (x y z : α) (xs ys zs : list α) def mk_symm (xs : list α) := xs ++ reverse xs theorem reverse_mk_symm (xs : list α) : reverse (mk_symm xs) = mk_symm xs := by simp [mk_symm] section local attribute [simp] reverse_mk_symm example (xs ys : list ℕ) : reverse (xs ++ mk_symm ys) = mk_symm ys ++ reverse xs := by simp example (xs ys : list ℕ) (p : list ℕ → Prop) (h : p (reverse (xs ++ (mk_symm ys)))) : p (mk_symm ys ++ reverse xs) := by simp at h; assumption end
9ea402f0c0cd9f28787477671d4d500c0f8a1dbe
7cef822f3b952965621309e88eadf618da0c8ae9
/src/measure_theory/lebesgue_measure.lean
3232f8bcde2ae3ce675da122bd45a819a4259868
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
11,497
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 Lebesgue measure on the real line -/ import measure_theory.measure_space measure_theory.borel_space noncomputable theory open classical set lattice filter open nnreal (of_real) namespace measure_theory /-- Length of an interval. This is the largest monotonic function which correctly measures all intervals. -/ def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h : s ⊆ Ico a b), of_real (b - a) @[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 := le_zero_iff_eq.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma lebesgue_length_Ico (a b : ℝ) : lebesgue_length (Ico a b) = of_real (b - a) := begin refine le_antisymm (infi_le_of_le a $ infi_le_of_le b $ infi_le _ (by refl)) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂, exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : lebesgue_length s₁ ≤ lebesgue_length s₂ := infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩ lemma lebesgue_length_eq_infi_Ioo (s) : lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) := begin refine le_antisymm (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _, refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le (subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _), rw [← sub_add, ← ennreal.coe_add, ennreal.coe_le_coe], apply le_trans nnreal.of_real_add_le _, simp, end @[simp] lemma lebesgue_length_Ioo (a b : ℝ) : lebesgue_length (Ioo a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _, rw lebesgue_length_eq_infi_Ioo (Ioo a b), refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _), cases le_or_lt b a with ab ab, {simp [ab]}, cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂, rw [lebesgue_length_Ico, ennreal.coe_le_coe], exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_eq_infi_Icc (s) : lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) := begin refine le_antisymm _ (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩), refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le (subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _), rw [sub_eq_add_neg, add_right_comm, ←ennreal.coe_add, ennreal.coe_le_coe], apply le_trans nnreal.of_real_add_le, simp end @[simp] lemma lebesgue_length_Icc (a b : ℝ) : lebesgue_length (Icc a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self), rw lebesgue_length_eq_infi_Icc (Icc a b), exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp)) end /-- The Lebesgue outer measure, as an outer measure of ℝ. -/ def lebesgue_outer : outer_measure ℝ := outer_measure.of_function lebesgue_length lebesgue_length_empty lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s := outer_measure.of_function_le _ _ _ lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) : (of_real (b - a) : ennreal) ≤ ∑ i, of_real (d i - c i) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), (of_real (b - a) : ennreal) ≤ s.sum (λ i, of_real (d i - c i)), { rcases compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ), @is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]}, rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, have := cv ⟨ab, le_refl _⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left' (IH _ (finset.erase_ssubset is) (c i) _)), { rw [← ennreal.coe_add, ennreal.coe_le_coe], refine le_trans (nnreal.of_real_le_of_real _) nnreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (le_of_lt bd) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma lebesgue_outer_Icc (a b : ℝ) : lebesgue_outer (Icc a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length) (le_infi $ λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ennreal) < lebesgue_length (f i) + ε' i, { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo}, simpa [infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2), exact lebesgue_length_subadditive (subset.trans hf $ Union_subset_Union $ λ i, (hg i).1) end @[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 := by simpa using lebesgue_outer_Icc a a @[simp] lemma lebesgue_outer_Ico (a b : ℝ) : lebesgue_outer (Ico a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ico; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @nnreal.of_real_add_le (b - a - ε) ε, rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_right_comm, ← lebesgue_outer_Icc a (b-ε), nnreal.of_real_coe] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Icc_subset_Ico_right $ (sub_lt_self_iff _).2 ε0) end @[simp] lemma lebesgue_outer_Ioo (a b : ℝ) : lebesgue_outer (Ioo a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ioo; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @nnreal.of_real_add_le (b - a - ε) ε, rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_sub, ← lebesgue_outer_Ico (a+ε) b, nnreal.of_real_coe] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Ico_subset_Ioo_left $ (lt_add_iff_pos_right _).2 ε0) end lemma is_lebesgue_measurable_Iio {c : ℝ} : lebesgue_outer.caratheodory.is_measurable (Iio c) := outer_measure.caratheodory_is_measurable $ λ t, le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin refine le_trans (add_le_add' (lebesgue_length_mono $ inter_subset_inter_left _ h) (lebesgue_length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hca; cases le_total b c with hbc hcb; simp [*, -sub_eq_add_neg, sub_add_sub_cancel']; rw [← ennreal.coe_add, ennreal.coe_le_coe], { simp [*, -nnreal.of_real_add, nnreal.of_real_add_of_real, -sub_eq_add_neg, sub_add_sub_cancel'] }, { rw nnreal.of_real_of_nonpos, { simp }, exact sub_nonpos.2 (le_trans hbc hca) } end theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer := begin refine le_antisymm (λ s, _) (outer_measure.trim_ge _), rw outer_measure.trim_eq_infi, refine le_infi (λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ s, f i ⊆ s ∧ is_measurable s ∧ lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← lebesgue_outer_Ico at h₂, exact ⟨_, h₁, is_measurable_Ico, le_of_lt $ by simpa using h₂⟩ }, simp at hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)) _, apply infi_le_of_le (is_measurable.Union (λ i, (hg i).2.1)) _, exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end /-- Lebesgue measure on the Borel sets The outer Lebesgue measure is the completion of this measure. (TODO: proof this) -/ instance : measure_space ℝ := ⟨{to_outer_measure := lebesgue_outer, m_Union := have borel ℝ ≤ lebesgue_outer.caratheodory, by rw real.borel_eq_generate_from_Iio_rat; refine measurable_space.generate_from_le _; simp [is_lebesgue_measurable_Iio] {contextual := tt}, λ f hf, lebesgue_outer.Union_eq_of_caratheodory (λ i, this _ (hf i)), trimmed := lebesgue_outer_trim }⟩ @[simp] theorem lebesgue_to_outer_measure : (measure_space.μ : measure ℝ).to_outer_measure = lebesgue_outer := rfl theorem real.volume_val (s) : volume s = lebesgue_outer s := rfl local attribute [simp] real.volume_val @[simp] lemma real.volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp @[simp] lemma real.volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp @[simp] lemma real.volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp @[simp] lemma real.volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp /- section vitali def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ∃ y ∈ Icc (0:ℝ) 1, ∃ q:ℚ, ↑q = x - y := ⟨x, h, 0, by simp⟩ def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ := classical.some (vitali_aux_h x h) theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 := Exists.fst (classical.some_spec (vitali_aux_h x h):_) theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ∃ q:ℚ, ↑q = x - vitali_aux x h := Exists.snd (classical.some_spec (vitali_aux_h x h):_) def vitali : set ℝ := {x | ∃ h, x = vitali_aux x h} theorem vitali_nonmeasurable : ¬ is_null_measurable measure_space.μ vitali := sorry end vitali -/ end measure_theory
36f05384e37e4f2d1fd507971fce1117262cda2d
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/hash.lean
0fb3fb78960ddc489e4494ffbeeeeca26af48b76
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
245
lean
definition id1 {A : Type} (a : A) : A := a definition id2 (A : Type) (a : A) : A := a (* local t1 = get_env():find("id1"):type() local t2 = get_env():find("id2"):type() assert(t1:hash() == t2:hash()) assert(t1:hash_bi() ~= t2:hash_bi()) *)
dd1de64a64cb880ae311b14b1bd7d5a7d1c601b3
90323904e6ca77359449e3800bdf2f32ac4c0898
/johnstone.lean
97464e16717e46e117d6cc04d5ef678e06673d49
[]
no_license
XiaohuWang0921/johnstone
77bc5173c37e1a6530e777691b98993c17470b22
fd2e6800643b8a9f2a1d97591319ec444e1a4681
refs/heads/master
1,679,196,086,807
1,615,292,273,000
1,615,292,273,000
341,864,701
1
0
null
null
null
null
UTF-8
Lean
false
false
2,222
lean
universes u v def monic {α : Type u} {β : Type v} (f : α → β) := ∀ x y, f x = f y → x = y section johnstone open true variables (p : Prop) (φ : Prop → Prop) (μ : monic φ) theorem johnstone : φ (φ p) = p := let UT := {q // φ q}, VT := {q // φ q ∧ q}, UP := ∃ q, φ q, VP := ∃ q, φ q ∧ q, h₀ (w : φ true) : VP := ⟨true, w, intro⟩, h₁ : VP → φ true := λ ⟨_, w₀, w₁⟩, eq.rec w₀ $ propext ⟨(λ _, intro), (λ _, w₁)⟩, h₂ : φ true = VP := propext ⟨h₀, h₁⟩, h₃ : ∀ t : UT, t.val → VP := λ ⟨q, w₀⟩ w₁, ⟨q, w₀, w₁⟩, h₄ : ∀ t : UT, VP → t.val := λ ⟨q₀, w₀⟩ ⟨q₁, w₁, w₂⟩, @eq.rec Prop q₁ id w₂ q₀ $ μ q₁ q₀ $ propext ⟨(λ _, w₀), (λ _, w₁)⟩, h₅ (t : UT) : t.val = VP := propext ⟨h₃ t, h₄ t⟩, h₆ (w : φ VP) : UP := ⟨VP, w⟩, h₇ : UP → φ VP := λ ⟨q, w⟩, eq.rec w $ h₅ ⟨q, w⟩, h₈ : φ VP = UP := propext ⟨h₆, h₇⟩, h₉ : ∀ t : UT, t.val → t.val = UP := λ ⟨q, w₀⟩ w₁, propext ⟨(λ _, ⟨q, w₀⟩), (λ _, w₁)⟩, h₁₀ (w : φ true) : φ UP := eq.rec w $ h₉ ⟨true, w⟩ intro, h₁₁ (w : φ UP) : φ true := h₁ ⟨UP, w, UP, w⟩, h₁₂ : φ UP = φ true := propext ⟨h₁₁, h₁₀⟩, h₁₃ : UP = true := μ UP true h₁₂, h₁₄ : φ (φ true) = true := trans (congr (eq.refl φ) h₂) $ trans h₈ h₁₃, h₁₅ (w : φ $ φ p) : p := @eq.rec Prop true id intro p $ μ true p $ μ (φ true) (φ p) $ trans h₁₄ $ propext ⟨(λ _, w), (λ _, intro)⟩, h₁₆ (w : p) : φ $ φ p := @eq.rec Prop true id intro (φ $ φ p) $ trans (symm h₁₄) $ congr (eq.refl φ) $ congr (eq.refl φ) $ propext ⟨(λ _, w), (λ _, intro)⟩ in propext ⟨h₁₅, h₁₆⟩ end johnstone
1391fd759b59e3fc73dcbe00c9144827f39c1818
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo2006_q3.lean
8e3a0862d3ad4fe0b93a8f2c0d0ae2fcc34090ec
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,518
lean
/- Copyright (c) 2021 Tian Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tian Chen -/ import analysis.special_functions.sqrt /-! # IMO 2006 Q3 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Determine the least real number $M$ such that $$ \left| ab(a^2 - b^2) + bc(b^2 - c^2) + ca(c^2 - a^2) \right| ≤ M (a^2 + b^2 + c^2)^2 $$ for all real numbers $a$, $b$, $c$. ## Solution The answer is $M = \frac{9 \sqrt 2}{32}$. This is essentially a translation of the solution in https://web.evanchen.cc/exams/IMO-2006-notes.pdf. It involves making the substitution `x = a - b`, `y = b - c`, `z = c - a`, `s = a + b + c`. -/ open real namespace imo2006_q3 /-- Replacing `x` and `y` with their average increases the left side. -/ lemma lhs_ineq {x y : ℝ} (hxy : 0 ≤ x * y) : 16 * x ^ 2 * y ^ 2 * (x + y) ^ 2 ≤ ((x + y) ^ 2) ^ 3 := begin conv_rhs { rw pow_succ' }, refine mul_le_mul_of_nonneg_right _ (sq_nonneg _), apply le_of_sub_nonneg, calc ((x + y) ^ 2) ^ 2 - 16 * x ^ 2 * y ^ 2 = (x - y) ^ 2 * ((x + y) ^ 2 + 4 * (x * y)) : by ring ... ≥ 0 : mul_nonneg (sq_nonneg _) $ add_nonneg (sq_nonneg _) $ mul_nonneg zero_lt_four.le hxy end lemma four_pow_four_pos : (0 : ℝ) < 4 ^ 4 := pow_pos zero_lt_four _ lemma mid_ineq {s t : ℝ} : s * t ^ 3 ≤ (3 * t + s) ^ 4 / 4 ^ 4 := (le_div_iff four_pow_four_pos).mpr $ le_of_sub_nonneg $ calc (3 * t + s) ^ 4 - s * t ^ 3 * 4 ^ 4 = (s - t) ^ 2 * ((s + 7 * t) ^ 2 + 2 * (4 * t) ^ 2) : by ring ... ≥ 0 : mul_nonneg (sq_nonneg _) $ add_nonneg (sq_nonneg _) $ mul_nonneg zero_le_two (sq_nonneg _) /-- Replacing `x` and `y` with their average decreases the right side. -/ lemma rhs_ineq {x y : ℝ} : 3 * (x + y) ^ 2 ≤ 2 * (x ^ 2 + y ^ 2 + (x + y) ^ 2) := le_of_sub_nonneg $ calc _ = (x - y) ^ 2 : by ring ... ≥ 0 : sq_nonneg _ lemma zero_lt_32 : (0 : ℝ) < 32 := by norm_num theorem subst_wlog {x y z s : ℝ} (hxy : 0 ≤ x * y) (hxyz : x + y + z = 0) : 32 * |x * y * z * s| ≤ sqrt 2 * (x^2 + y^2 + z^2 + s^2)^2 := have hz : (x + y)^2 = z^2 := neg_eq_of_add_eq_zero_right hxyz ▸ (neg_sq _).symm, have hs : 0 ≤ 2 * s ^ 2 := mul_nonneg zero_le_two (sq_nonneg s), have this : _ := calc (2 * s^2) * (16 * x^2 * y^2 * (x + y)^2) ≤ (3 * (x + y)^2 + 2 * s^2)^4 / 4^4 : le_trans (mul_le_mul_of_nonneg_left (lhs_ineq hxy) hs) mid_ineq ... ≤ (2 * (x^2 + y^2 + (x + y)^2) + 2 * s^2)^4 / 4^4 : div_le_div_of_le four_pow_four_pos.le $ pow_le_pow_of_le_left (add_nonneg (mul_nonneg zero_lt_three.le (sq_nonneg _)) hs) (add_le_add_right rhs_ineq _) _, le_of_pow_le_pow _ (mul_nonneg (sqrt_nonneg _) (sq_nonneg _)) nat.succ_pos' $ calc (32 * |x * y * z * s|) ^ 2 = 32 * ((2 * s^2) * (16 * x^2 * y^2 * (x + y)^2)) : by rw [mul_pow, sq_abs, hz]; ring ... ≤ 32 * ((2 * (x^2 + y^2 + (x + y)^2) + 2 * s^2)^4 / 4^4) : mul_le_mul_of_nonneg_left this zero_lt_32.le ... = (sqrt 2 * (x^2 + y^2 + z^2 + s^2)^2)^2 : by rw [mul_pow, sq_sqrt zero_le_two, hz, ←pow_mul, ←mul_add, mul_pow, ←mul_comm_div, ←mul_assoc, show 32 / 4 ^ 4 * 2 ^ 4 = (2 : ℝ), by norm_num, show 2 * 2 = 4, by refl] /-- Proof that `M = 9 * sqrt 2 / 32` works with the substitution. -/ theorem subst_proof₁ (x y z s : ℝ) (hxyz : x + y + z = 0) : |x * y * z * s| ≤ sqrt 2 / 32 * (x^2 + y^2 + z^2 + s^2)^2 := begin wlog h' : 0 ≤ x * y generalizing x y z, swap, { rw [div_mul_eq_mul_div, le_div_iff' zero_lt_32], exact subst_wlog h' hxyz }, cases (mul_nonneg_of_three x y z).resolve_left h' with h h, { specialize this y z x _ h, { rw ← hxyz, ring, }, { convert this using 2; ring } }, { specialize this z x y _ h, { rw ← hxyz, ring, }, { convert this using 2; ring } }, end lemma lhs_identity (a b c : ℝ) : a * b * (a^2 - b^2) + b * c * (b^2 - c^2) + c * a * (c^2 - a^2) = (a - b) * (b - c) * (c - a) * -(a + b + c) := by ring theorem proof₁ {a b c : ℝ} : |a * b * (a^2 - b^2) + b * c * (b^2 - c^2) + c * a * (c^2 - a^2)| ≤ 9 * sqrt 2 / 32 * (a^2 + b^2 + c^2)^2 := calc _ = _ : congr_arg _ $ lhs_identity a b c ... ≤ _ : subst_proof₁ (a - b) (b - c) (c - a) (-(a + b + c)) (by ring) ... = _ : by ring theorem proof₂ (M : ℝ) (h : ∀ a b c : ℝ, |a * b * (a^2 - b^2) + b * c * (b^2 - c^2) + c * a * (c^2 - a^2)| ≤ M * (a^2 + b^2 + c^2)^2) : 9 * sqrt 2 / 32 ≤ M := begin have h₁ : ∀ x : ℝ, (2 - 3 * x - 2) * (2 - (2 + 3 * x)) * (2 + 3 * x - (2 - 3 * x)) * -(2 - 3 * x + 2 + (2 + 3 * x)) = -(18 ^ 2 * x ^ 2 * x), { intro, ring }, have h₂ : ∀ x : ℝ, (2 - 3 * x) ^ 2 + 2 ^ 2 + (2 + 3 * x) ^ 2 = 18 * x ^ 2 + 12, { intro, ring }, have := h (2 - 3 * sqrt 2) 2 (2 + 3 * sqrt 2), rw [lhs_identity, h₁, h₂, sq_sqrt zero_le_two, abs_neg, abs_eq_self.mpr, ← div_le_iff] at this, { convert this using 1, ring }, { apply pow_pos, norm_num }, { exact mul_nonneg (mul_nonneg (sq_nonneg _) zero_le_two) (sqrt_nonneg _) } end end imo2006_q3 open imo2006_q3 theorem imo2006_q3 (M : ℝ) : (∀ a b c : ℝ, |a * b * (a^2 - b^2) + b * c * (b^2 - c^2) + c * a * (c^2 - a^2)| ≤ M * (a^2 + b^2 + c^2)^2) ↔ 9 * sqrt 2 / 32 ≤ M := ⟨proof₂ M, λ h _ _ _, le_trans proof₁ $ mul_le_mul_of_nonneg_right h $ sq_nonneg _⟩
041e6fe91453acb60aaca504da736d739d2265f3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/fin_category_auto.lean
a89d55edd2ddfcf90bc22c536e342d3e70f23ffd
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,520
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.basic import Mathlib.category_theory.discrete_category import Mathlib.PostPort universes u_1 v l namespace Mathlib /-! # Finite categories A category is finite in this sense if it has finitely many objects, and finitely many morphisms. ## Implementation We also ask for decidable equality of objects and morphisms, but it may be reasonable to just go classical in future. -/ namespace category_theory protected instance discrete_fintype {α : Type u_1} [fintype α] : fintype (discrete α) := id _inst_1 protected instance discrete_hom_fintype {α : Type u_1} [DecidableEq α] (X : discrete α) (Y : discrete α) : fintype (X ⟶ Y) := ulift.fintype (plift (X = Y)) /-- A category with a `fintype` of objects, and a `fintype` for each morphism space. -/ class fin_category (J : Type v) [small_category J] where decidable_eq_obj : autoParam (DecidableEq J) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) fintype_obj : autoParam (fintype J) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) decidable_eq_hom : autoParam ((j j' : J) → DecidableEq (j ⟶ j')) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) fintype_hom : autoParam ((j j' : J) → fintype (j ⟶ j')) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) -- We need a `decidable_eq` instance here to construct `fintype` on the morphism spaces. protected instance fin_category_discrete_of_decidable_fintype (J : Type v) [DecidableEq J] [fintype J] : fin_category (discrete J) := fin_category.mk end Mathlib
25a947eec57c5a9b625903b1f3922d8d7ff6b83c
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/section4.lean
5cb4da3b24695fc7aaf4571ecee800524cef0f44
[ "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
635
lean
set_option pp.universes true set_option pp.implicit true section universe k parameter A : Type section universe variable l universe variable u parameter B : Type definition foo (a : A) (b : B) := b inductive mypair | mk : A → B → mypair print mypair.rec check mypair.mk definition pr1' : mypair → A | (mypair.mk a b) := a definition pr2' : mypair → B | (mypair.mk a b) := b end check mypair.rec variable a : A check foo num a 0 definition pr1 : mypair num → A | (mypair.mk a b) := a definition pr2 : mypair num → num | (mypair.mk a b) := b end
1999518532d0916bffbea9797d332f5941ff5e6c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/sites/adjunction.lean
c4cea48c75f04bc36d21300323a2bb2790bc366f
[ "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,076
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.sites.compatible_sheafification import category_theory.adjunction.whiskering /-! In this file, we show that an adjunction `F ⊣ G` induces an adjunction between categories of sheaves, under certain hypotheses on `F` and `G`. -/ namespace category_theory open category_theory.grothendieck_topology open category_theory open category_theory.limits open opposite universes w₁ w₂ v u variables {C : Type u} [category.{v} C] (J : grothendieck_topology C) variables {D : Type w₁} [category.{max v u} D] variables {E : Type w₂} [category.{max v u} E] variables {F : D ⥤ E} {G : E ⥤ D} variables [∀ (X : C) (S : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (S.index P).multicospan F] variables [concrete_category.{max v u} D] [preserves_limits (forget D)] /-- The forgetful functor from `Sheaf J D` to sheaves of types, for a concrete category `D` whose forgetful functor preserves the correct limits. -/ abbreviation Sheaf_forget : Sheaf J D ⥤ SheafOfTypes J := Sheaf_compose J (forget D) ⋙ (Sheaf_equiv_SheafOfTypes J).functor -- We need to sheafify... variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)] [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)] [reflects_isomorphisms (forget D)] namespace Sheaf noncomputable theory /-- This is the functor sending a sheaf `X : Sheaf J E` to the sheafification of `X ⋙ G`. -/ abbreviation compose_and_sheafify (G : E ⥤ D) : Sheaf J E ⥤ Sheaf J D := Sheaf_to_presheaf J E ⋙ (whiskering_right _ _ _).obj G ⋙ presheaf_to_Sheaf J D /-- An auxiliary definition to be used in defining `category_theory.Sheaf.adjunction` below. -/ @[simps] def compose_equiv (adj : G ⊣ F) (X : Sheaf J E) (Y : Sheaf J D) : ((compose_and_sheafify J G).obj X ⟶ Y) ≃ (X ⟶ (Sheaf_compose J F).obj Y) := let A := adj.whisker_right Cᵒᵖ in { to_fun := λ η, ⟨A.hom_equiv _ _ (J.to_sheafify _ ≫ η.val)⟩, inv_fun := λ γ, ⟨J.sheafify_lift ((A.hom_equiv _ _).symm ((Sheaf_to_presheaf _ _).map γ)) Y.2⟩, left_inv := begin intros η, ext1, dsimp, symmetry, apply J.sheafify_lift_unique, rw equiv.symm_apply_apply, end, right_inv := begin intros γ, ext1, dsimp, rw [J.to_sheafify_sheafify_lift, equiv.apply_symm_apply], end } /-- An adjunction `adj : G ⊣ F` with `F : D ⥤ E` and `G : E ⥤ D` induces an adjunction between `Sheaf J D` and `Sheaf J E`, in contexts where one can sheafify `D`-valued presheaves, and `F` preserves the correct limits. -/ @[simps unit_app_val counit_app_val] def adjunction (adj : G ⊣ F) : compose_and_sheafify J G ⊣ Sheaf_compose J F := adjunction.mk_of_hom_equiv { hom_equiv := compose_equiv J adj, hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext1, dsimp, simp }, hom_equiv_naturality_right' := λ X Y Y' f g, by { ext1, dsimp, simp } } instance [is_right_adjoint F] : is_right_adjoint (Sheaf_compose J F) := ⟨_, adjunction J (adjunction.of_right_adjoint F)⟩ section forget_to_type /-- This is the functor sending a sheaf of types `X` to the sheafification of `X ⋙ G`. -/ abbreviation compose_and_sheafify_from_types (G : Type (max v u) ⥤ D) : SheafOfTypes J ⥤ Sheaf J D := (Sheaf_equiv_SheafOfTypes J).inverse ⋙ compose_and_sheafify _ G /-- A variant of the adjunction between sheaf categories, in the case where the right adjoint is the forgetful functor to sheaves of types. -/ def adjunction_to_types {G : Type (max v u) ⥤ D} (adj : G ⊣ forget D) : compose_and_sheafify_from_types J G ⊣ Sheaf_forget J := ((Sheaf_equiv_SheafOfTypes J).symm.to_adjunction).comp (adjunction J adj) @[simp] lemma adjunction_to_types_unit_app_val {G : Type (max v u) ⥤ D} (adj : G ⊣ forget D) (Y : SheafOfTypes J) : ((adjunction_to_types J adj).unit.app Y).val = (adj.whisker_right _).unit.app ((SheafOfTypes_to_presheaf J).obj Y) ≫ whisker_right (J.to_sheafify _) (forget D) := begin dsimp [adjunction_to_types, adjunction.comp], simpa, end @[simp] lemma adjunction_to_types_counit_app_val {G : Type (max v u) ⥤ D} (adj : G ⊣ forget D) (X : Sheaf J D) : ((adjunction_to_types J adj).counit.app X).val = J.sheafify_lift ((functor.associator _ _ _).hom ≫ (adj.whisker_right _).counit.app _) X.2 := begin dsimp [adjunction_to_types, adjunction.comp, adjunction.whisker_right], rw category.id_comp, apply J.sheafify_lift_unique, rw [adjunction_counit_app_val, J.sheafify_map_sheafify_lift, J.to_sheafify_sheafify_lift], ext, dsimp [Sheaf_equiv_SheafOfTypes, equivalence.symm, equivalence.to_adjunction, nat_iso.of_components], simp, end instance [is_right_adjoint (forget D)] : is_right_adjoint (Sheaf_forget J) := ⟨_, adjunction_to_types J (adjunction.of_right_adjoint (forget D))⟩ end forget_to_type end Sheaf end category_theory
32f3ca3281bfa1ef3f133afc24ba48bddad612bd
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/algebra/infinite_sum.lean
2902483670a9b42840bc731d01ac55c20f03622e
[ "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
48,312
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.intervals import topology.instances.real import topology.algebra.module import data.indicator_function import data.equiv.encodable.lattice import data.nat.parity import order.filter.at_top_bot /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators nnreal variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 -- see Note [operator precedence of big operators] notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 := by simp [tsum, h] lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator_subset] @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) : has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a := (equiv.of_injective g hg).has_sum_iff.symm lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ g.map_sum _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := ⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩ variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff]) (by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp, forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum (f ∘ coe : s ∪ t → α) (a + b) := begin rw has_sum_subtype_iff_indicator at *, rw set.indicator_union_of_disjoint hs, exact ha.add hb end lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum f (a + b) := by simpa [← hs.compl_eq] using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl hb lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl.symm hb lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a) (ho : has_sum (λ k, f (2 * k + 1)) b) : has_sum f (a + b) := begin have := mul_right_injective' (@two_ne_zero ℕ _ _), replace he := this.has_sum_range_iff.2 he, replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho, refine he.add_is_compl _ ho, simpa [(∘)] using nat.is_compl_even_odd end lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : summable f := (he.has_sum.even_add_odd ho.has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : ∑'b:β, (0:α) = 0 := has_sum_zero.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : ∑' b, f b = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α] {f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b := congr_arg tsum (funext hfg) lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b := (has_sum_fintype f).tsum_eq @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : ∑' x : {x // x ∈ s}, f x = ∑ x in s, f x := (s.has_sum f).tsum_eq @[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) : ∑' x : (s : set β), f x = ∑ x in s, f x := s.tsum_subtype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : ∑'b, f b = f b := (has_sum_single b hf).tsum_eq @[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : ∑' b', (if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) : ∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h := by by_cases hP : P; simp [hP] lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) : ∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 := by by_cases hP : P; simp [hP] lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : ∑' b, f b = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : ∑'b, f b = ∑'c, g c := (equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : ∑' x, f x = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : ∑' x:s, f x = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : ∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : ∑'p, f p = ∑'b c, f (b, c) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : ∑' c b, f b c = ∑' b c, f b c := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section encodable open encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode2 [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode2 γ i, s b) = ∑' b : γ, m (s b) := begin have H : ∀ n, m (⨆ b ∈ decode2 γ n, s b) ≠ 0 → (decode2 γ n).is_some, { intros n h, cases decode2 γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek2] at h ⊢, convert h, simp [set.ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode2 γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode2 (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : ∑' i, m (⋃ b ∈ decode2 γ i, s b) = ∑' b, m (s b) := tsum_supr_decode2 m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i)) (s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) := by { rw [← supr_decode2, ← tsum_supr_decode2 _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable variables [has_continuous_add α] lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t) (hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) : (∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) := (hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : (∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k := (he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm end tsum section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp [has_sum, tendsto_pi] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp [summable, pi.has_sum, classical.skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) : has_sum (update f b a) (a - f b + a₁) := begin convert ((has_sum_ite_eq b _).add hf), ext b', by_cases h : b' = b, { rw h, simp, }, { simp [h] }, end lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) : summable (update f b a) := (hf.has_sum.update b a).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : ∑'b, - f b = - ∑'b, f b := hf.has_sum.neg.tsum_eq lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b := (hf.has_sum.sub hg.has_sum).tsum_eq lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i := by simpa [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : ∑'b, f b = f 0 + ∑'b, f (b + 1) := by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin by_cases hf : summable f, { have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i), { ext1 i, rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] }, have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds, simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat }, { convert tendsto_const_nhds, ext1 i, rw ← summable_nat_add_iff i at hf, { exact tsum_eq_zero_of_not_summable hf }, { apply_instance } } end end subtype end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma summable.tsum_mul_left (a) (hf : summable f) : ∑'b, a * f b = a * ∑'b, f b := (hf.has_sum.mul_left _).tsum_eq lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq end tsum end topological_semiring section has_continuous_smul variables {R : Type*} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [has_continuous_smul R α] {f : β → α} lemma has_sum.smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) := hf.map (const_smul_hom α r) (continuous_const.smul continuous_id) lemma summable.smul {r : R} (hf : summable f) : summable (λ z, r • f z) := hf.has_sum.smul.summable lemma tsum_smul [t2_space α] {r : R} (hf : summable f) : ∑' z, r • f z = r • ∑' z, f z := hf.has_sum.smul.tsum_eq end has_continuous_smul section division_ring variables [division_ring α] [topological_space α] [topological_semiring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.div_const (h : has_sum f a) (b : α) : has_sum (λ x, f x / b) (a / b) := by simp only [div_eq_mul_inv, h.mul_right b⁻¹] lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a⁻¹⟩ lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x := if hf : summable f then hf.tsum_mul_left a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero] lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a := if hf : summable f then hf.tsum_mul_right a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul] end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b @[mono] lemma has_sum_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f ≤ g) : a₁ ≤ a₂ := has_sum_le h hf hg lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ tsum f := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : ∑'b, f b ≤ ∑'b, g b := has_sum_le h hf.has_sum hg.has_sum @[mono] lemma tsum_mono (hf : summable f) (hg : summable g) (h : f ≤ g) : ∑' n, f n ≤ ∑' n, g n := tsum_le_tsum h hf hg lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ ∑'b, g b := begin by_cases hg : summable g, { exact hg.has_sum.nonneg h }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : ∑'b, f b ≤ 0 := begin by_cases hf : summable f, { exact hf.has_sum.nonpos h }, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section ordered_topological_group variables [ordered_add_comm_group α] [topological_space α] [topological_add_group α] [order_closed_topology α] {f g : β → α} {a₁ a₂ : α} lemma has_sum_lt {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ < a₂ := have update f i 0 ≤ update g i 0 := update_le_update_iff.mpr ⟨rfl.le, λ i _, h i⟩, have 0 - f i + a₁ ≤ 0 - g i + a₂ := has_sum_le this (hf.update i 0) (hg.update i 0), by simpa only [zero_sub, add_neg_cancel_left] using add_lt_add_of_lt_of_le hi this @[mono] lemma has_sum_strict_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f < g) : a₁ < a₂ := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : summable f) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi hf.has_sum hg.has_sum @[mono] lemma tsum_strict_mono (hf : summable f) (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hf hg end ordered_topological_group section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] lemma tsum_ne_zero_iff (hf : summable f) : ∑' i, f i ≠ 0 ↔ ∃ x, f x ≠ 0 := by rw [ne.def, tsum_eq_zero_iff hf, not_forall] end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [regular_space α] {f : β × γ → α} (h : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_prod' h h.prod_factor lemma tsum_comm [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : ∑' c b, f b c = ∑' b c, f b c := tsum_comm' h h.prod_factor h.prod_symm.prod_factor /-- Let `f : ℕ → ℝ` be a sequence with summable series and let `i ∈ ℕ` be an index. Lemma `tsum_ite_eq_extract` writes `Σ f n` as the sum of `f i` plus the series of the remaining terms. TODO: generalize this to `f : β → α` with appropriate typeclass assumptions -/ lemma tsum_ite_eq_extract {f : ℕ → ℝ} (hf : summable f) (i : ℕ) : ∑' n, f n = f i + ∑' n, ite (n = i) 0 (f n) := begin refine ((tsum_congr _).trans $ tsum_add (hf.summable_of_eq_zero_or_self _) $ hf.summable_of_eq_zero_or_self _).trans (add_right_cancel_iff.mpr (tsum_ite_eq i (f i))); exact λ j, by { by_cases ji : j = i; simp [ji] } end end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (singleton_disjoint.2 hx) end lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero } end topological_group lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, abs (f x)) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, abs (f x) = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, abs (f x) = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, abs (f x)) ↔ summable (λ x : {x | 0 ≤ f x}, abs (f x)) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, abs (f x)) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs section cauchy_seq open finset.Ico filter /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ abs (∑ x in Ico N n, d x) : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq
efa26ff6d3a716d966ee9785259fad800a73ff48
c777c32c8e484e195053731103c5e52af26a25d1
/src/order/liminf_limsup.lean
adafe31cd2008009231ba1afd838d648727558e3
[ "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
45,350
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johannes Hölzl, Rémy Degenne -/ import order.filter.cofinite import order.hom.complete_lattice /-! # liminfs and limsups of functions and filters > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Defines the Liminf/Limsup of a function taking values in a conditionally complete lattice, with respect to an arbitrary filter. We define `Limsup f` (`Liminf f`) where `f` is a filter taking values in a conditionally complete lattice. `Limsup f` is the smallest element `a` such that, eventually, `u ≤ a` (and vice versa for `Liminf f`). To work with the Limsup along a function `u` use `Limsup (map u f)`. Usually, one defines the Limsup as `Inf (Sup s)` where the Inf is taken over all sets in the filter. For instance, in ℕ along a function `u`, this is `Inf_n (Sup_{k ≥ n} u k)` (and the latter quantity decreases with `n`, so this is in fact a limit.). There is however a difficulty: it is well possible that `u` is not bounded on the whole space, only eventually (think of `Limsup (λx, 1/x)` on ℝ. Then there is no guarantee that the quantity above really decreases (the value of the `Sup` beforehand is not really well defined, as one can not use ∞), so that the Inf could be anything. So one can not use this `Inf Sup ...` definition in conditionally complete lattices, and one has to use a less tractable definition. In conditionally complete lattices, the definition is only useful for filters which are eventually bounded above (otherwise, the Limsup would morally be +∞, which does not belong to the space) and which are frequently bounded below (otherwise, the Limsup would morally be -∞, which is not in the space either). We start with definitions of these concepts for arbitrary filters, before turning to the definitions of Limsup and Liminf. In complete lattices, however, it coincides with the `Inf Sup` definition. -/ open filter set open_locale filter variables {α β γ ι : Type*} namespace filter section relation /-- `f.is_bounded (≺)`: the filter `f` is eventually bounded w.r.t. the relation `≺`, i.e. eventually, it is bounded by some uniform bound. `r` will be usually instantiated with `≤` or `≥`. -/ def is_bounded (r : α → α → Prop) (f : filter α) := ∃ b, ∀ᶠ x in f, r x b /-- `f.is_bounded_under (≺) u`: the image of the filter `f` under `u` is eventually bounded w.r.t. the relation `≺`, i.e. eventually, it is bounded by some uniform bound. -/ def is_bounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (map u f).is_bounded r variables {r : α → α → Prop} {f g : filter α} /-- `f` is eventually bounded if and only if, there exists an admissible set on which it is bounded. -/ lemma is_bounded_iff : f.is_bounded r ↔ (∃s∈f.sets, ∃b, s ⊆ {x | r x b}) := iff.intro (assume ⟨b, hb⟩, ⟨{a | r a b}, hb, b, subset.refl _⟩) (assume ⟨s, hs, b, hb⟩, ⟨b, mem_of_superset hs hb⟩) /-- A bounded function `u` is in particular eventually bounded. -/ lemma is_bounded_under_of {f : filter β} {u : β → α} : (∃b, ∀x, r (u x) b) → f.is_bounded_under r u | ⟨b, hb⟩ := ⟨b, show ∀ᶠ x in f, r (u x) b, from eventually_of_forall hb⟩ lemma is_bounded_bot : is_bounded r ⊥ ↔ nonempty α := by simp [is_bounded, exists_true_iff_nonempty] lemma is_bounded_top : is_bounded r ⊤ ↔ (∃t, ∀x, r x t) := by simp [is_bounded, eq_univ_iff_forall] lemma is_bounded_principal (s : set α) : is_bounded r (𝓟 s) ↔ (∃t, ∀x∈s, r x t) := by simp [is_bounded, subset_def] lemma is_bounded_sup [is_trans α r] (hr : ∀b₁ b₂, ∃b, r b₁ b ∧ r b₂ b) : is_bounded r f → is_bounded r g → is_bounded r (f ⊔ g) | ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := let ⟨b, rb₁b, rb₂b⟩ := hr b₁ b₂ in ⟨b, eventually_sup.mpr ⟨h₁.mono (λ x h, trans h rb₁b), h₂.mono (λ x h, trans h rb₂b)⟩⟩ lemma is_bounded.mono (h : f ≤ g) : is_bounded r g → is_bounded r f | ⟨b, hb⟩ := ⟨b, h hb⟩ lemma is_bounded_under.mono {f g : filter β} {u : β → α} (h : f ≤ g) : g.is_bounded_under r u → f.is_bounded_under r u := λ hg, hg.mono (map_mono h) lemma is_bounded_under.mono_le [preorder β] {l : filter α} {u v : α → β} (hu : is_bounded_under (≤) l u) (hv : v ≤ᶠ[l] u) : is_bounded_under (≤) l v := hu.imp $ λ b hb, (eventually_map.1 hb).mp $ hv.mono $ λ x, le_trans lemma is_bounded_under.mono_ge [preorder β] {l : filter α} {u v : α → β} (hu : is_bounded_under (≥) l u) (hv : u ≤ᶠ[l] v) : is_bounded_under (≥) l v := @is_bounded_under.mono_le α βᵒᵈ _ _ _ _ hu hv lemma is_bounded_under_const [is_refl α r] {l : filter β} {a : α} : is_bounded_under r l (λ _, a) := ⟨a, eventually_map.2 $ eventually_of_forall $ λ _, refl _⟩ lemma is_bounded.is_bounded_under {q : β → β → Prop} {u : α → β} (hf : ∀a₀ a₁, r a₀ a₁ → q (u a₀) (u a₁)) : f.is_bounded r → f.is_bounded_under q u | ⟨b, h⟩ := ⟨u b, show ∀ᶠ x in f, q (u x) (u b), from h.mono (λ x, hf x b)⟩ lemma not_is_bounded_under_of_tendsto_at_top [preorder β] [no_max_order β] {f : α → β} {l : filter α} [l.ne_bot] (hf : tendsto f l at_top) : ¬ is_bounded_under (≤) l f := begin rintro ⟨b, hb⟩, rw eventually_map at hb, obtain ⟨b', h⟩ := exists_gt b, have hb' := (tendsto_at_top.mp hf) b', have : {x : α | f x ≤ b} ∩ {x : α | b' ≤ f x} = ∅ := eq_empty_of_subset_empty (λ x hx, (not_le_of_lt h) (le_trans hx.2 hx.1)), exact (nonempty_of_mem (hb.and hb')).ne_empty this end lemma not_is_bounded_under_of_tendsto_at_bot [preorder β] [no_min_order β] {f : α → β} {l : filter α} [l.ne_bot](hf : tendsto f l at_bot) : ¬ is_bounded_under (≥) l f := @not_is_bounded_under_of_tendsto_at_top α βᵒᵈ _ _ _ _ _ hf lemma is_bounded_under.bdd_above_range_of_cofinite [semilattice_sup β] {f : α → β} (hf : is_bounded_under (≤) cofinite f) : bdd_above (range f) := begin rcases hf with ⟨b, hb⟩, haveI : nonempty β := ⟨b⟩, rw [← image_univ, ← union_compl_self {x | f x ≤ b}, image_union, bdd_above_union], exact ⟨⟨b, ball_image_iff.2 $ λ x, id⟩, (hb.image f).bdd_above⟩ end lemma is_bounded_under.bdd_below_range_of_cofinite [semilattice_inf β] {f : α → β} (hf : is_bounded_under (≥) cofinite f) : bdd_below (range f) := @is_bounded_under.bdd_above_range_of_cofinite α βᵒᵈ _ _ hf lemma is_bounded_under.bdd_above_range [semilattice_sup β] {f : ℕ → β} (hf : is_bounded_under (≤) at_top f) : bdd_above (range f) := by { rw ← nat.cofinite_eq_at_top at hf, exact hf.bdd_above_range_of_cofinite } lemma is_bounded_under.bdd_below_range [semilattice_inf β] {f : ℕ → β} (hf : is_bounded_under (≥) at_top f) : bdd_below (range f) := @is_bounded_under.bdd_above_range βᵒᵈ _ _ hf /-- `is_cobounded (≺) f` states that the filter `f` does not tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated with `≤` or `≥`. There is a subtlety in this definition: we want `f.is_cobounded` to hold for any `f` in the case of complete lattices. This will be relevant to deduce theorems on complete lattices from their versions on conditionally complete lattices with additional assumptions. We have to be careful in the edge case of the trivial filter containing the empty set: the other natural definition `¬ ∀ a, ∀ᶠ n in f, a ≤ n` would not work as well in this case. -/ def is_cobounded (r : α → α → Prop) (f : filter α) := ∃b, ∀a, (∀ᶠ x in f, r x a) → r b a /-- `is_cobounded_under (≺) f u` states that the image of the filter `f` under the map `u` does not tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated with `≤` or `≥`. -/ def is_cobounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (map u f).is_cobounded r /-- To check that a filter is frequently bounded, it suffices to have a witness which bounds `f` at some point for every admissible set. This is only an implication, as the other direction is wrong for the trivial filter.-/ lemma is_cobounded.mk [is_trans α r] (a : α) (h : ∀s∈f, ∃x∈s, r a x) : f.is_cobounded r := ⟨a, assume y s, let ⟨x, h₁, h₂⟩ := h _ s in trans h₂ h₁⟩ /-- A filter which is eventually bounded is in particular frequently bounded (in the opposite direction). At least if the filter is not trivial. -/ lemma is_bounded.is_cobounded_flip [is_trans α r] [ne_bot f] : f.is_bounded r → f.is_cobounded (flip r) | ⟨a, ha⟩ := ⟨a, assume b hb, let ⟨x, rxa, rbx⟩ := (ha.and hb).exists in show r b a, from trans rbx rxa⟩ lemma is_bounded.is_cobounded_ge [preorder α] [ne_bot f] (h : f.is_bounded (≤)) : f.is_cobounded (≥) := h.is_cobounded_flip lemma is_bounded.is_cobounded_le [preorder α] [ne_bot f] (h : f.is_bounded (≥)) : f.is_cobounded (≤) := h.is_cobounded_flip lemma is_cobounded_bot : is_cobounded r ⊥ ↔ (∃b, ∀x, r b x) := by simp [is_cobounded] lemma is_cobounded_top : is_cobounded r ⊤ ↔ nonempty α := by simp [is_cobounded, eq_univ_iff_forall, exists_true_iff_nonempty] {contextual := tt} lemma is_cobounded_principal (s : set α) : (𝓟 s).is_cobounded r ↔ (∃b, ∀a, (∀x∈s, r x a) → r b a) := by simp [is_cobounded, subset_def] lemma is_cobounded.mono (h : f ≤ g) : f.is_cobounded r → g.is_cobounded r | ⟨b, hb⟩ := ⟨b, assume a ha, hb a (h ha)⟩ end relation lemma is_cobounded_le_of_bot [preorder α] [order_bot α] {f : filter α} : f.is_cobounded (≤) := ⟨⊥, assume a h, bot_le⟩ lemma is_cobounded_ge_of_top [preorder α] [order_top α] {f : filter α} : f.is_cobounded (≥) := ⟨⊤, assume a h, le_top⟩ lemma is_bounded_le_of_top [preorder α] [order_top α] {f : filter α} : f.is_bounded (≤) := ⟨⊤, eventually_of_forall $ λ _, le_top⟩ lemma is_bounded_ge_of_bot [preorder α] [order_bot α] {f : filter α} : f.is_bounded (≥) := ⟨⊥, eventually_of_forall $ λ _, bot_le⟩ @[simp] lemma _root_.order_iso.is_bounded_under_le_comp [preorder α] [preorder β] (e : α ≃o β) {l : filter γ} {u : γ → α} : is_bounded_under (≤) l (λ x, e (u x)) ↔ is_bounded_under (≤) l u := e.surjective.exists.trans $ exists_congr $ λ a, by simp only [eventually_map, e.le_iff_le] @[simp] lemma _root_.order_iso.is_bounded_under_ge_comp [preorder α] [preorder β] (e : α ≃o β) {l : filter γ} {u : γ → α} : is_bounded_under (≥) l (λ x, e (u x)) ↔ is_bounded_under (≥) l u := e.dual.is_bounded_under_le_comp @[simp, to_additive] lemma is_bounded_under_le_inv [ordered_comm_group α] {l : filter β} {u : β → α} : is_bounded_under (≤) l (λ x, (u x)⁻¹) ↔ is_bounded_under (≥) l u := (order_iso.inv α).is_bounded_under_ge_comp @[simp, to_additive] lemma is_bounded_under_ge_inv [ordered_comm_group α] {l : filter β} {u : β → α} : is_bounded_under (≥) l (λ x, (u x)⁻¹) ↔ is_bounded_under (≤) l u := (order_iso.inv α).is_bounded_under_le_comp lemma is_bounded_under.sup [semilattice_sup α] {f : filter β} {u v : β → α} : f.is_bounded_under (≤) u → f.is_bounded_under (≤) v → f.is_bounded_under (≤) (λa, u a ⊔ v a) | ⟨bu, (hu : ∀ᶠ x in f, u x ≤ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≤ bv)⟩ := ⟨bu ⊔ bv, show ∀ᶠ x in f, u x ⊔ v x ≤ bu ⊔ bv, by filter_upwards [hu, hv] with _ using sup_le_sup⟩ @[simp] lemma is_bounded_under_le_sup [semilattice_sup α] {f : filter β} {u v : β → α} : f.is_bounded_under (≤) (λ a, u a ⊔ v a) ↔ f.is_bounded_under (≤) u ∧ f.is_bounded_under (≤) v := ⟨λ h, ⟨h.mono_le $ eventually_of_forall $ λ _, le_sup_left, h.mono_le $ eventually_of_forall $ λ _, le_sup_right⟩, λ h, h.1.sup h.2⟩ lemma is_bounded_under.inf [semilattice_inf α] {f : filter β} {u v : β → α} : f.is_bounded_under (≥) u → f.is_bounded_under (≥) v → f.is_bounded_under (≥) (λa, u a ⊓ v a) := @is_bounded_under.sup αᵒᵈ β _ _ _ _ @[simp] lemma is_bounded_under_ge_inf [semilattice_inf α] {f : filter β} {u v : β → α} : f.is_bounded_under (≥) (λ a, u a ⊓ v a) ↔ f.is_bounded_under (≥) u ∧ f.is_bounded_under (≥) v := @is_bounded_under_le_sup αᵒᵈ _ _ _ _ _ lemma is_bounded_under_le_abs [linear_ordered_add_comm_group α] {f : filter β} {u : β → α} : f.is_bounded_under (≤) (λ a, |u a|) ↔ f.is_bounded_under (≤) u ∧ f.is_bounded_under (≥) u := is_bounded_under_le_sup.trans $ and_congr iff.rfl is_bounded_under_le_neg /-- Filters are automatically bounded or cobounded in complete lattices. To use the same statements in complete and conditionally complete lattices but let automation fill automatically the boundedness proofs in complete lattices, we use the tactic `is_bounded_default` in the statements, in the form `(hf : f.is_bounded (≥) . is_bounded_default)`. -/ meta def is_bounded_default : tactic unit := tactic.applyc ``is_cobounded_le_of_bot <|> tactic.applyc ``is_cobounded_ge_of_top <|> tactic.applyc ``is_bounded_le_of_top <|> tactic.applyc ``is_bounded_ge_of_bot section conditionally_complete_lattice variables [conditionally_complete_lattice α] /-- The `Limsup` of a filter `f` is the infimum of the `a` such that, eventually for `f`, holds `x ≤ a`. -/ def Limsup (f : filter α) : α := Inf { a | ∀ᶠ n in f, n ≤ a } /-- The `Liminf` of a filter `f` is the supremum of the `a` such that, eventually for `f`, holds `x ≥ a`. -/ def Liminf (f : filter α) : α := Sup { a | ∀ᶠ n in f, a ≤ n } /-- The `limsup` of a function `u` along a filter `f` is the infimum of the `a` such that, eventually for `f`, holds `u x ≤ a`. -/ def limsup (u : β → α) (f : filter β) : α := Limsup (map u f) /-- The `liminf` of a function `u` along a filter `f` is the supremum of the `a` such that, eventually for `f`, holds `u x ≥ a`. -/ def liminf (u : β → α) (f : filter β) : α := Liminf (map u f) /-- The `blimsup` of a function `u` along a filter `f`, bounded by a predicate `p`, is the infimum of the `a` such that, eventually for `f`, `u x ≤ a` whenever `p x` holds. -/ def blimsup (u : β → α) (f : filter β) (p : β → Prop) := Inf { a | ∀ᶠ x in f, p x → u x ≤ a } /-- The `bliminf` of a function `u` along a filter `f`, bounded by a predicate `p`, is the supremum of the `a` such that, eventually for `f`, `a ≤ u x` whenever `p x` holds. -/ def bliminf (u : β → α) (f : filter β) (p : β → Prop) := Sup { a | ∀ᶠ x in f, p x → a ≤ u x } section variables {f : filter β} {u : β → α} {p : β → Prop} theorem limsup_eq : limsup u f = Inf { a | ∀ᶠ n in f, u n ≤ a } := rfl theorem liminf_eq : liminf u f = Sup { a | ∀ᶠ n in f, a ≤ u n } := rfl theorem blimsup_eq : blimsup u f p = Inf { a | ∀ᶠ x in f, p x → u x ≤ a } := rfl theorem bliminf_eq : bliminf u f p = Sup { a | ∀ᶠ x in f, p x → a ≤ u x } := rfl end @[simp] lemma blimsup_true (f : filter β) (u : β → α) : blimsup u f (λ x, true) = limsup u f := by simp [blimsup_eq, limsup_eq] @[simp] lemma bliminf_true (f : filter β) (u : β → α) : bliminf u f (λ x, true) = liminf u f := by simp [bliminf_eq, liminf_eq] lemma blimsup_eq_limsup_subtype {f : filter β} {u : β → α} {p : β → Prop} : blimsup u f p = limsup (u ∘ (coe : {x | p x} → β)) (comap coe f) := begin simp only [blimsup_eq, limsup_eq, function.comp_app, eventually_comap, set_coe.forall, subtype.coe_mk, mem_set_of_eq], congr, ext a, exact eventually_congr (eventually_of_forall (λ x, ⟨λ hx y hy hxy, hxy.symm ▸ (hx (hxy ▸ hy)), λ hx hx', hx x hx' rfl⟩)), end lemma bliminf_eq_liminf_subtype {f : filter β} {u : β → α} {p : β → Prop} : bliminf u f p = liminf (u ∘ (coe : {x | p x} → β)) (comap coe f) := @blimsup_eq_limsup_subtype αᵒᵈ β _ f u p theorem Limsup_le_of_le {f : filter α} {a} (hf : f.is_cobounded (≤) . is_bounded_default) (h : ∀ᶠ n in f, n ≤ a) : Limsup f ≤ a := cInf_le hf h theorem le_Liminf_of_le {f : filter α} {a} (hf : f.is_cobounded (≥) . is_bounded_default) (h : ∀ᶠ n in f, a ≤ n) : a ≤ Liminf f := le_cSup hf h theorem limsup_le_of_le {f : filter β} {u : β → α} {a} (hf : f.is_cobounded_under (≤) u . is_bounded_default) (h : ∀ᶠ n in f, u n ≤ a) : limsup u f ≤ a := cInf_le hf h theorem le_liminf_of_le {f : filter β} {u : β → α} {a} (hf : f.is_cobounded_under (≥) u . is_bounded_default) (h : ∀ᶠ n in f, a ≤ u n) : a ≤ liminf u f := le_cSup hf h theorem le_Limsup_of_le {f : filter α} {a} (hf : f.is_bounded (≤) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, n ≤ b) → a ≤ b) : a ≤ Limsup f := le_cInf hf h theorem Liminf_le_of_le {f : filter α} {a} (hf : f.is_bounded (≥) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ n) → b ≤ a) : Liminf f ≤ a := cSup_le hf h theorem le_limsup_of_le {f : filter β} {u : β → α} {a} (hf : f.is_bounded_under (≤) u . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, u n ≤ b) → a ≤ b) : a ≤ limsup u f := le_cInf hf h theorem liminf_le_of_le {f : filter β} {u : β → α} {a} (hf : f.is_bounded_under (≥) u . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ u n) → b ≤ a) : liminf u f ≤ a := cSup_le hf h theorem Liminf_le_Limsup {f : filter α} [ne_bot f] (h₁ : f.is_bounded (≤) . is_bounded_default) (h₂ : f.is_bounded (≥) . is_bounded_default) : Liminf f ≤ Limsup f := Liminf_le_of_le h₂ $ assume a₀ ha₀, le_Limsup_of_le h₁ $ assume a₁ ha₁, show a₀ ≤ a₁, from let ⟨b, hb₀, hb₁⟩ := (ha₀.and ha₁).exists in le_trans hb₀ hb₁ lemma liminf_le_limsup {f : filter β} [ne_bot f] {u : β → α} (h : f.is_bounded_under (≤) u . is_bounded_default) (h' : f.is_bounded_under (≥) u . is_bounded_default) : liminf u f ≤ limsup u f := Liminf_le_Limsup h h' lemma Limsup_le_Limsup {f g : filter α} (hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) (h : ∀ a, (∀ᶠ n in g, n ≤ a) → ∀ᶠ n in f, n ≤ a) : Limsup f ≤ Limsup g := cInf_le_cInf hf hg h lemma Liminf_le_Liminf {f g : filter α} (hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) (h : ∀ a, (∀ᶠ n in f, a ≤ n) → ∀ᶠ n in g, a ≤ n) : Liminf f ≤ Liminf g := cSup_le_cSup hg hf h lemma limsup_le_limsup {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : u ≤ᶠ[f] v) (hu : f.is_cobounded_under (≤) u . is_bounded_default) (hv : f.is_bounded_under (≤) v . is_bounded_default) : limsup u f ≤ limsup v f := Limsup_le_Limsup hu hv $ assume b, h.trans lemma liminf_le_liminf {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a ≤ v a) (hu : f.is_bounded_under (≥) u . is_bounded_default) (hv : f.is_cobounded_under (≥) v . is_bounded_default) : liminf u f ≤ liminf v f := @limsup_le_limsup βᵒᵈ α _ _ _ _ h hv hu lemma Limsup_le_Limsup_of_le {f g : filter α} (h : f ≤ g) (hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) : Limsup f ≤ Limsup g := Limsup_le_Limsup hf hg (assume a ha, h ha) lemma Liminf_le_Liminf_of_le {f g : filter α} (h : g ≤ f) (hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) : Liminf f ≤ Liminf g := Liminf_le_Liminf hf hg (assume a ha, h ha) lemma limsup_le_limsup_of_le {α β} [conditionally_complete_lattice β] {f g : filter α} (h : f ≤ g) {u : α → β} (hf : f.is_cobounded_under (≤) u . is_bounded_default) (hg : g.is_bounded_under (≤) u . is_bounded_default) : limsup u f ≤ limsup u g := Limsup_le_Limsup_of_le (map_mono h) hf hg lemma liminf_le_liminf_of_le {α β} [conditionally_complete_lattice β] {f g : filter α} (h : g ≤ f) {u : α → β} (hf : f.is_bounded_under (≥) u . is_bounded_default) (hg : g.is_cobounded_under (≥) u . is_bounded_default) : liminf u f ≤ liminf u g := Liminf_le_Liminf_of_le (map_mono h) hf hg theorem Limsup_principal {s : set α} (h : bdd_above s) (hs : s.nonempty) : Limsup (𝓟 s) = Sup s := by simp [Limsup]; exact cInf_upper_bounds_eq_cSup h hs theorem Liminf_principal {s : set α} (h : bdd_below s) (hs : s.nonempty) : Liminf (𝓟 s) = Inf s := @Limsup_principal αᵒᵈ _ s h hs lemma limsup_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : limsup u f = limsup v f := begin rw limsup_eq, congr' with b, exact eventually_congr (h.mono $ λ x hx, by simp [hx]) end lemma blimsup_congr {f : filter β} {u v : β → α} {p : β → Prop} (h : ∀ᶠ a in f, p a → u a = v a) : blimsup u f p = blimsup v f p := begin rw blimsup_eq, congr' with b, refine eventually_congr (h.mono $ λ x hx, ⟨λ h₁ h₂, _, λ h₁ h₂, _⟩), { rw ← hx h₂, exact h₁ h₂, }, { rw hx h₂, exact h₁ h₂, }, end lemma bliminf_congr {f : filter β} {u v : β → α} {p : β → Prop} (h : ∀ᶠ a in f, p a → u a = v a) : bliminf u f p = bliminf v f p := @blimsup_congr αᵒᵈ _ _ _ _ _ _ h lemma liminf_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : liminf u f = liminf v f := @limsup_congr βᵒᵈ _ _ _ _ _ h lemma limsup_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f] (b : β) : limsup (λ x, b) f = b := by simpa only [limsup_eq, eventually_const] using cInf_Ici lemma liminf_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f] (b : β) : liminf (λ x, b) f = b := @limsup_const βᵒᵈ α _ f _ b end conditionally_complete_lattice section complete_lattice variables [complete_lattice α] @[simp] theorem Limsup_bot : Limsup (⊥ : filter α) = ⊥ := bot_unique $ Inf_le $ by simp @[simp] theorem Liminf_bot : Liminf (⊥ : filter α) = ⊤ := top_unique $ le_Sup $ by simp @[simp] theorem Limsup_top : Limsup (⊤ : filter α) = ⊤ := top_unique $ le_Inf $ by simp [eq_univ_iff_forall]; exact assume b hb, (top_unique $ hb _) @[simp] theorem Liminf_top : Liminf (⊤ : filter α) = ⊥ := bot_unique $ Sup_le $ by simp [eq_univ_iff_forall]; exact assume b hb, (bot_unique $ hb _) @[simp] lemma blimsup_false {f : filter β} {u : β → α} : blimsup u f (λ x, false) = ⊥ := by simp [blimsup_eq] @[simp] lemma bliminf_false {f : filter β} {u : β → α} : bliminf u f (λ x, false) = ⊤ := by simp [bliminf_eq] /-- Same as limsup_const applied to `⊥` but without the `ne_bot f` assumption -/ lemma limsup_const_bot {f : filter β} : limsup (λ x : β, (⊥ : α)) f = (⊥ : α) := begin rw [limsup_eq, eq_bot_iff], exact Inf_le (eventually_of_forall (λ x, le_rfl)), end /-- Same as limsup_const applied to `⊤` but without the `ne_bot f` assumption -/ lemma liminf_const_top {f : filter β} : liminf (λ x : β, (⊤ : α)) f = (⊤ : α) := @limsup_const_bot αᵒᵈ β _ _ theorem has_basis.Limsup_eq_infi_Sup {ι} {p : ι → Prop} {s} {f : filter α} (h : f.has_basis p s) : Limsup f = ⨅ i (hi : p i), Sup (s i) := le_antisymm (le_infi₂ $ λ i hi, Inf_le $ h.eventually_iff.2 ⟨i, hi, λ x, le_Sup⟩) (le_Inf $ assume a ha, let ⟨i, hi, ha⟩ := h.eventually_iff.1 ha in infi₂_le_of_le _ hi $ Sup_le ha) theorem has_basis.Liminf_eq_supr_Inf {p : ι → Prop} {s : ι → set α} {f : filter α} (h : f.has_basis p s) : Liminf f = ⨆ i (hi : p i), Inf (s i) := @has_basis.Limsup_eq_infi_Sup αᵒᵈ _ _ _ _ _ h theorem Limsup_eq_infi_Sup {f : filter α} : Limsup f = ⨅ s ∈ f, Sup s := f.basis_sets.Limsup_eq_infi_Sup theorem Liminf_eq_supr_Inf {f : filter α} : Liminf f = ⨆ s ∈ f, Inf s := @Limsup_eq_infi_Sup αᵒᵈ _ _ theorem limsup_le_supr {f : filter β} {u : β → α} : limsup u f ≤ ⨆ n, u n := limsup_le_of_le (by is_bounded_default) (eventually_of_forall (le_supr u)) theorem infi_le_liminf {f : filter β} {u : β → α} : (⨅ n, u n) ≤ liminf u f := le_liminf_of_le (by is_bounded_default) (eventually_of_forall (infi_le u)) /-- In a complete lattice, the limsup of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem limsup_eq_infi_supr {f : filter β} {u : β → α} : limsup u f = ⨅ s ∈ f, ⨆ a ∈ s, u a := (f.basis_sets.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, id] lemma limsup_eq_infi_supr_of_nat {u : ℕ → α} : limsup u at_top = ⨅ n : ℕ, ⨆ i ≥ n, u i := (at_top_basis.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, infi_const]; refl lemma limsup_eq_infi_supr_of_nat' {u : ℕ → α} : limsup u at_top = ⨅ n : ℕ, ⨆ i : ℕ, u (i + n) := by simp only [limsup_eq_infi_supr_of_nat, supr_ge_eq_supr_nat_add] theorem has_basis.limsup_eq_infi_supr {p : ι → Prop} {s : ι → set β} {f : filter β} {u : β → α} (h : f.has_basis p s) : limsup u f = ⨅ i (hi : p i), ⨆ a ∈ s i, u a := (h.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, id] lemma blimsup_congr' {f : filter β} {p q : β → Prop} {u : β → α} (h : ∀ᶠ x in f, u x ≠ ⊥ → (p x ↔ q x)) : blimsup u f p = blimsup u f q := begin simp only [blimsup_eq], congr, ext a, refine eventually_congr (h.mono $ λ b hb, _), cases eq_or_ne (u b) ⊥ with hu hu, { simp [hu], }, rw hb hu, end lemma bliminf_congr' {f : filter β} {p q : β → Prop} {u : β → α} (h : ∀ᶠ x in f, u x ≠ ⊤ → (p x ↔ q x)) : bliminf u f p = bliminf u f q := @blimsup_congr' αᵒᵈ β _ _ _ _ _ h lemma blimsup_eq_infi_bsupr {f : filter β} {p : β → Prop} {u : β → α} : blimsup u f p = ⨅ s ∈ f, ⨆ b (hb : p b ∧ b ∈ s), u b := begin refine le_antisymm (Inf_le_Inf _) (infi_le_iff.mpr $ λ a ha, le_Inf_iff.mpr $ λ a' ha', _), { rintros - ⟨s, rfl⟩, simp only [mem_set_of_eq, le_infi_iff], conv { congr, funext, rw imp.swap, }, refine eventually_imp_distrib_left.mpr (λ h, eventually_iff_exists_mem.2 ⟨s, h, λ x h₁ h₂, _⟩), exact @le_supr₂ α β (λ b, p b ∧ b ∈ s) _ (λ b hb, u b) x ⟨h₂, h₁⟩, }, { obtain ⟨s, hs, hs'⟩ := eventually_iff_exists_mem.mp ha', simp_rw imp.swap at hs', exact (le_infi_iff.mp (ha s) hs).trans (by simpa only [supr₂_le_iff, and_imp]), }, end lemma blimsup_eq_infi_bsupr_of_nat {p : ℕ → Prop} {u : ℕ → α} : blimsup u at_top p = ⨅ i, ⨆ j (hj : p j ∧ i ≤ j), u j := by simp only [blimsup_eq_limsup_subtype, mem_preimage, mem_Ici, function.comp_app, cinfi_pos, supr_subtype, (at_top_basis.comap (coe : {x | p x} → ℕ)).limsup_eq_infi_supr, mem_set_of_eq, subtype.coe_mk, supr_and] /-- In a complete lattice, the liminf of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem liminf_eq_supr_infi {f : filter β} {u : β → α} : liminf u f = ⨆ s ∈ f, ⨅ a ∈ s, u a := @limsup_eq_infi_supr αᵒᵈ β _ _ _ lemma liminf_eq_supr_infi_of_nat {u : ℕ → α} : liminf u at_top = ⨆ n : ℕ, ⨅ i ≥ n, u i := @limsup_eq_infi_supr_of_nat αᵒᵈ _ u lemma liminf_eq_supr_infi_of_nat' {u : ℕ → α} : liminf u at_top = ⨆ n : ℕ, ⨅ i : ℕ, u (i + n) := @limsup_eq_infi_supr_of_nat' αᵒᵈ _ _ theorem has_basis.liminf_eq_supr_infi {p : ι → Prop} {s : ι → set β} {f : filter β} {u : β → α} (h : f.has_basis p s) : liminf u f = ⨆ i (hi : p i), ⨅ a ∈ s i, u a := @has_basis.limsup_eq_infi_supr αᵒᵈ _ _ _ _ _ _ _ h lemma bliminf_eq_supr_binfi {f : filter β} {p : β → Prop} {u : β → α} : bliminf u f p = ⨆ s ∈ f, ⨅ b (hb : p b ∧ b ∈ s), u b := @blimsup_eq_infi_bsupr αᵒᵈ β _ f p u lemma bliminf_eq_supr_binfi_of_nat {p : ℕ → Prop} {u : ℕ → α} : bliminf u at_top p = ⨆ i, ⨅ j (hj : p j ∧ i ≤ j), u j := @blimsup_eq_infi_bsupr_of_nat αᵒᵈ _ p u lemma limsup_eq_Inf_Sup {ι R : Type*} (F : filter ι) [complete_lattice R] (a : ι → R) : limsup a F = Inf ((λ I, Sup (a '' I)) '' F.sets) := begin refine le_antisymm _ _, { rw limsup_eq, refine Inf_le_Inf (λ x hx, _), rcases (mem_image _ F.sets x).mp hx with ⟨I, ⟨I_mem_F, hI⟩⟩, filter_upwards [I_mem_F] with i hi, exact hI ▸ le_Sup (mem_image_of_mem _ hi), }, { refine le_Inf_iff.mpr (λ b hb, Inf_le_of_le (mem_image_of_mem _ $ filter.mem_sets.mpr hb) $ Sup_le _), rintros _ ⟨_, h, rfl⟩, exact h, }, end lemma liminf_eq_Sup_Inf {ι R : Type*} (F : filter ι) [complete_lattice R] (a : ι → R) : liminf a F = Sup ((λ I, Inf (a '' I)) '' F.sets) := @filter.limsup_eq_Inf_Sup ι (order_dual R) _ _ a @[simp] lemma liminf_nat_add (f : ℕ → α) (k : ℕ) : liminf (λ i, f (i + k)) at_top = liminf f at_top := by { simp_rw liminf_eq_supr_infi_of_nat, exact supr_infi_ge_nat_add f k } @[simp] lemma limsup_nat_add (f : ℕ → α) (k : ℕ) : limsup (λ i, f (i + k)) at_top = limsup f at_top := @liminf_nat_add αᵒᵈ _ f k lemma liminf_le_of_frequently_le' {α β} [complete_lattice β] {f : filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, u a ≤ x) : liminf u f ≤ x := begin rw liminf_eq, refine Sup_le (λ b hb, _), have hbx : ∃ᶠ a in f, b ≤ x, { revert h, rw [←not_imp_not, not_frequently, not_frequently], exact λ h, hb.mp (h.mono (λ a hbx hba hax, hbx (hba.trans hax))), }, exact hbx.exists.some_spec, end lemma le_limsup_of_frequently_le' {α β} [complete_lattice β] {f : filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, x ≤ u a) : x ≤ limsup u f := @liminf_le_of_frequently_le' _ βᵒᵈ _ _ _ _ h /-- If `f : α → α` is a morphism of complete lattices, then the limsup of its iterates of any `a : α` is a fixed point. -/ @[simp] lemma complete_lattice_hom.apply_limsup_iterate (f : complete_lattice_hom α α) (a : α) : f (limsup (λ n, f^[n] a) at_top) = limsup (λ n, f^[n] a) at_top := begin rw [limsup_eq_infi_supr_of_nat', map_infi], simp_rw [_root_.map_supr, ← function.comp_apply f, ← function.iterate_succ' f, ← nat.add_succ], conv_rhs { rw infi_split _ ((<) (0 : ℕ)), }, simp only [not_lt, le_zero_iff, infi_infi_eq_left, add_zero, infi_nat_gt_zero_eq, left_eq_inf], refine (infi_le (λ i, ⨆ j, (f^[j + (i + 1)]) a) 0).trans _, simp only [zero_add, function.comp_app, supr_le_iff], exact λ i, le_supr (λ i, (f^[i] a)) (i + 1), end /-- If `f : α → α` is a morphism of complete lattices, then the liminf of its iterates of any `a : α` is a fixed point. -/ lemma complete_lattice_hom.apply_liminf_iterate (f : complete_lattice_hom α α) (a : α) : f (liminf (λ n, f^[n] a) at_top) = liminf (λ n, f^[n] a) at_top := (complete_lattice_hom.dual f).apply_limsup_iterate _ variables {f g : filter β} {p q : β → Prop} {u v : β → α} lemma blimsup_mono (h : ∀ x, p x → q x) : blimsup u f p ≤ blimsup u f q := Inf_le_Inf $ λ a ha, ha.mono $ by tauto lemma bliminf_antitone (h : ∀ x, p x → q x) : bliminf u f q ≤ bliminf u f p := Sup_le_Sup $ λ a ha, ha.mono $ by tauto lemma mono_blimsup' (h : ∀ᶠ x in f, p x → u x ≤ v x) : blimsup u f p ≤ blimsup v f p := Inf_le_Inf $ λ a ha, (ha.and h).mono $ λ x hx hx', (hx.2 hx').trans (hx.1 hx') lemma mono_blimsup (h : ∀ x, p x → u x ≤ v x) : blimsup u f p ≤ blimsup v f p := mono_blimsup' $ eventually_of_forall h lemma mono_bliminf' (h : ∀ᶠ x in f, p x → u x ≤ v x) : bliminf u f p ≤ bliminf v f p := Sup_le_Sup $ λ a ha, (ha.and h).mono $ λ x hx hx', (hx.1 hx').trans (hx.2 hx') lemma mono_bliminf (h : ∀ x, p x → u x ≤ v x) : bliminf u f p ≤ bliminf v f p := mono_bliminf' $ eventually_of_forall h lemma bliminf_antitone_filter (h : f ≤ g) : bliminf u g p ≤ bliminf u f p := Sup_le_Sup $ λ a ha, ha.filter_mono h lemma blimsup_monotone_filter (h : f ≤ g) : blimsup u f p ≤ blimsup u g p := Inf_le_Inf $ λ a ha, ha.filter_mono h @[simp] lemma blimsup_and_le_inf : blimsup u f (λ x, p x ∧ q x) ≤ blimsup u f p ⊓ blimsup u f q := le_inf (blimsup_mono $ by tauto) (blimsup_mono $ by tauto) @[simp] lemma bliminf_sup_le_and : bliminf u f p ⊔ bliminf u f q ≤ bliminf u f (λ x, p x ∧ q x) := @blimsup_and_le_inf αᵒᵈ β _ f p q u /-- See also `filter.blimsup_or_eq_sup`. -/ @[simp] lemma blimsup_sup_le_or : blimsup u f p ⊔ blimsup u f q ≤ blimsup u f (λ x, p x ∨ q x) := sup_le (blimsup_mono $ by tauto) (blimsup_mono $ by tauto) /-- See also `filter.bliminf_or_eq_inf`. -/ @[simp] lemma bliminf_or_le_inf : bliminf u f (λ x, p x ∨ q x) ≤ bliminf u f p ⊓ bliminf u f q := @blimsup_sup_le_or αᵒᵈ β _ f p q u lemma order_iso.apply_blimsup [complete_lattice γ] (e : α ≃o γ) : e (blimsup u f p) = blimsup (e ∘ u) f p := begin simp only [blimsup_eq, map_Inf, function.comp_app], congr, ext c, obtain ⟨a, rfl⟩ := e.surjective c, simp, end lemma order_iso.apply_bliminf [complete_lattice γ] (e : α ≃o γ) : e (bliminf u f p) = bliminf (e ∘ u) f p := @order_iso.apply_blimsup αᵒᵈ β γᵒᵈ _ f p u _ e.dual lemma Sup_hom.apply_blimsup_le [complete_lattice γ] (g : Sup_hom α γ) : g (blimsup u f p) ≤ blimsup (g ∘ u) f p := begin simp only [blimsup_eq_infi_bsupr], refine ((order_hom_class.mono g).map_infi₂_le _).trans _, simp only [_root_.map_supr], end lemma Inf_hom.le_apply_bliminf [complete_lattice γ] (g : Inf_hom α γ) : bliminf (g ∘ u) f p ≤ g (bliminf u f p) := @Sup_hom.apply_blimsup_le αᵒᵈ β γᵒᵈ _ f p u _ g.dual end complete_lattice section complete_distrib_lattice variables [complete_distrib_lattice α] {f : filter β} {p q : β → Prop} {u : β → α} @[simp] lemma blimsup_or_eq_sup : blimsup u f (λ x, p x ∨ q x) = blimsup u f p ⊔ blimsup u f q := begin refine le_antisymm _ blimsup_sup_le_or, simp only [blimsup_eq, Inf_sup_eq, sup_Inf_eq, le_infi₂_iff, mem_set_of_eq], refine λ a' ha' a ha, Inf_le ((ha.and ha').mono $ λ b h hb, _), exact or.elim hb (λ hb, le_sup_of_le_left $ h.1 hb) (λ hb, le_sup_of_le_right $ h.2 hb), end @[simp] lemma bliminf_or_eq_inf : bliminf u f (λ x, p x ∨ q x) = bliminf u f p ⊓ bliminf u f q := @blimsup_or_eq_sup αᵒᵈ β _ f p q u lemma sup_limsup [ne_bot f] (a : α) : a ⊔ limsup u f = limsup (λ x, a ⊔ u x) f := begin simp only [limsup_eq_infi_supr, supr_sup_eq, sup_binfi_eq], congr, ext s, congr, ext hs, congr, exact (bsupr_const (nonempty_of_mem hs)).symm, end lemma inf_liminf [ne_bot f] (a : α) : a ⊓ liminf u f = liminf (λ x, a ⊓ u x) f := @sup_limsup αᵒᵈ β _ f _ _ _ lemma sup_liminf (a : α) : a ⊔ liminf u f = liminf (λ x, a ⊔ u x) f := begin simp only [liminf_eq_supr_infi], rw [sup_comm, bsupr_sup (⟨univ, univ_mem⟩ : ∃ (i : set β), i ∈ f)], simp_rw [binfi_sup_eq, @sup_comm _ _ a], end lemma inf_limsup (a : α) : a ⊓ limsup u f = limsup (λ x, a ⊓ u x) f := @sup_liminf αᵒᵈ β _ f _ _ end complete_distrib_lattice section complete_boolean_algebra variables [complete_boolean_algebra α] (f : filter β) (u : β → α) lemma limsup_compl : (limsup u f)ᶜ = liminf (compl ∘ u) f := by simp only [limsup_eq_infi_supr, liminf_eq_supr_infi, compl_infi, compl_supr] lemma liminf_compl : (liminf u f)ᶜ = limsup (compl ∘ u) f := by simp only [limsup_eq_infi_supr, liminf_eq_supr_infi, compl_infi, compl_supr] lemma limsup_sdiff (a : α) : (limsup u f) \ a = limsup (λ b, (u b) \ a) f := begin simp only [limsup_eq_infi_supr, sdiff_eq], rw binfi_inf (⟨univ, univ_mem⟩ : ∃ (i : set β), i ∈ f), simp_rw [inf_comm, inf_bsupr_eq, inf_comm], end lemma liminf_sdiff [ne_bot f] (a : α) : (liminf u f) \ a = liminf (λ b, (u b) \ a) f := by simp only [sdiff_eq, @inf_comm _ _ _ aᶜ, inf_liminf] lemma sdiff_limsup [ne_bot f] (a : α) : a \ limsup u f = liminf (λ b, a \ u b) f := begin rw ← compl_inj_iff, simp only [sdiff_eq, liminf_compl, (∘), compl_inf, compl_compl, sup_limsup], end lemma sdiff_liminf (a : α) : a \ liminf u f = limsup (λ b, a \ u b) f := begin rw ← compl_inj_iff, simp only [sdiff_eq, limsup_compl, (∘), compl_inf, compl_compl, sup_liminf], end end complete_boolean_algebra section set_lattice variables {p : ι → Prop} {s : ι → set α} lemma cofinite.blimsup_set_eq : blimsup s cofinite p = { x | { n | p n ∧ x ∈ s n }.infinite } := begin simp only [blimsup_eq, le_eq_subset, eventually_cofinite, not_forall, Inf_eq_sInter, exists_prop], ext x, refine ⟨λ h, _, λ hx t h, _⟩; contrapose! h, { simp only [mem_sInter, mem_set_of_eq, not_forall, exists_prop], exact ⟨{x}ᶜ, by simpa using h, by simp⟩, }, { exact hx.mono (λ i hi, ⟨hi.1, λ hit, h (hit hi.2)⟩), }, end lemma cofinite.bliminf_set_eq : bliminf s cofinite p = { x | { n | p n ∧ x ∉ s n }.finite } := begin rw ← compl_inj_iff, simpa only [bliminf_eq_supr_binfi, compl_infi, compl_supr, ← blimsup_eq_infi_bsupr, cofinite.blimsup_set_eq], end /-- In other words, `limsup cofinite s` is the set of elements lying inside the family `s` infinitely often. -/ lemma cofinite.limsup_set_eq : limsup s cofinite = { x | { n | x ∈ s n }.infinite } := by simp only [← cofinite.blimsup_true s, cofinite.blimsup_set_eq, true_and] /-- In other words, `liminf cofinite s` is the set of elements lying outside the family `s` finitely often. -/ lemma cofinite.liminf_set_eq : liminf s cofinite = { x | { n | x ∉ s n }.finite } := by simp only [← cofinite.bliminf_true s, cofinite.bliminf_set_eq, true_and] lemma exists_forall_mem_of_has_basis_mem_blimsup {l : filter β} {b : ι → set β} {q : ι → Prop} (hl : l.has_basis q b) {u : β → set α} {p : β → Prop} {x : α} (hx : x ∈ blimsup u l p) : ∃ f : {i | q i} → β, ∀ i, x ∈ u (f i) ∧ p (f i) ∧ f i ∈ b i := begin rw blimsup_eq_infi_bsupr at hx, simp only [supr_eq_Union, infi_eq_Inter, mem_Inter, mem_Union, exists_prop] at hx, choose g hg hg' using hx, refine ⟨λ (i : {i | q i}), g (b i) (hl.mem_of_mem i.2), λ i, ⟨_, _⟩⟩, { exact hg' (b i) (hl.mem_of_mem i.2), }, { exact hg (b i) (hl.mem_of_mem i.2), }, end lemma exists_forall_mem_of_has_basis_mem_blimsup' {l : filter β} {b : ι → set β} (hl : l.has_basis (λ _, true) b) {u : β → set α} {p : β → Prop} {x : α} (hx : x ∈ blimsup u l p) : ∃ f : ι → β, ∀ i, x ∈ u (f i) ∧ p (f i) ∧ f i ∈ b i := begin obtain ⟨f, hf⟩ := exists_forall_mem_of_has_basis_mem_blimsup hl hx, exact ⟨λ i, f ⟨i, trivial⟩, λ i, hf ⟨i, trivial⟩⟩, end end set_lattice section conditionally_complete_linear_order lemma frequently_lt_of_lt_Limsup {f : filter α} [conditionally_complete_linear_order α] {a : α} (hf : f.is_cobounded (≤) . is_bounded_default) (h : a < Limsup f) : ∃ᶠ n in f, a < n := begin contrapose! h, simp only [not_frequently, not_lt] at h, exact Limsup_le_of_le hf h, end lemma frequently_lt_of_Liminf_lt {f : filter α} [conditionally_complete_linear_order α] {a : α} (hf : f.is_cobounded (≥) . is_bounded_default) (h : Liminf f < a) : ∃ᶠ n in f, n < a := @frequently_lt_of_lt_Limsup (order_dual α) f _ a hf h lemma eventually_lt_of_lt_liminf {f : filter α} [conditionally_complete_linear_order β] {u : α → β} {b : β} (h : b < liminf u f) (hu : f.is_bounded_under (≥) u . is_bounded_default) : ∀ᶠ a in f, b < u a := begin obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, c ≤ u n}), b < c := exists_lt_of_lt_cSup hu h, exact hc.mono (λ x hx, lt_of_lt_of_le hbc hx) end lemma eventually_lt_of_limsup_lt {f : filter α} [conditionally_complete_linear_order β] {u : α → β} {b : β} (h : limsup u f < b) (hu : f.is_bounded_under (≤) u . is_bounded_default) : ∀ᶠ a in f, u a < b := @eventually_lt_of_lt_liminf _ βᵒᵈ _ _ _ _ h hu lemma le_limsup_of_frequently_le {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu_le : ∃ᶠ x in f, b ≤ u x) (hu : f.is_bounded_under (≤) u . is_bounded_default) : b ≤ limsup u f := begin revert hu_le, rw [←not_imp_not, not_frequently], simp_rw ←lt_iff_not_ge, exact λ h, eventually_lt_of_limsup_lt h hu, end lemma liminf_le_of_frequently_le {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu_le : ∃ᶠ x in f, u x ≤ b) (hu : f.is_bounded_under (≥) u . is_bounded_default) : liminf u f ≤ b := @le_limsup_of_frequently_le _ βᵒᵈ _ f u b hu_le hu lemma frequently_lt_of_lt_limsup {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu : f.is_cobounded_under (≤) u . is_bounded_default) (h : b < limsup u f) : ∃ᶠ x in f, b < u x := begin contrapose! h, apply Limsup_le_of_le hu, simpa using h, end lemma frequently_lt_of_liminf_lt {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu : f.is_cobounded_under (≥) u . is_bounded_default) (h : liminf u f < b) : ∃ᶠ x in f, u x < b := @frequently_lt_of_lt_limsup _ βᵒᵈ _ f u b hu h end conditionally_complete_linear_order end filter section order open filter lemma monotone.is_bounded_under_le_comp [nonempty β] [linear_order β] [preorder γ] [no_max_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : monotone g) (hg' : tendsto g at_top at_top) : is_bounded_under (≤) l (g ∘ f) ↔ is_bounded_under (≤) l f := begin refine ⟨_, λ h, h.is_bounded_under hg⟩, rintro ⟨c, hc⟩, rw eventually_map at hc, obtain ⟨b, hb⟩ : ∃ b, ∀ a ≥ b, c < g a := eventually_at_top.1 (hg'.eventually_gt_at_top c), exact ⟨b, hc.mono $ λ x hx, not_lt.1 (λ h, (hb _ h.le).not_le hx)⟩ end lemma monotone.is_bounded_under_ge_comp [nonempty β] [linear_order β] [preorder γ] [no_min_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : monotone g) (hg' : tendsto g at_bot at_bot) : is_bounded_under (≥) l (g ∘ f) ↔ is_bounded_under (≥) l f := hg.dual.is_bounded_under_le_comp hg' lemma antitone.is_bounded_under_le_comp [nonempty β] [linear_order β] [preorder γ] [no_max_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : antitone g) (hg' : tendsto g at_bot at_top) : is_bounded_under (≤) l (g ∘ f) ↔ is_bounded_under (≥) l f := hg.dual_right.is_bounded_under_ge_comp hg' lemma antitone.is_bounded_under_ge_comp [nonempty β] [linear_order β] [preorder γ] [no_min_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : antitone g) (hg' : tendsto g at_top at_bot) : is_bounded_under (≥) l (g ∘ f) ↔ is_bounded_under (≤) l f := hg.dual_right.is_bounded_under_le_comp hg' lemma galois_connection.l_limsup_le [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : filter α} {v : α → β} {l : β → γ} {u : γ → β} (gc : galois_connection l u) (hlv : f.is_bounded_under (≤) (λ x, l (v x)) . is_bounded_default) (hv_co : f.is_cobounded_under (≤) v . is_bounded_default) : l (limsup v f) ≤ limsup (λ x, l (v x)) f := begin refine le_Limsup_of_le hlv (λ c hc, _), rw filter.eventually_map at hc, simp_rw (gc _ _) at hc ⊢, exact Limsup_le_of_le hv_co hc, end lemma order_iso.limsup_apply {γ} [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : filter α} {u : α → β} (g : β ≃o γ) (hu : f.is_bounded_under (≤) u . is_bounded_default) (hu_co : f.is_cobounded_under (≤) u . is_bounded_default) (hgu : f.is_bounded_under (≤) (λ x, g (u x)) . is_bounded_default) (hgu_co : f.is_cobounded_under (≤) (λ x, g (u x)) . is_bounded_default) : g (limsup u f) = limsup (λ x, g (u x)) f := begin refine le_antisymm (g.to_galois_connection.l_limsup_le hgu hu_co) _, rw [←(g.symm.symm_apply_apply $ limsup (λ x, g (u x)) f), g.symm_symm], refine g.monotone _, have hf : u = λ i, g.symm (g (u i)), from funext (λ i, (g.symm_apply_apply (u i)).symm), nth_rewrite 0 hf, refine g.symm.to_galois_connection.l_limsup_le _ hgu_co, simp_rw g.symm_apply_apply, exact hu, end lemma order_iso.liminf_apply {γ} [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : filter α} {u : α → β} (g : β ≃o γ) (hu : f.is_bounded_under (≥) u . is_bounded_default) (hu_co : f.is_cobounded_under (≥) u . is_bounded_default) (hgu : f.is_bounded_under (≥) (λ x, g (u x)) . is_bounded_default) (hgu_co : f.is_cobounded_under (≥) (λ x, g (u x)) . is_bounded_default) : g (liminf u f) = liminf (λ x, g (u x)) f := @order_iso.limsup_apply α βᵒᵈ γᵒᵈ _ _ f u g.dual hu hu_co hgu hgu_co end order
df376224a88653127c2243d014fdac2e9268d3a0
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/list/sigma.lean
f4900fbdcc857a438910a7134b18f49d31d8c6e8
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
23,984
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 data.sigma 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 _ @[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 (map_sublist_map _ h) 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₂ := perm_nodup $ perm_map _ h 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', ext 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] 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 := begin have := not_congr (@lookup_is_some _ _ _ a l), simp at this, refine iff.trans _ this, cases lookup a l; exact dec_trivial end 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 mem_of_perm p 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 x ys, { constructor }, iterate 2 { specialize h x, simp at h, cases h }, simp at nd₀ nd₁, rename x y, 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 a }, 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_erase, specialize h x, simp [h'] at h, exact h } } end 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, exact λ H, H b (or.inl rfl) }, { 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 (map_sublist_map _ $ lookup_all_sublist a l) 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 (nodupkeys_iff_pairwise.1 nd).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 := subset_of_sublist (map_sublist_map _ (kerase_sublist a l)) 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₁] /- 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₂ := perm.skip ⟨a, b⟩ $ perm_kerase nd₁ p 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 -/ def erase_dupkeys : list (sigma β) → list (sigma β) := list.foldr (λ ⟨x,y⟩, kinsert x y) [] lemma erase_dupkeys_cons {x : α} {y : β x} (l : list (sigma β)) : erase_dupkeys (⟨x,y⟩ :: l) = kinsert x y (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 /- 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_left {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.skip : hd tl₁ tl₂ p ih { simp [ih (kerase hd.1 l), perm.skip] }, 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_right : ∀ 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 [perm.skip s (perm_kunion_right l (kerase_nodupkeys s.1 nd₁) (perm_kerase nd₁ p))] theorem perm_kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys) (p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ := perm.trans (perm_kunion_left p₁₂ l₃) (perm_kunion_right l₂ nd₃ p₃₄) @[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
86f158a53419b567da7bf31b1de351e2a34feed5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/version_auto.lean
1c659deb90da36b4fe78576c7112bbcb76dcf8a5
[]
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
432
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.nat.basic import Mathlib.Lean3Lib.init.data.string.basic namespace Mathlib def lean.version : ℕ × ℕ × ℕ := (bit1 1, bit0 (bit1 (bit0 (bit1 1))), 0) def lean.githash : string := sorry def lean.is_release : Bool := to_bool (1 ≠ 0) /-- Additional version description like "nightly-2018-03-11" -/ def lean.special_version_desc : string := string.empty end Mathlib
00bba2a0c304458a0e9074dd952b4eb3f0098d24
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world8/level8.lean
5df923ab0e70bb7fe11d66e7895a42f7dcdca32a
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
578
lean
import game.world8.level7 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 8: `eq_zero_of_add_right_eq_self` The lemma you're about to prove will be useful when we want to prove that $\leq$ is antisymmetric. There are some wrong paths that you can take with this one. -/ /- Lemma If $a$ and $b$ are natural numbers such that $$ a + b = a, $$ then $b = 0$. -/ lemma eq_zero_of_add_right_eq_self {a b : mynat} : a + b = a → b = 0 := begin [nat_num_game] intro h, apply add_left_cancel a, rw h, rw add_zero, refl, end end mynat -- hide
e9c5f74182aeede1cc12c0f62de35ca397cf0886
f57749ca63d6416f807b770f67559503fdb21001
/library/theories/group_theory/pgroup.lean
0dbce534e22a0bb3579a54b97198674203d5f4fb
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,393
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import theories.number_theory.primes data algebra.group algebra.group_power algebra.group_bigops .cyclic .finsubg .hom .perm .action open nat fin list algebra function subtype namespace group section pgroup open finset fintype variables {G S : Type} [ambientG : group G] [deceqG : decidable_eq G] [finS : fintype S] [deceqS : decidable_eq S] include ambientG definition psubg (H : finset G) (p m : nat) : Prop := prime p ∧ card H = p^m include deceqG finS deceqS variables {H : finset G} [subgH : is_finsubg H] include subgH variables {hom : G → perm S} [Hom : is_hom_class hom] include Hom open finset.partition lemma card_mod_eq_of_action_by_psubg {p : nat} : ∀ {m : nat}, psubg H p m → (card S) mod p = (card (fixed_points hom H)) mod p | 0 := by rewrite [↑psubg, pow_zero]; intro Psubg; rewrite [finsubg_eq_singleton_one_of_card_one (and.right Psubg), fixed_points_of_one] | (succ m) := take Ppsubg, begin rewrite [@orbit_class_equation' G S ambientG finS deceqS hom Hom H subgH], apply add_mod_eq_of_dvd, apply dvd_Sum_of_dvd, intro s Psin, rewrite mem_filter_iff at Psin, cases Psin with Psinorbs Pcardne, esimp [orbits, equiv_classes, orbit_partition] at Psinorbs, rewrite mem_image_iff at Psinorbs, cases Psinorbs with a Pa, cases Pa with Pain Porb, substvars, cases Ppsubg with Pprime PcardH, assert Pdvd : card (orbit hom H a) ∣ p ^ (succ m), rewrite -PcardH, apply dvd_of_eq_mul (finset.card (stab hom H a)), apply orbit_stabilizer_theorem, apply or.elim (eq_one_or_dvd_of_dvd_prime_pow Pprime Pdvd), intro Pcardeq, contradiction, intro Ppdvd, exact Ppdvd end end pgroup section psubg_cosets open finset fintype variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G] include ambientG deceqG finG variables {H : finset G} [finsubgH : is_finsubg H] include finsubgH lemma card_psubg_cosets_mod_eq {p : nat} {m : nat} : psubg H p m → (card (lcoset_type univ H)) mod p = card (lcoset_type (normalizer H) H) mod p := assume Psubg, by rewrite [-card_aol_fixed_points_eq_card_cosets]; exact card_mod_eq_of_action_by_psubg Psubg end psubg_cosets section cauchy lemma prodl_rotl_eq_one_of_prodl_eq_one {A B : Type} [gB : group B] {f : A → B} : ∀ {l : list A}, Prodl l f = 1 → Prodl (list.rotl l) f = 1 | nil := assume Peq, rfl | (a::l) := begin rewrite [rotl_cons, Prodl_cons f, Prodl_append _ _ f, Prodl_singleton], exact mul_eq_one_of_mul_eq_one end section rotl_peo variables {A : Type} [ambA : group A] include ambA variable [finA : fintype A] include finA variable (A) definition all_prodl_eq_one (n : nat) : list (list A) := map (λ l, cons (Prodl l id)⁻¹ l) (all_lists_of_len n) variable {A} lemma prodl_eq_one_of_mem_all_prodl_eq_one {n : nat} {l : list A} : l ∈ all_prodl_eq_one A n → Prodl l id = 1 := assume Plin, obtain l' Pl' Pl, from exists_of_mem_map Plin, by substvars; rewrite [Prodl_cons id _ l', mul.left_inv] lemma length_of_mem_all_prodl_eq_one {n : nat} {l : list A} : l ∈ all_prodl_eq_one A n → length l = succ n := assume Plin, obtain l' Pl' Pl, from exists_of_mem_map Plin, begin substvars, rewrite [length_cons, length_mem_all_lists Pl'] end lemma nodup_all_prodl_eq_one {n : nat} : nodup (all_prodl_eq_one A n) := nodup_map (take l₁ l₂ Peq, tail_eq_of_cons_eq Peq) nodup_all_lists lemma all_prodl_eq_one_complete {n : nat} : ∀ {l : list A}, length l = succ n → Prodl l id = 1 → l ∈ all_prodl_eq_one A n | nil := assume Pleq, by contradiction | (a::l) := assume Pleq Pprod, begin rewrite length_cons at Pleq, rewrite (Prodl_cons id a l) at Pprod, rewrite [eq_inv_of_mul_eq_one Pprod], apply mem_map, apply mem_all_lists, apply succ.inj Pleq end open fintype lemma length_all_prodl_eq_one {n : nat} : length (@all_prodl_eq_one A _ _ n) = (card A)^n := eq.trans !length_map length_all_lists open fin definition prodseq {n : nat} (s : seq A n) : A := Prodl (upto n) s definition peo [reducible] {n : nat} (s : seq A n) := prodseq s = 1 definition constseq {n : nat} (s : seq A (succ n)) := ∀ i, s i = s !zero lemma prodseq_eq {n :nat} {s : seq A n} : prodseq s = Prodl (fun_to_list s) id := Prodl_map lemma prodseq_eq_pow_of_constseq {n : nat} (s : seq A (succ n)) : constseq s → prodseq s = (s !zero) ^ succ n := assume Pc, assert Pcl : ∀ i, i ∈ upto (succ n) → s i = s !zero, from take i, assume Pin, Pc i, by rewrite [↑prodseq, Prodl_eq_pow_of_const _ Pcl, fin.length_upto] lemma seq_eq_of_constseq_of_eq {n : nat} {s₁ s₂ : seq A (succ n)} : constseq s₁ → constseq s₂ → s₁ !zero = s₂ !zero → s₁ = s₂ := assume Pc₁ Pc₂ Peq, funext take i, by rewrite [Pc₁ i, Pc₂ i, Peq] lemma peo_const_one : ∀ {n : nat}, peo (λ i : fin n, (1 : A)) | 0 := rfl | (succ n) := let s := λ i : fin (succ n), (1 : A) in assert Pconst : constseq s, from take i, rfl, calc prodseq s = (s !zero) ^ succ n : prodseq_eq_pow_of_constseq s Pconst ... = (1 : A) ^ succ n : rfl ... = 1 : algebra.one_pow variable [deceqA : decidable_eq A] include deceqA variable (A) definition peo_seq [reducible] (n : nat) := {s : seq A (succ n) | peo s} definition peo_seq_one (n : nat) : peo_seq A n := tag (λ i : fin (succ n), (1 : A)) peo_const_one definition all_prodseq_eq_one (n : nat) : list (seq A (succ n)) := dmap (λ l, length l = card (fin (succ n))) list_to_fun (all_prodl_eq_one A n) definition all_peo_seqs (n : nat) : list (peo_seq A n) := dmap peo tag (all_prodseq_eq_one A n) variable {A} lemma prodseq_eq_one_of_mem_all_prodseq_eq_one {n : nat} {s : seq A (succ n)} : s ∈ all_prodseq_eq_one A n → prodseq s = 1 := assume Psin, obtain l Pex, from exists_of_mem_dmap Psin, obtain leq Pin Peq, from Pex, by rewrite [prodseq_eq, Peq, list_to_fun_to_list, prodl_eq_one_of_mem_all_prodl_eq_one Pin] lemma all_prodseq_eq_one_complete {n : nat} {s : seq A (succ n)} : prodseq s = 1 → s ∈ all_prodseq_eq_one A n := assume Peq, assert Plin : map s (elems (fin (succ n))) ∈ all_prodl_eq_one A n, from begin apply all_prodl_eq_one_complete, rewrite [length_map], exact length_upto (succ n), rewrite prodseq_eq at Peq, exact Peq end, assert Psin : list_to_fun (map s (elems (fin (succ n)))) (length_map_of_fintype s) ∈ all_prodseq_eq_one A n, from mem_dmap _ Plin, by rewrite [fun_eq_list_to_fun_map s (length_map_of_fintype s)]; apply Psin lemma nodup_all_prodseq_eq_one {n : nat} : nodup (all_prodseq_eq_one A n) := dmap_nodup_of_dinj dinj_list_to_fun nodup_all_prodl_eq_one lemma rotl1_peo_of_peo {n : nat} {s : seq A n} : peo s → peo (rotl_fun 1 s) := begin rewrite [↑peo, *prodseq_eq, seq_rotl_eq_list_rotl], apply prodl_rotl_eq_one_of_prodl_eq_one end section local attribute perm.f [coercion] lemma rotl_perm_peo_of_peo {n : nat} : ∀ {m} {s : seq A n}, peo s → peo (rotl_perm A n m s) | 0 := begin rewrite [↑rotl_perm, rotl_seq_zero], intros, assumption end | (succ m) := take s, assert Pmul : rotl_perm A n (m + 1) s = rotl_fun 1 (rotl_perm A n m s), from calc s ∘ (rotl (m + 1)) = s ∘ ((rotl m) ∘ (rotl 1)) : rotl_compose ... = s ∘ (rotl m) ∘ (rotl 1) : compose.assoc, begin rewrite [-add_one, Pmul], intro P, exact rotl1_peo_of_peo (rotl_perm_peo_of_peo P) end end lemma nodup_all_peo_seqs {n : nat} : nodup (all_peo_seqs A n) := dmap_nodup_of_dinj (dinj_tag peo) nodup_all_prodseq_eq_one lemma all_peo_seqs_complete {n : nat} : ∀ s : peo_seq A n, s ∈ all_peo_seqs A n := take ps, subtype.destruct ps (take s, assume Ps, assert Pin : s ∈ all_prodseq_eq_one A n, from all_prodseq_eq_one_complete Ps, mem_dmap Ps Pin) lemma length_all_peo_seqs {n : nat} : length (all_peo_seqs A n) = (card A)^n := eq.trans (eq.trans (show length (all_peo_seqs A n) = length (all_prodseq_eq_one A n), from assert Pmap : map elt_of (all_peo_seqs A n) = all_prodseq_eq_one A n, from map_dmap_of_inv_of_pos (λ s P, rfl) (λ s, prodseq_eq_one_of_mem_all_prodseq_eq_one), by rewrite [-Pmap, length_map]) (show length (all_prodseq_eq_one A n) = length (all_prodl_eq_one A n), from assert Pmap : map fun_to_list (all_prodseq_eq_one A n) = all_prodl_eq_one A n, from map_dmap_of_inv_of_pos list_to_fun_to_list (λ l Pin, by rewrite [length_of_mem_all_prodl_eq_one Pin, card_fin]), by rewrite [-Pmap, length_map])) length_all_prodl_eq_one definition peo_seq_is_fintype [instance] {n : nat} : fintype (peo_seq A n) := fintype.mk (all_peo_seqs A n) nodup_all_peo_seqs all_peo_seqs_complete lemma card_peo_seq {n : nat} : card (peo_seq A n) = (card A)^n := length_all_peo_seqs section variable (A) local attribute perm.f [coercion] definition rotl_peo_seq (n : nat) (m : nat) (s : peo_seq A n) : peo_seq A n := tag (rotl_perm A (succ n) m (elt_of s)) (rotl_perm_peo_of_peo (has_property s)) variable {A} end lemma rotl_peo_seq_zero {n : nat} : rotl_peo_seq A n 0 = id := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, ↑rotl_perm, rotl_seq_zero] end lemma rotl_peo_seq_id {n : nat} : rotl_peo_seq A n (succ n) = id := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, -rotl_perm_pow_eq, rotl_perm_pow_eq_one] end lemma rotl_peo_seq_compose {n i j : nat} : (rotl_peo_seq A n i) ∘ (rotl_peo_seq A n j) = rotl_peo_seq A n (j + i) := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, ↑rotl_perm, ↑rotl_fun, compose.assoc, rotl_compose] end lemma rotl_peo_seq_mod {n i : nat} : rotl_peo_seq A n i = rotl_peo_seq A n (i mod succ n) := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, rotl_perm_mod] end lemma rotl_peo_seq_inj {n m : nat} : injective (rotl_peo_seq A n m) := take ps₁ ps₂, subtype.destruct ps₁ (λ s₁ P₁, subtype.destruct ps₂ (λ s₂ P₂, assume Peq, tag_eq (rotl_fun_inj (dinj_tag peo _ _ Peq)))) variable (A) definition rotl_perm_ps [reducible] (n : nat) (m : fin (succ n)) : perm (peo_seq A n) := perm.mk (rotl_peo_seq A n m) rotl_peo_seq_inj variable {A} variable {n : nat} lemma rotl_perm_ps_eq {m : fin (succ n)} {s : peo_seq A n} : elt_of (perm.f (rotl_perm_ps A n m) s) = perm.f (rotl_perm A (succ n) m) (elt_of s) := rfl lemma rotl_perm_ps_eq_of_rotl_perm_eq {i j : fin (succ n)} : (rotl_perm A (succ n) i) = (rotl_perm A (succ n) j) → (rotl_perm_ps A n i) = (rotl_perm_ps A n j) := assume Peq, eq_of_feq (funext take s, subtype.eq (by rewrite [*rotl_perm_ps_eq, Peq])) lemma rotl_perm_ps_hom (i j : fin (succ n)) : rotl_perm_ps A n (i+j) = (rotl_perm_ps A n i) * (rotl_perm_ps A n j) := eq_of_feq (begin rewrite [↑rotl_perm_ps, {val (i+j)}val_madd, add.comm, -rotl_peo_seq_mod, -rotl_peo_seq_compose] end) section local attribute group_of_add_group [instance] definition rotl_perm_ps_is_hom [instance] : is_hom_class (rotl_perm_ps A n) := is_hom_class.mk rotl_perm_ps_hom open finset lemma const_of_is_fixed_point {s : peo_seq A n} : is_fixed_point (rotl_perm_ps A n) univ s → constseq (elt_of s) := assume Pfp, take i, begin rewrite [-(Pfp i !mem_univ) at {1}, rotl_perm_ps_eq, ↑rotl_perm, ↑rotl_fun, {i}mk_mod_eq at {2}, rotl_to_zero] end lemma const_of_rotl_fixed_point {s : peo_seq A n} : s ∈ fixed_points (rotl_perm_ps A n) univ → constseq (elt_of s) := assume Psin, take i, begin apply const_of_is_fixed_point, exact is_fixed_point_of_mem_fixed_points Psin end lemma pow_eq_one_of_mem_fixed_points {s : peo_seq A n} : s ∈ fixed_points (rotl_perm_ps A n) univ → (elt_of s !zero)^(succ n) = 1 := assume Psin, eq.trans (eq.symm (prodseq_eq_pow_of_constseq (elt_of s) (const_of_rotl_fixed_point Psin))) (has_property s) lemma peo_seq_one_is_fixed_point : is_fixed_point (rotl_perm_ps A n) univ (peo_seq_one A n) := take h, assume Pin, by esimp [rotl_perm_ps] lemma peo_seq_one_mem_fixed_points : peo_seq_one A n ∈ fixed_points (rotl_perm_ps A n) univ := mem_fixed_points_of_exists_of_is_fixed_point (exists.intro !zero !mem_univ) peo_seq_one_is_fixed_point lemma generator_of_prime_of_dvd_order {p : nat} : prime p → p ∣ card A → ∃ g : A, g ≠ 1 ∧ g^p = 1 := assume Pprime Pdvd, let pp := nat.pred p, spp := nat.succ pp in assert Peq : spp = p, from succ_pred_prime Pprime, have Ppsubg : psubg (@univ (fin spp) _) spp 1, from and.intro (eq.symm Peq ▸ Pprime) (by rewrite [Peq, card_fin, pow_one]), have Pcardmod : (nat.pow (card A) pp) mod p = (card (fixed_points (rotl_perm_ps A pp) univ)) mod p, from Peq ▸ card_peo_seq ▸ card_mod_eq_of_action_by_psubg Ppsubg, have Pfpcardmod : (card (fixed_points (rotl_perm_ps A pp) univ)) mod p = 0, from eq.trans (eq.symm Pcardmod) (mod_eq_zero_of_dvd (dvd_pow_of_dvd_of_pos Pdvd (pred_prime_pos Pprime))), have Pfpcardpos : card (fixed_points (rotl_perm_ps A pp) univ) > 0, from card_pos_of_mem peo_seq_one_mem_fixed_points, have Pfpcardgt1 : card (fixed_points (rotl_perm_ps A pp) univ) > 1, from gt_one_of_pos_of_prime_dvd Pprime Pfpcardpos Pfpcardmod, obtain s₁ s₂ Pin₁ Pin₂ Psnes, from exists_two_of_card_gt_one Pfpcardgt1, decidable.by_cases (λ Pe₁ : elt_of s₁ !zero = 1, assert Pne₂ : elt_of s₂ !zero ≠ 1, from assume Pe₂, absurd (subtype.eq (seq_eq_of_constseq_of_eq (const_of_rotl_fixed_point Pin₁) (const_of_rotl_fixed_point Pin₂) (eq.trans Pe₁ (eq.symm Pe₂)))) Psnes, exists.intro (elt_of s₂ !zero) (and.intro Pne₂ (Peq ▸ pow_eq_one_of_mem_fixed_points Pin₂))) (λ Pne, exists.intro (elt_of s₁ !zero) (and.intro Pne (Peq ▸ pow_eq_one_of_mem_fixed_points Pin₁))) end theorem cauchy_theorem {p : nat} : prime p → p ∣ card A → ∃ g : A, order g = p := assume Pprime Pdvd, obtain g Pne Pgpow, from generator_of_prime_of_dvd_order Pprime Pdvd, assert Porder : order g ∣ p, from order_dvd_of_pow_eq_one Pgpow, or.elim (eq_one_or_eq_self_of_prime_of_dvd Pprime Porder) (λ Pe, absurd (eq_one_of_order_eq_one Pe) Pne) (λ Porderp, exists.intro g Porderp) end rotl_peo end cauchy section sylow open finset fintype variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G] include ambientG deceqG finG theorem first_sylow_theorem {p : nat} (Pp : prime p) : ∀ n, p^n ∣ card G → ∃ (H : finset G) (finsubgH : is_finsubg H), card H = p^n | 0 := assume Pdvd, exists.intro (singleton 1) (exists.intro one_is_finsubg (by rewrite [card_singleton, pow_zero])) | (succ n) := assume Pdvd, obtain H PfinsubgH PcardH, from first_sylow_theorem n (pow_dvd_of_pow_succ_dvd Pdvd), assert Ppsubg : psubg H p n, from and.intro Pp PcardH, assert Ppowsucc : p^(succ n) ∣ (card (lcoset_type univ H) * p^n), by rewrite [-PcardH, -(lagrange_theorem' !subset_univ)]; exact Pdvd, assert Ppdvd : p ∣ card (lcoset_type (normalizer H) H), from dvd_of_mod_eq_zero (by rewrite [-(card_psubg_cosets_mod_eq Ppsubg), -dvd_iff_mod_eq_zero]; exact dvd_of_pow_succ_dvd_mul_pow (pos_of_prime Pp) Ppowsucc), obtain J PJ, from cauchy_theorem Pp Ppdvd, exists.intro (fin_coset_Union (cyc J)) (exists.intro _ (by rewrite [pow_succ', -PcardH, -PJ]; apply card_Union_lcosets)) end sylow end group
4ff1d9ff584c28ae93325833e92d0fd86f73631c
4efff1f47634ff19e2f786deadd394270a59ecd2
/test/slim_check.lean
025d7376eb6e586f449202eba85fd20c36714121
[ "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
2,425
lean
import system.random.basic import data.nat.prime import data.zmod.basic /-- fermat's primality test -/ def primality_test (p : ℕ) (h : fact (0 < p)) : rand bool := if h : 2 ≤ p-1 then do n ← rand.random_r 2 (p-1) h, return $ (n : zmod p)^(p-1) = 1 -- we do arithmetic with `zmod n` so that modulo and multiplication are interleaved else return (p = 2) /-- `iterated_primality_test_aux p h n` generating `n` candidate witnesses that `p` is a composite number and concludes that `p` is prime if none of them is a valid witness -/ def iterated_primality_test_aux (p : ℕ) (h : fact (0 < p)) : ℕ → rand bool | 0 := pure tt | (n+1) := do b ← primality_test p h, if b then iterated_primality_test_aux n else pure ff def iterated_primality_test (p : ℕ) : rand bool := if h : 0 < p then iterated_primality_test_aux p h 10 else pure ff /-- `find_prime_aux p h n` generates a candidate prime number, tests it as well as the 19 odd numbers following it. If none of them is (probably) prime, try again `n-1` times. -/ def find_prime_aux (p : ℕ) (h : 1 ≤ p / 2) : ℕ → rand (option ℕ) | 0 := pure none | (n+1) := do k ← rand.random_r 1 (p / 2) h, let xs := (list.range' k 20).map (λ i, 2*i+1), some r ← option_t.run $ xs.mfirst (λ n, option_t.mk $ mcond (iterated_primality_test n) (pure (some n)) (pure none)) | find_prime_aux n, pure r def find_prime (p : ℕ) : rand (option ℕ) := if h : 1 ≤ p / 2 then find_prime_aux p h 20 else pure none open tactic /- `ps` should be `[97, 101, 103, 107, 109, 113]` but it uses a pseudo primality test and some composite numbers also sneak in -/ run_cmd do let xs := list.range' 90 30, ps ← tactic.run_rand (xs.mfilter iterated_primality_test), when (ps ≠ [97, 101, 103, 107, 109, 113]) (trace!"The random primality test also included some composite numbers: {ps}") /- `ps` should be `[97, 101, 103, 107, 109, 113]`. This test is deterministic because we pick the random seed -/ run_cmd do let xs := list.range' 90 30, let ps : list ℕ := (xs.mfilter iterated_primality_test).eval ⟨ mk_std_gen 10 ⟩, guard (ps = [97, 101, 103, 107, 109, 113]) <|> fail "wrong list of prime numbers" /- this finds a random probably-prime number -/ run_cmd do some p ← tactic.run_rand (find_prime 100000) | trace "no prime found, gave up", when (¬ nat.prime p) (trace!"The number {p} fooled Fermat's test")
fb8d1c00139bd461e83c849d0bdb78159a88dc6c
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/data/polynomial/eval.lean
6c27b23ce75ae6f53eec5bc6034eef3d6b60d1a3
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,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.induction import data.polynomial.degree.definitions import deprecated.ring /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w y variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section variables [semiring S] variables (f : R →+* S) (x : S) /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial R) : S := p.sum (λ e a, f a * x ^ e) lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl lemma eval₂_congr {R S : Type*} [semiring R] [semiring S] {f g : R →+* S} {s t : S} {φ ψ : polynomial R} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := by rintro rfl rfl rfl; refl @[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by simp [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by rw [f.map_one, one_mul, pow_one] @[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n := begin apply sum_single_index, simp, end @[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n := begin rw X_pow_eq_monomial, convert eval₂_monomial f x, simp, end @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [f.map_zero, zero_mul]) (λ _ _ _, by rw [f.map_add, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 := by rw [← C_1, eval₂_C, f.map_one] @[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) := by rw [bit0, eval₂_add, bit0] @[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) := by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1] @[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = g s • eval₂ g x p := begin simp only [eval₂, sum_smul_index, forall_const, zero_mul, g.map_zero, g.map_mul, mul_assoc], -- Why doesn't `rw [←finsupp.mul_sum]` work? convert (@finsupp.mul_sum _ _ _ _ _ (g s) p (λ i a, (g a * x ^ i))).symm, end @[simp] lemma eval₂_C_X : eval₂ C X p = p := polynomial.induction_on' p (λ p q hp hq, by simp [hp, hq]) (λ n x, by rw [eval₂_monomial, monomial_eq_smul_X, C_mul']) instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } @[simp] lemma eval₂_nat_cast (n : ℕ) : (n : polynomial R).eval₂ f x = n := nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ] variables [semiring T] lemma eval₂_sum (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) lemma eval₂_finset_sum (s : finset ι) (g : ι → polynomial R) (x : S) : (∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x := begin classical, induction s using finset.induction with p hp s hs, simp, rw [sum_insert, eval₂_add, hs, sum_insert]; assumption, end lemma eval₂_mul_noncomm (hf : ∀ b a, f b * a = a * f b) : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin have f_zero : ∀ (a : ℕ), f 0 * x ^ a = 0, { intro, simp }, have f_add : ∀ (a : ℕ) (b₁ b₂ : R), f (b₁ + b₂) * x ^ a = f b₁ * x ^ a + f b₂ * x ^ a, { intros, rw [f.map_add, add_mul] }, simp_rw [eval₂, add_monoid_algebra.mul_def, finsupp.sum_mul _ p, finsupp.mul_sum _ q], rw sum_sum_index; try { assumption }, apply sum_congr rfl, assume i hi, dsimp only, rw sum_sum_index; try { assumption }, apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, is_semiring_hom.map_mul f, pow_add], { rw [mul_assoc, ←mul_assoc _ (x ^ i), hf _ (x ^ i), mul_assoc, mul_assoc] }, { apply f_zero } end lemma eval₂_list_prod_noncomm (ps : list (polynomial R)) (hf : ∀ b a, f b * a = a * f b): ps.prod.eval₂ f x = (ps.map (polynomial.eval₂ f x)).prod := begin induction ps, { simp }, { simp [eval₂_mul_noncomm _ _ hf, ps_ih] {contextual := tt} } end /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' (f : R →+* S) (hf : ∀ b a, f b * a = a * f b) (x : S) : polynomial R →+* S := { to_fun := eval₂ f x, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ _ _, eval₂_mul_noncomm _ _ hf, map_one' := eval₂_one _ _ } end /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ section eval₂ variables [comm_semiring S] variables (f : R →+* S) (x : S) @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin apply eval₂_mul_noncomm, simp [mul_comm] end lemma eval₂_mul_eq_zero_of_left (q : polynomial R) (hp : p.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_left hp (q.eval₂ f x) end lemma eval₂_mul_eq_zero_of_right (p : polynomial R) (hq : q.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_right (p.eval₂ f x) hq end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x) : polynomial R →+* S := ring_hom.of (eval₂ f x) @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _ lemma eval₂_eq_sum_range : p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i := trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp))) lemma eval₂_eq_sum_range' (f : R →+* S) {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) : eval₂ f x p = ∑ i in finset.range n, f (p.coeff i) * x ^ i := begin rw [eval₂_eq_sum, p.sum_over_range' _ _ hn], intro i, rw [f.map_zero, zero_mul] end end eval₂ section eval variables {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → polynomial R → R := eval₂ (ring_hom.id _) lemma eval_eq_sum : p.eval x = sum p (λ e a, a * x ^ e) := rfl @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_nat_cast {n : ℕ} : (n : polynomial R).eval x = n := by simp only [←C_eq_nat_cast, eval_C] @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n := eval₂_monomial _ _ @[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _ @[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _ @[simp] lemma eval_smul (p : polynomial R) (x : R) {s : R} : (s • p).eval x = s • p.eval x := eval₂_smul (ring_hom.id _) _ _ lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval_finset_sum (s : finset ι) (g : ι → polynomial R) (x : R) : (∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma coeff_zero_eq_eval_zero (p : polynomial R) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp end eval section comp /-- The composition of polynomials as a polynomial. -/ def comp (p q : polynomial R) : polynomial R := p.eval₂ C q lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) := rfl @[simp] lemma comp_X : p.comp X = p := begin simp only [comp, eval₂, ← single_eq_C_mul_X], exact finsupp.sum_single _, end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← p.support.sum_hom (@C R _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial R) p = 1 := by rw [← C_1, C_comp] @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : polynomial R) : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ @[simp] lemma bit0_comp : comp (bit0 p : polynomial R) q = bit0 (p.comp q) := by simp only [bit0, add_comp] @[simp] lemma bit1_comp : comp (bit1 p : polynomial R) q = bit1 (p.comp q) := by simp only [bit1, add_comp, bit0_comp, one_comp] lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : polynomial R) : (φ.comp ψ).comp χ = φ.comp (ψ.comp χ) := begin apply polynomial.induction_on φ; { intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * } end end comp section map variables [semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial R → polynomial S := eval₂ (C.comp f) X instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) := is_semiring_hom.comp _ _ @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) := begin dsimp only [map], rw [eval₂_monomial, single_eq_C_mul_X], refl, end @[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _ @[simp] theorem map_nat_cast (n : ℕ) : (n : polynomial R).map f = n := nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, map_add, ih, map_one, n.cast_succ] @[simp] lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← p.support.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, f.map_mul], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map [semiring T] (g : S →+* T) (p : polynomial R) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end lemma map_injective (hf : function.injective f) : function.injective (map f) := λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h] lemma map_surjective (hf : function.surjective f) : function.surjective (map f) := λ p, polynomial.induction_on' p (λ p q hp hq, let ⟨p', hp'⟩ := hp, ⟨q', hq'⟩ := hq in ⟨p' + q', by rw [map_add f, hp', hq']⟩) (λ n s, let ⟨r, hr⟩ := hf s in ⟨monomial n r, by rw [map_monomial f, hr]⟩) variables {f} lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 := ⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp [hp] ... = f x * (p.map f).coeff p.nat_degree : by { congr, apply (coeff_map _ _).symm } ... = 0 : by simp [hfp], λ h, ext (λ n, trans (coeff_map f n) (h _)) ⟩ lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 := λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _) variables (f) open is_semiring_hom -- If the rings were commutative, we could prove this just using `eval₂_mul`. -- TODO this proof is just a hack job on the proof of `eval₂_mul`, -- using that `X` is central. It should probably be golfed! @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := begin dunfold map, dunfold eval₂, rw [add_monoid_algebra.mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, (C.comp f).map_mul, pow_add], { simp [←mul_assoc], conv_lhs { rw ←@X_pow_mul_assoc _ _ _ _ i }, }, { simp, } }, { intro, simp, }, { intros, simp [add_mul], } }, { intro, simp, }, { intros, simp [add_mul], } end instance map.is_semiring_hom : is_semiring_hom (map f) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ _ _, eval₂_add _ _, map_mul := λ _ _, map_mul f, } /-- `polynomial.map` as a `ring_hom` -/ def map_ring_hom (f : R →+* S) : polynomial R →+* polynomial S := ring_hom.of (map f) @[simp] lemma coe_map_ring_hom (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl lemma map_list_prod (L : list (polynomial R)) : L.prod.map f = (L.map $ map f).prod := eq.symm $ list.prod_hom _ (monoid_hom.of (map f)) @[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := is_monoid_hom.map_pow (map f) _ _ lemma mem_map_range {p : polynomial S} : p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) := begin split, { rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ }, { intro h, rw p.as_sum_range_C_mul_X_pow, apply is_add_submonoid.finset_sum_mem, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [map_mul, map_C, hc, map_pow, map_X] } end lemma eval₂_map [semiring T] (g : S →+* T) (x : T) : (p.map f).eval₂ g x = p.eval₂ (g.comp f) x := begin convert finsupp.sum_map_range_index _, { change map f p = map_range f _ p, ext, rw map_range_apply, exact coeff_map f a, }, { exact f.map_zero, }, { intro a, simp only [ring_hom.map_zero, zero_mul], }, end lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := eval₂_map f (ring_hom.id _) x lemma map_sum {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∑ i in s, g i).map f = ∑ i in s, (g i).map f := eq.symm $ sum_hom _ _ end map /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ attribute [irreducible] polynomial.eval₂ section hom_eval₂ -- TODO: Here we need commutativity in both `S` and `T`? variables [comm_semiring S] [comm_semiring T] variables (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) := begin apply polynomial.induction_on p; clear p, { intros a, rw [eval₂_C, eval₂_C], refl, }, { intros p q hp hq, simp only [hp, hq, eval₂_add, g.map_add] }, { intros n a ih, simp only [eval₂_mul, eval₂_C, eval₂_X_pow, g.map_mul, g.map_pow], refl, } end end hom_eval₂ end semiring section comm_semiring section eval variables [comm_semiring R] {p q : polynomial R} {x : R} @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) : p.eval₂ f (f x) = f (p.eval x) := (ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] /-- Polynomial evaluation commutes with finset.prod -/ lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := begin classical, apply finset.induction_on s, { simp only [finset.prod_empty, eval_one] }, { intros j s hj hpj, have h0 : ∏ i in insert j s, eval x (p i) = (eval x (p j)) * ∏ i in s, eval x (p i), { apply finset.prod_insert hj }, rw [h0, ← hpj, finset.prod_insert hj, eval_mul] }, end end eval section map variables [comm_semiring R] [comm_semiring S] (f : R →+* S) lemma map_multiset_prod (m : multiset (polynomial R)) : m.prod.map f = (m.map $ map f).prod := eq.symm $ multiset.prod_hom _ (monoid_hom.of (map f)) lemma map_prod {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∏ i in s, g i).map f = ∏ i in s, (g i).map f := eq.symm $ prod_hom _ _ lemma support_map_subset (p : polynomial R) : (map f p).support ⊆ p.support := begin intros x, simp only [mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f, end lemma map_comp (p q : polynomial R) : map f (p.comp q) = (map f p).comp (map f q) := polynomial.induction_on p (by simp) (by simp {contextual := tt}) (by simp [pow_succ', ← mul_assoc, polynomial.comp] {contextual := tt}) end map end comm_semiring section ring variables [ring R] {p q r : polynomial R} -- @[simp] -- lemma C_eq_int_cast (n : ℤ) : C ↑n = (n : polynomial R) := -- (C : R →+* _).map_int_cast n lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b instance map.is_ring_hom {S} [ring S] (f : R →+* S) : is_ring_hom (map f) := by apply is_ring_hom.of_semiring @[simp] lemma map_sub {S} [ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {S} [ring S] (f : R →+* S) : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma map_int_cast {S} [ring S] (f : R →+* S) (n : ℤ) : map f ↑n = ↑n := (ring_hom.of (map f)).map_int_cast n @[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : polynomial R).eval x = n := by simp only [←C_eq_int_cast, eval_C] @[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} : (-p).eval₂ f x = -p.eval₂ f x := by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero] @[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg] @[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x := eval₂_neg _ @[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x := eval₂_sub _ lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] @[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _ @[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _ end ring section comm_ring variables [comm_ring R] {p q : polynomial R} instance eval₂.is_ring_hom {S} [comm_ring S] (f : R →+* S) {x : S} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom _ end comm_ring end polynomial
238f2c6845ade2a7b4bc6436f5d1ce165d25df1f
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/stuckTC.lean
ec65d2c100af04fdcf08085d2db4ccd9ddeb3dbb
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,046
lean
namespace Ex1 inductive Ty where | int | bool | fn (a ty : Ty) @[reducible] def Ty.interp : Ty → Type | int => Int | bool => Bool | fn a b => a.interp → b.interp def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp := f x y def f (a b : Ty.bool.interp) : Ty.bool.interp := test (.==.) a b end Ex1 namespace Ex2 inductive Ty where | int | bool @[reducible] def Ty.interp : Ty → Type | int => Int | bool => Bool def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp := f x y def f (a b : Ty.bool.interp) : Ty.bool.interp := test (.==.) a b end Ex2 namespace Ex3 inductive Ty where | int | bool @[reducible] def Ty.interp (ty : Ty) : Type := Ty.casesOn (motive := fun _ => Type) ty Int Bool def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp := f x y def f (a b : Ty.bool.interp) : Ty.bool.interp := test (.==.) a b end Ex3
f0f13b1116cc320125ea855cf97c58d1837bd68b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/gluing.lean
934a506d6500bfd5e59a7e45e5e0ec8016186af5
[ "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
18,567
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 topology.category.Top import category_theory.glue_data import category_theory.concrete_category.elementwise /-! # Gluing Topological spaces Given a family of gluing data (see `category_theory/glue_data`), we can then glue them together. The construction should be "sealed" and considered as a black box, while only using the API provided. ## Main definitions * `Top.glue_data`: A structure containing the family of gluing data. * `category_theory.glue_data.glued`: The glued topological space. This is defined as the multicoequalizer of `∐ V i j ⇉ ∐ U i`, so that the general colimit API can be used. * `category_theory.glue_data.ι`: The immersion `ι i : U i ⟶ glued` for each `i : ι`. * `Top.glue_data.rel`: A relation on `Σ i, D.U i` defined by `⟨i, x⟩ ~ ⟨j, y⟩` iff `⟨i, x⟩ = ⟨j, y⟩` or `t i j x = y`. See `Top.glue_data.ι_eq_iff_rel`. * `Top.glue_data.mk`: A constructor of `glue_data` whose conditions are stated in terms of elements rather than subobjects and pullbacks. * `Top.glue_data.of_open_subsets`: Given a family of open sets, we may glue them into a new topological space. This new space embeds into the original space, and is homeomorphic to it if the given family is an open cover (`Top.glue_data.open_cover_glue_homeo`). ## Main results * `Top.glue_data.is_open_iff`: A set in `glued` is open iff its preimage along each `ι i` is open. * `Top.glue_data.ι_jointly_surjective`: The `ι i`s are jointly surjective. * `Top.glue_data.rel_equiv`: `rel` is an equivalence relation. * `Top.glue_data.ι_eq_iff_rel`: `ι i x = ι j y ↔ ⟨i, x⟩ ~ ⟨j, y⟩`. * `Top.glue_data.image_inter`: The intersection of the images of `U i` and `U j` in `glued` is `V i j`. * `Top.glue_data.preimage_range`: The preimage of the image of `U i` in `U j` is `V i j`. * `Top.glue_data.preimage_image_eq_preimage_f`: The preimage of the image of some `U ⊆ U i` is given by the preimage along `f j i`. * `Top.glue_data.ι_open_embedding`: Each of the `ι i`s are open embeddings. -/ noncomputable theory open topological_space category_theory universes v u open category_theory.limits namespace Top /-- A family of gluing data consists of 1. An index type `J` 2. An object `U i` for each `i : J`. 3. An object `V i j` for each `i j : J`. (Note that this is `J × J → Top` rather than `J → J → Top` to connect to the limits library easier.) 4. An open embedding `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. (This merely means that `V i j ∩ V i k ⊆ t i j ⁻¹' (V j i ∩ V j k)`.) 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the topological spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. Most of the times it would be easier to use the constructor `Top.glue_data.mk'` where the conditions are stated in a less categorical way. -/ @[nolint has_nonempty_instance] structure glue_data extends glue_data Top := (f_open : ∀ i j, open_embedding (f i j)) (f_mono := λ i j, (Top.mono_iff_injective _).mpr (f_open i j).to_embedding.inj) namespace glue_data variable (D : glue_data.{u}) local notation `𝖣` := D.to_glue_data lemma π_surjective : function.surjective 𝖣 .π := (Top.epi_iff_surjective 𝖣 .π).mp infer_instance lemma is_open_iff (U : set 𝖣 .glued) : is_open U ↔ ∀ i, is_open (𝖣 .ι i ⁻¹' U) := begin delta category_theory.glue_data.ι, simp_rw ← multicoequalizer.ι_sigma_π 𝖣 .diagram, rw ← (homeo_of_iso (multicoequalizer.iso_coequalizer 𝖣 .diagram).symm).is_open_preimage, rw [coequalizer_is_open_iff, colimit_is_open_iff.{u}], split, { intros h j, exact h ⟨j⟩, }, { intros h j, cases j, exact h j, }, end lemma ι_jointly_surjective (x : 𝖣 .glued) : ∃ i (y : D.U i), 𝖣 .ι i y = x := 𝖣 .ι_jointly_surjective (forget Top) x /-- An equivalence relation on `Σ i, D.U i` that holds iff `𝖣 .ι i x = 𝖣 .ι j y`. See `Top.glue_data.ι_eq_iff_rel`. -/ def rel (a b : Σ i, ((D.U i : Top) : Type*)) : Prop := a = b ∨ ∃ (x : D.V (a.1, b.1)) , D.f _ _ x = a.2 ∧ D.f _ _ (D.t _ _ x) = b.2 lemma rel_equiv : equivalence D.rel := ⟨ λ x, or.inl (refl x), begin rintros a b (⟨⟨⟩⟩|⟨x,e₁,e₂⟩), exacts [or.inl rfl, or.inr ⟨D.t _ _ x, by simp [e₁, e₂]⟩] end, begin rintros ⟨i,a⟩ ⟨j,b⟩ ⟨k,c⟩ (⟨⟨⟩⟩|⟨x,e₁,e₂⟩), exact id, rintro (⟨⟨⟩⟩|⟨y,e₃,e₄⟩), exact or.inr ⟨x,e₁,e₂⟩, let z := (pullback_iso_prod_subtype (D.f j i) (D.f j k)).inv ⟨⟨_,_⟩, e₂.trans e₃.symm⟩, have eq₁ : (D.t j i) ((pullback.fst : _ ⟶ D.V _) z) = x := by simp, have eq₂ : (pullback.snd : _ ⟶ D.V _) z = y := pullback_iso_prod_subtype_inv_snd_apply _ _ _, clear_value z, right, use (pullback.fst : _ ⟶ D.V (i, k)) (D.t' _ _ _ z), dsimp only at *, substs e₁ e₃ e₄ eq₁ eq₂, have h₁ : D.t' j i k ≫ pullback.fst ≫ D.f i k = pullback.fst ≫ D.t j i ≫ D.f i j, { rw ← 𝖣 .t_fac_assoc, congr' 1, exact pullback.condition }, have h₂ : D.t' j i k ≫ pullback.fst ≫ D.t i k ≫ D.f k i = pullback.snd ≫ D.t j k ≫ D.f k j, { rw ← 𝖣 .t_fac_assoc, apply @epi.left_cancellation _ _ _ _ (D.t' k j i), rw [𝖣 .cocycle_assoc, 𝖣 .t_fac_assoc, 𝖣 .t_inv_assoc], exact pullback.condition.symm }, exact ⟨continuous_map.congr_fun h₁ z, continuous_map.congr_fun h₂ z⟩ end⟩ open category_theory.limits.walking_parallel_pair lemma eqv_gen_of_π_eq {x y : ∐ D.U} (h : 𝖣 .π x = 𝖣 .π y) : eqv_gen (types.coequalizer_rel 𝖣 .diagram.fst_sigma_map 𝖣 .diagram.snd_sigma_map) x y := begin delta glue_data.π multicoequalizer.sigma_π at h, simp_rw comp_app at h, replace h := (Top.mono_iff_injective (multicoequalizer.iso_coequalizer 𝖣 .diagram).inv).mp _ h, let diagram := parallel_pair 𝖣 .diagram.fst_sigma_map 𝖣 .diagram.snd_sigma_map ⋙ forget _, have : colimit.ι diagram one x = colimit.ι diagram one y, { rw ←ι_preserves_colimits_iso_hom, simp [h] }, have : (colimit.ι diagram _ ≫ colim.map _ ≫ (colimit.iso_colimit_cocone _).hom) _ = (colimit.ι diagram _ ≫ colim.map _ ≫ (colimit.iso_colimit_cocone _).hom) _ := (congr_arg (colim.map (diagram_iso_parallel_pair diagram).hom ≫ (colimit.iso_colimit_cocone (types.coequalizer_colimit _ _)).hom) this : _), simp only [eq_to_hom_refl, types_comp_apply, colimit.ι_map_assoc, diagram_iso_parallel_pair_hom_app, colimit.iso_colimit_cocone_ι_hom, types_id_apply] at this, exact quot.eq.1 this, apply_instance end lemma ι_eq_iff_rel (i j : D.J) (x : D.U i) (y : D.U j) : 𝖣 .ι i x = 𝖣 .ι j y ↔ D.rel ⟨i, x⟩ ⟨j, y⟩ := begin split, { delta glue_data.ι, simp_rw ← multicoequalizer.ι_sigma_π, intro h, rw ← (show _ = sigma.mk i x, from concrete_category.congr_hom (sigma_iso_sigma.{u} D.U).inv_hom_id _), rw ← (show _ = sigma.mk j y, from concrete_category.congr_hom (sigma_iso_sigma.{u} D.U).inv_hom_id _), change inv_image D.rel (sigma_iso_sigma.{u} D.U).hom _ _, simp only [Top.sigma_iso_sigma_inv_apply], rw ← (inv_image.equivalence _ _ D.rel_equiv).eqv_gen_iff, refine eqv_gen.mono _ (D.eqv_gen_of_π_eq h : _), rintros _ _ ⟨x⟩, rw ← (show (sigma_iso_sigma.{u} _).inv _ = x, from concrete_category.congr_hom (sigma_iso_sigma.{u} _).hom_inv_id x), generalize : (sigma_iso_sigma.{u} D.V).hom x = x', obtain ⟨⟨i,j⟩,y⟩ := x', unfold inv_image multispan_index.fst_sigma_map multispan_index.snd_sigma_map, simp only [opens.inclusion_apply, Top.comp_app, sigma_iso_sigma_inv_apply, category_theory.limits.colimit.ι_desc_apply, cofan.mk_ι_app, sigma_iso_sigma_hom_ι_apply, continuous_map.to_fun_eq_coe], erw [sigma_iso_sigma_hom_ι_apply, sigma_iso_sigma_hom_ι_apply], exact or.inr ⟨y, by { dsimp [glue_data.diagram], simp }⟩ }, { rintro (⟨⟨⟩⟩|⟨z,e₁,e₂⟩), refl, dsimp only at *, subst e₁, subst e₂, simp } end lemma ι_injective (i : D.J) : function.injective (𝖣 .ι i) := begin intros x y h, rcases (D.ι_eq_iff_rel _ _ _ _).mp h with (⟨⟨⟩⟩|⟨_,e₁,e₂⟩), { refl }, { dsimp only at *, cases e₁, cases e₂, simp } end instance ι_mono (i : D.J) : mono (𝖣 .ι i) := (Top.mono_iff_injective _).mpr (D.ι_injective _) lemma image_inter (i j : D.J) : set.range (𝖣 .ι i) ∩ set.range (𝖣 .ι j) = set.range (D.f i j ≫ 𝖣 .ι _) := begin ext x, split, { rintro ⟨⟨x₁, eq₁⟩, ⟨x₂, eq₂⟩⟩, obtain (⟨⟨⟩⟩|⟨y,e₁,e₂⟩) := (D.ι_eq_iff_rel _ _ _ _).mp (eq₁.trans eq₂.symm), { exact ⟨inv (D.f i i) x₁, by simp [eq₁]⟩ }, { dsimp only at *, substs e₁ eq₁, exact ⟨y, by simp⟩ } }, { rintro ⟨x, hx⟩, exact ⟨⟨D.f i j x, hx⟩, ⟨D.f j i (D.t _ _ x), by simp [← hx]⟩⟩ } end lemma preimage_range (i j : D.J) : 𝖣 .ι j ⁻¹' (set.range (𝖣 .ι i)) = set.range (D.f j i) := by rw [← set.preimage_image_eq (set.range (D.f j i)) (D.ι_injective j), ← set.image_univ, ← set.image_univ, ←set.image_comp, ←coe_comp, set.image_univ,set.image_univ, ← image_inter, set.preimage_range_inter] lemma preimage_image_eq_image (i j : D.J) (U : set (𝖣 .U i)) : 𝖣 .ι j ⁻¹' (𝖣 .ι i '' U) = D.f _ _ '' ((D.t j i ≫ D.f _ _) ⁻¹' U) := begin have : D.f _ _ ⁻¹' (𝖣 .ι j ⁻¹' (𝖣 .ι i '' U)) = (D.t j i ≫ D.f _ _) ⁻¹' U, { ext x, conv_rhs { rw ← set.preimage_image_eq U (D.ι_injective _) }, generalize : 𝖣 .ι i '' U = U', simp }, rw [← this, set.image_preimage_eq_inter_range], symmetry, apply set.inter_eq_self_of_subset_left, rw ← D.preimage_range i j, exact set.preimage_mono (set.image_subset_range _ _), end lemma preimage_image_eq_image' (i j : D.J) (U : set (𝖣 .U i)) : 𝖣 .ι j ⁻¹' (𝖣 .ι i '' U) = (D.t i j ≫ D.f _ _) '' ((D.f _ _) ⁻¹' U) := begin convert D.preimage_image_eq_image i j U using 1, rw [coe_comp, coe_comp, ← set.image_image], congr' 1, rw [← set.eq_preimage_iff_image_eq, set.preimage_preimage], change _ = (D.t i j ≫ D.t j i ≫ _) ⁻¹' _, rw 𝖣 .t_inv_assoc, rw ← is_iso_iff_bijective, apply (forget Top).map_is_iso end lemma open_image_open (i : D.J) (U : opens (𝖣 .U i)) : is_open (𝖣 .ι i '' U) := begin rw is_open_iff, intro j, rw preimage_image_eq_image, apply (D.f_open _ _).is_open_map, apply (D.t j i ≫ D.f i j).continuous_to_fun.is_open_preimage, exact U.property end lemma ι_open_embedding (i : D.J) : open_embedding (𝖣 .ι i) := open_embedding_of_continuous_injective_open (𝖣 .ι i).continuous_to_fun (D.ι_injective i) (λ U h, D.open_image_open i ⟨U, h⟩) /-- A family of gluing data consists of 1. An index type `J` 2. A bundled topological space `U i` for each `i : J`. 3. An open set `V i j ⊆ U i` for each `i j : J`. 4. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `V i i = U i`. 7. `t i i` is the identity. 8. For each `x ∈ V i j ∩ V i k`, `t i j x ∈ V j k`. 9. `t j k (t i j x) = t i k x`. We can then glue the topological spaces `U i` together by identifying `V i j` with `V j i`. -/ @[nolint has_nonempty_instance] structure mk_core := {J : Type u} (U : J → Top.{u}) (V : Π i, J → opens (U i)) (t : Π i j, (opens.to_Top _).obj (V i j) ⟶ (opens.to_Top _).obj (V j i)) (V_id : ∀ i, V i i = ⊤) (t_id : ∀ i, ⇑(t i i) = id) (t_inter : ∀ ⦃i j⦄ k (x : V i j), ↑x ∈ V i k → @coe (V j i) (U j) _ (t i j x) ∈ V j k) (cocycle : ∀ i j k (x : V i j) (h : ↑x ∈ V i k), @coe (V k j) (U k) _ (t j k ⟨↑(t i j x), t_inter k x h⟩) = @coe (V k i) (U k) _ (t i k ⟨x, h⟩)) lemma mk_core.t_inv (h : mk_core) (i j : h.J) (x : h.V j i) : h.t i j ((h.t j i) x) = x := begin have := h.cocycle j i j x _, rw h.t_id at this, convert subtype.eq this, { ext, refl }, all_goals { rw h.V_id, trivial } end instance (h : mk_core.{u}) (i j : h.J) : is_iso (h.t i j) := by { use h.t j i, split; ext1, exacts [h.t_inv _ _ _, h.t_inv _ _ _] } /-- (Implementation) the restricted transition map to be fed into `glue_data`. -/ def mk_core.t' (h : mk_core.{u}) (i j k : h.J) : pullback (h.V i j).inclusion (h.V i k).inclusion ⟶ pullback (h.V j k).inclusion (h.V j i).inclusion := begin refine (pullback_iso_prod_subtype _ _).hom ≫ ⟨_, _⟩ ≫ (pullback_iso_prod_subtype _ _).inv, { intro x, refine ⟨⟨⟨(h.t i j x.1.1).1, _⟩, h.t i j x.1.1⟩, rfl⟩, rcases x with ⟨⟨⟨x, hx⟩, ⟨x', hx'⟩⟩, (rfl : x = x')⟩, exact h.t_inter _ ⟨x, hx⟩ hx' }, continuity, end /-- This is a constructor of `Top.glue_data` whose arguments are in terms of elements and intersections rather than subobjects and pullbacks. Please refer to `Top.glue_data.mk_core` for details. -/ def mk' (h : mk_core.{u}) : Top.glue_data := { J := h.J, U := h.U, V := λ i, (opens.to_Top _).obj (h.V i.1 i.2), f := λ i j, (h.V i j).inclusion , f_id := λ i, (h.V_id i).symm ▸ is_iso.of_iso (opens.inclusion_top_iso (h.U i)), f_open := λ (i j : h.J), (h.V i j).open_embedding, t := h.t, t_id := λ i, by { ext, rw h.t_id, refl }, t' := h.t', t_fac := λ i j k, begin delta mk_core.t', rw [category.assoc, category.assoc, pullback_iso_prod_subtype_inv_snd, ← iso.eq_inv_comp, pullback_iso_prod_subtype_inv_fst_assoc], ext ⟨⟨⟨x, hx⟩, ⟨x', hx'⟩⟩, (rfl : x = x')⟩, refl, end, cocycle := λ i j k, begin delta mk_core.t', simp_rw ← category.assoc, rw iso.comp_inv_eq, simp only [iso.inv_hom_id_assoc, category.assoc, category.id_comp], rw [← iso.eq_inv_comp, iso.inv_hom_id], ext1 ⟨⟨⟨x, hx⟩, ⟨x', hx'⟩⟩, (rfl : x = x')⟩, simp only [Top.comp_app, continuous_map.coe_mk, prod.mk.inj_iff, Top.id_app, subtype.mk_eq_mk, subtype.coe_mk], rw [← subtype.coe_injective.eq_iff, subtype.val_eq_coe, subtype.coe_mk, and_self], convert congr_arg coe (h.t_inv k i ⟨x, hx'⟩) using 3, ext, exact h.cocycle i j k ⟨x, hx⟩ hx', end } . variables {α : Type u} [topological_space α] {J : Type u} (U : J → opens α) include U /-- We may construct a glue data from a family of open sets. -/ @[simps to_glue_data_J to_glue_data_U to_glue_data_V to_glue_data_t to_glue_data_f] def of_open_subsets : Top.glue_data.{u} := mk'.{u} { J := J, U := λ i, (opens.to_Top $ Top.of α).obj (U i), V := λ i j, (opens.map $ opens.inclusion _).obj (U j), t := λ i j, ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, by continuity⟩, V_id := λ i, by { ext, cases U i, simp }, t_id := λ i, by { ext, refl }, t_inter := λ i j k x hx, hx, cocycle := λ i j k x h, rfl } /-- The canonical map from the glue of a family of open subsets `α` into `α`. This map is an open embedding (`from_open_subsets_glue_open_embedding`), and its range is `⋃ i, (U i : set α)` (`range_from_open_subsets_glue`). -/ def from_open_subsets_glue : (of_open_subsets U).to_glue_data.glued ⟶ Top.of α := multicoequalizer.desc _ _ (λ x, opens.inclusion _) (by { rintro ⟨i, j⟩, ext x, refl }) @[simp, elementwise] lemma ι_from_open_subsets_glue (i : J) : (of_open_subsets U).to_glue_data.ι i ≫ from_open_subsets_glue U = opens.inclusion _ := multicoequalizer.π_desc _ _ _ _ _ lemma from_open_subsets_glue_injective : function.injective (from_open_subsets_glue U) := begin intros x y e, obtain ⟨i, ⟨x, hx⟩, rfl⟩ := (of_open_subsets U).ι_jointly_surjective x, obtain ⟨j, ⟨y, hy⟩, rfl⟩ := (of_open_subsets U).ι_jointly_surjective y, rw [ι_from_open_subsets_glue_apply, ι_from_open_subsets_glue_apply] at e, change x = y at e, subst e, rw (of_open_subsets U).ι_eq_iff_rel, right, exact ⟨⟨⟨x, hx⟩, hy⟩, rfl, rfl⟩, end lemma from_open_subsets_glue_is_open_map : is_open_map (from_open_subsets_glue U) := begin intros s hs, rw (of_open_subsets U).is_open_iff at hs, rw is_open_iff_forall_mem_open, rintros _ ⟨x, hx, rfl⟩, obtain ⟨i, ⟨x, hx'⟩, rfl⟩ := (of_open_subsets U).ι_jointly_surjective x, use from_open_subsets_glue U '' s ∩ set.range (@opens.inclusion (Top.of α) (U i)), use set.inter_subset_left _ _, split, { erw ← set.image_preimage_eq_inter_range, apply (@opens.open_embedding (Top.of α) (U i)).is_open_map, convert hs i using 1, rw [← ι_from_open_subsets_glue, coe_comp, set.preimage_comp], congr' 1, refine set.preimage_image_eq _ (from_open_subsets_glue_injective U) }, { refine ⟨set.mem_image_of_mem _ hx, _⟩, rw ι_from_open_subsets_glue_apply, exact set.mem_range_self _ }, end lemma from_open_subsets_glue_open_embedding : open_embedding (from_open_subsets_glue U) := open_embedding_of_continuous_injective_open (continuous_map.continuous_to_fun _) (from_open_subsets_glue_injective U) (from_open_subsets_glue_is_open_map U) lemma range_from_open_subsets_glue : set.range (from_open_subsets_glue U) = ⋃ i, (U i : set α) := begin ext, split, { rintro ⟨x, rfl⟩, obtain ⟨i, ⟨x, hx'⟩, rfl⟩ := (of_open_subsets U).ι_jointly_surjective x, rw ι_from_open_subsets_glue_apply, exact set.subset_Union _ i hx' }, { rintro ⟨_, ⟨i, rfl⟩, hx⟩, refine ⟨(of_open_subsets U).to_glue_data.ι i ⟨x, hx⟩, ι_from_open_subsets_glue_apply _ _ _⟩ } end /-- The gluing of an open cover is homeomomorphic to the original space. -/ def open_cover_glue_homeo (h : (⋃ i, (U i : set α)) = set.univ) : (of_open_subsets U).to_glue_data.glued ≃ₜ α := homeomorph.homeomorph_of_continuous_open (equiv.of_bijective (from_open_subsets_glue U) ⟨from_open_subsets_glue_injective U, set.range_iff_surjective.mp ((range_from_open_subsets_glue U).symm ▸ h)⟩) (from_open_subsets_glue U).2 (from_open_subsets_glue_is_open_map U) end glue_data end Top
c739967e097babe72483128f7407a640263b27d2
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/fintype/card.lean
7873bffbf09d20e85efea3732c8810e72b4cb6f9
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,040
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Haitao Zhang Cardinality for finite types. -/ import .basic data.list data.finset.card open eq.ops nat function list finset namespace fintype definition card [reducible] (A : Type) [finA : fintype A] := finset.card (@finset.univ A _) lemma card_eq_card_image_of_inj {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {B : Type} [finB : fintype B] [deceqB : decidable_eq B] {f : A → B} : injective f → finset.card (image f univ) = card A := assume Pinj, card_image_eq_of_inj_on (to_set_univ⁻¹ ▸ (iff.mp !set.injective_iff_inj_on_univ Pinj)) -- General version of the pigeonhole principle. See also data.less_than. lemma card_le_of_inj (A : Type) [finA : fintype A] [deceqA : decidable_eq A] (B : Type) [finB : fintype B] [deceqB : decidable_eq B] : (∃ f : A → B, injective f) → card A ≤ card B := assume Pex, obtain f Pinj, from Pex, have Pinj_on_univ : _, from iff.mp !set.injective_iff_inj_on_univ Pinj, have Pinj_ts : set.inj_on f (ts univ), from to_set_univ⁻¹ ▸ Pinj_on_univ, have Psub : (image f univ) ⊆ univ, from !subset_univ, finset.card_le_of_inj_on univ univ (exists.intro f (and.intro Pinj_ts Psub)) -- used to prove that inj ∧ eq card => surj lemma univ_of_card_eq_univ {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {s : finset A} : finset.card s = card A → s = univ := assume Pcardeq, ext (take a, have D : decidable (a ∈ s), from decidable_mem a s, begin apply iff.intro, intro ain, apply mem_univ, intro ain, cases D with Pin Pnin, exact Pin, have Pplus1 : finset.card (insert a s) = finset.card s + 1, from card_insert_of_not_mem Pnin, rewrite Pcardeq at Pplus1, have Ple : finset.card (insert a s) ≤ card A, begin apply card_le_card_of_subset, apply subset_univ end, rewrite Pplus1 at Ple, exact false.elim (not_succ_le_self Ple) end) end fintype
e5f3125628a12d2bea5fde0cf93894cadf55ecc2
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finset/pointwise.lean
5ad07d6a985ab45c0a13806f4e13d566855032e2
[ "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
31,560
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yaël Dillies -/ import data.finset.n_ary import data.finset.preimage import data.set.pointwise /-! # Pointwise operations of finsets This file defines pointwise algebraic operations on finsets. ## Main declarations For finsets `s` and `t`: * `0` (`finset.has_zero`): The singleton `{0}`. * `1` (`finset.has_one`): The singleton `{1}`. * `-s` (`finset.has_neg`): Negation, finset of all `-x` where `x ∈ s`. * `s⁻¹` (`finset.has_inv`): Inversion, finset of all `x⁻¹` where `x ∈ s`. * `s + t` (`finset.has_add`): Addition, finset of all `x + y` where `x ∈ s` and `y ∈ t`. * `s * t` (`finset.has_mul`): Multiplication, finset of all `x * y` where `x ∈ s` and `y ∈ t`. * `s - t` (`finset.has_sub`): Subtraction, finset of all `x - y` where `x ∈ s` and `y ∈ t`. * `s / t` (`finset.has_div`): Division, finset of all `x / y` where `x ∈ s` and `y ∈ t`. * `s +ᵥ t` (`finset.has_vadd`): Scalar addition, finset of all `x +ᵥ y` where `x ∈ s` and `y ∈ t`. * `s • t` (`finset.has_scalar`): Scalar multiplication, finset of all `x • y` where `x ∈ s` and `y ∈ t`. * `s -ᵥ t` (`finset.has_vsub`): Scalar subtraction, finset of all `x -ᵥ y` where `x ∈ s` and `y ∈ t`. * `a • s` (`finset.has_scalar_finset`): Scaling, finset of all `a • x` where `x ∈ s`. * `a +ᵥ s` (`finset.has_vadd_finset`): Translation, finset of all `a +ᵥ x` where `x ∈ s`. For `α` a semigroup/monoid, `finset α` is a semigroup/monoid. As an unfortunate side effect, this means that `n • s`, where `n : ℕ`, is ambiguous between pointwise scaling and repeated pointwise addition; the former has `(2 : ℕ) • {1, 2} = {2, 4}`, while the latter has `(2 : ℕ) • {1, 2} = {2, 3, 4}`. ## Implementation notes We put all instances in the locale `pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. ## Tags finset multiplication, finset addition, pointwise addition, pointwise multiplication, pointwise subtraction -/ open function open_locale pointwise variables {F α β γ : Type*} namespace finset /-! ### `0`/`1` as sets -/ section has_one variables [has_one α] {s : finset α} {a : α} /-- The finset `1 : finset α` is defined as `{1}` in locale `pointwise`. -/ @[to_additive "The finset `0 : finset α` is defined as `{0}` in locale `pointwise`."] protected def has_one : has_one (finset α) := ⟨{1}⟩ localized "attribute [instance] finset.has_one finset.has_zero" in pointwise @[simp, to_additive] lemma mem_one : a ∈ (1 : finset α) ↔ a = 1 := mem_singleton @[simp, to_additive] lemma coe_one : ↑(1 : finset α) = (1 : set α) := coe_singleton 1 @[simp, to_additive] lemma one_subset : (1 : finset α) ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff @[to_additive] lemma singleton_one : ({1} : finset α) = 1 := rfl @[to_additive] lemma one_mem_one : (1 : α) ∈ (1 : finset α) := mem_singleton_self _ @[to_additive] lemma one_nonempty : (1 : finset α).nonempty := ⟨1, one_mem_one⟩ @[simp, to_additive] protected lemma map_one {f : α ↪ β} : map f 1 = {f 1} := map_singleton f 1 @[simp, to_additive] lemma image_one [decidable_eq β] {f : α → β} : image f 1 = {f 1} := image_singleton f 1 end has_one /-! ### Finset negation/inversion -/ section has_inv variables [decidable_eq α] [has_inv α] {s s₁ s₂ t t₁ t₂ u : finset α} {a b : α} /-- The pointwise inversion of finset `s⁻¹` is defined as `{x⁻¹ | x ∈ s}` in locale `pointwise`. -/ @[to_additive "The pointwise negation of finset `-s` is defined as `{-x | x ∈ s}` in locale `pointwise`."] protected def has_inv : has_inv (finset α) := ⟨image has_inv.inv⟩ localized "attribute [instance] finset.has_inv finset.has_neg" in pointwise @[to_additive] lemma inv_def : s⁻¹ = s.image (λ x, x⁻¹) := rfl @[to_additive] lemma image_inv : s.image (λ x, x⁻¹) = s⁻¹ := rfl @[to_additive] lemma mem_inv {x : α} : x ∈ s⁻¹ ↔ ∃ y ∈ s, y⁻¹ = x := mem_image @[to_additive] lemma inv_mem_inv (ha : a ∈ s) : a⁻¹ ∈ s⁻¹ := mem_image_of_mem _ ha @[to_additive] lemma card_inv_le : s⁻¹.card ≤ s.card := card_image_le @[simp, to_additive] lemma inv_empty : (∅ : finset α)⁻¹ = ∅ := image_empty _ @[simp, to_additive] lemma inv_nonempty_iff : s⁻¹.nonempty ↔ s.nonempty := nonempty.image_iff _ alias inv_nonempty_iff ↔ finset.nonempty.inv finset.nonempty.of_inv @[to_additive, mono] lemma inv_subset_inv (h : s ⊆ t) : s⁻¹ ⊆ t⁻¹ := image_subset_image h attribute [mono] neg_subset_neg @[simp, to_additive] lemma inv_singleton (a : α) : ({a} : finset α)⁻¹ = {a⁻¹} := image_singleton _ _ end has_inv open_locale pointwise section has_involutive_inv variables [decidable_eq α] [has_involutive_inv α] {s t : finset α} @[simp, norm_cast, to_additive] lemma coe_inv (s : finset α) : ↑(s⁻¹) = (s : set α)⁻¹ := coe_image.trans set.image_inv @[simp, to_additive] lemma card_inv : s⁻¹.card = s.card := card_image_of_injective _ inv_injective @[simp, to_additive] lemma preimage_inv : s.preimage has_inv.inv (inv_injective.inj_on _) = s⁻¹ := coe_injective $ by rw [coe_preimage, set.inv_preimage, coe_inv] end has_involutive_inv /-! ### Finset addition/multiplication -/ section has_mul variables [decidable_eq α] [has_mul α] {s s₁ s₂ t t₁ t₂ u : finset α} {a b : α} /-- The pointwise multiplication of finsets `s * t` and `t` is defined as `{x * y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive "The pointwise addition of finsets `s + t` is defined as `{x + y | x ∈ s, y ∈ t}` in locale `pointwise`."] protected def has_mul : has_mul (finset α) := ⟨image₂ (*)⟩ localized "attribute [instance] finset.has_mul finset.has_add" in pointwise @[to_additive] lemma mul_def : s * t = (s.product t).image (λ p : α × α, p.1 * p.2) := rfl @[to_additive add_image_prod] lemma image_mul_prod : (s.product t).image (λ x : α × α, x.fst * x.snd) = s * t := rfl @[to_additive] lemma mem_mul {x : α} : x ∈ s * t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y * z = x := mem_image₂ @[simp, norm_cast, to_additive] lemma coe_mul (s t : finset α) : (↑(s * t) : set α) = ↑s * ↑t := coe_image₂ _ _ _ @[to_additive] lemma mul_mem_mul : a ∈ s → b ∈ t → a * b ∈ s * t := mem_image₂_of_mem @[to_additive] lemma mul_card_le : (s * t).card ≤ s.card * t.card := card_image₂_le _ _ _ @[simp, to_additive] lemma empty_mul (s : finset α) : ∅ * s = ∅ := image₂_empty_left @[simp, to_additive] lemma mul_empty (s : finset α) : s * ∅ = ∅ := image₂_empty_right @[simp, to_additive] lemma mul_eq_empty : s * t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp, to_additive] lemma mul_nonempty : (s * t).nonempty ↔ s.nonempty ∧ t.nonempty := image₂_nonempty_iff @[to_additive] lemma nonempty.mul : s.nonempty → t.nonempty → (s * t).nonempty := nonempty.image₂ @[to_additive] lemma nonempty.of_mul_left : (s * t).nonempty → s.nonempty := nonempty.of_image₂_left @[to_additive] lemma nonempty.of_mul_right : (s * t).nonempty → t.nonempty := nonempty.of_image₂_right @[simp, to_additive] lemma mul_singleton (a : α) : s * {a} = s.image (* a) := image₂_singleton_right @[simp, to_additive] lemma singleton_mul (a : α) : {a} * s = s.image ((*) a) := image₂_singleton_left @[simp, to_additive] lemma singleton_mul_singleton (a b : α) : ({a} : finset α) * {b} = {a * b} := image₂_singleton @[to_additive, mono] lemma mul_subset_mul : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ * t₁ ⊆ s₂ * t₂ := image₂_subset @[to_additive] lemma mul_subset_mul_left : t₁ ⊆ t₂ → s * t₁ ⊆ s * t₂ := image₂_subset_left @[to_additive] lemma mul_subset_mul_right : s₁ ⊆ s₂ → s₁ * t ⊆ s₂ * t := image₂_subset_right @[to_additive] lemma mul_subset_iff : s * t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), x * y ∈ u := image₂_subset_iff attribute [mono] add_subset_add @[to_additive] lemma union_mul : (s₁ ∪ s₂) * t = s₁ * t ∪ s₂ * t := image₂_union_left @[to_additive] lemma mul_union : s * (t₁ ∪ t₂) = s * t₁ ∪ s * t₂ := image₂_union_right @[to_additive] lemma inter_mul_subset : (s₁ ∩ s₂) * t ⊆ s₁ * t ∩ (s₂ * t) := image₂_inter_subset_left @[to_additive] lemma mul_inter_subset : s * (t₁ ∩ t₂) ⊆ s * t₁ ∩ (s * t₂) := image₂_inter_subset_right /-- If a finset `u` is contained in the product of two sets `s * t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' * t'`. -/ @[to_additive "If a finset `u` is contained in the sum of two sets `s + t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' + t'`."] lemma subset_mul {s t : set α} : ↑u ⊆ s * t → ∃ s' t' : finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' * t' := subset_image₂ end has_mul /-! ### Finset subtraction/division -/ section has_div variables [decidable_eq α] [has_div α] {s s₁ s₂ t t₁ t₂ u : finset α} {a b : α} /-- The pointwise division of sfinets `s / t` is defined as `{x / y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive "The pointwise subtraction of finsets `s - t` is defined as `{x - y | x ∈ s, y ∈ t}` in locale `pointwise`."] protected def has_div : has_div (finset α) := ⟨image₂ (/)⟩ localized "attribute [instance] finset.has_div finset.has_add" in pointwise @[to_additive] lemma div_def : s / t = (s.product t).image (λ p : α × α, p.1 / p.2) := rfl @[to_additive add_image_prod] lemma image_div_prod : (s.product t).image (λ x : α × α, x.fst / x.snd) = s / t := rfl @[to_additive] lemma mem_div : a ∈ s / t ↔ ∃ b c, b ∈ s ∧ c ∈ t ∧ b / c = a := mem_image₂ @[simp, norm_cast, to_additive] lemma coe_div (s t : finset α) : (↑(s / t) : set α) = ↑s / ↑t := coe_image₂ _ _ _ @[to_additive] lemma div_mem_div : a ∈ s → b ∈ t → a / b ∈ s / t := mem_image₂_of_mem @[to_additive] lemma div_card_le : (s / t).card ≤ s.card * t.card := card_image₂_le _ _ _ @[simp, to_additive] lemma empty_div (s : finset α) : ∅ / s = ∅ := image₂_empty_left @[simp, to_additive] lemma div_empty (s : finset α) : s / ∅ = ∅ := image₂_empty_right @[simp, to_additive] lemma div_eq_empty : s / t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp, to_additive] lemma div_nonempty : (s / t).nonempty ↔ s.nonempty ∧ t.nonempty := image₂_nonempty_iff @[to_additive] lemma nonempty.div : s.nonempty → t.nonempty → (s / t).nonempty := nonempty.image₂ @[to_additive] lemma nonempty.of_div_left : (s / t).nonempty → s.nonempty := nonempty.of_image₂_left @[to_additive] lemma nonempty.of_div_right : (s / t).nonempty → t.nonempty := nonempty.of_image₂_right @[simp, to_additive] lemma div_singleton (a : α) : s / {a} = s.image (/ a) := image₂_singleton_right @[simp, to_additive] lemma singleton_div (a : α) : {a} / s = s.image ((/) a) := image₂_singleton_left @[simp, to_additive] lemma singleton_div_singleton (a b : α) : ({a} : finset α) / {b} = {a / b} := image₂_singleton @[to_additive, mono] lemma div_subset_div : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ / t₁ ⊆ s₂ / t₂ := image₂_subset @[to_additive] lemma div_subset_div_left : t₁ ⊆ t₂ → s / t₁ ⊆ s / t₂ := image₂_subset_left @[to_additive] lemma div_subset_div_right : s₁ ⊆ s₂ → s₁ / t ⊆ s₂ / t := image₂_subset_right @[to_additive] lemma div_subset_iff : s / t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), x / y ∈ u := image₂_subset_iff attribute [mono] sub_subset_sub @[to_additive] lemma union_div : (s₁ ∪ s₂) / t = s₁ / t ∪ s₂ / t := image₂_union_left @[to_additive] lemma div_union : s / (t₁ ∪ t₂) = s / t₁ ∪ s / t₂ := image₂_union_right @[to_additive] lemma inter_div_subset : (s₁ ∩ s₂) / t ⊆ s₁ / t ∩ (s₂ / t) := image₂_inter_subset_left @[to_additive] lemma div_inter_subset : s / (t₁ ∩ t₂) ⊆ s / t₁ ∩ (s / t₂) := image₂_inter_subset_right /-- If a finset `u` is contained in the product of two sets `s / t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' / t'`. -/ @[to_additive "If a finset `u` is contained in the sum of two sets `s - t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' - t'`."] lemma subset_div {s t : set α} : ↑u ⊆ s / t → ∃ s' t' : finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' / t' := subset_image₂ end has_div /-! ### Instances -/ open_locale pointwise section instances variables [decidable_eq α] /-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `finset`. -/ protected def has_nsmul [has_zero α] [has_add α] : has_scalar ℕ (finset α) := ⟨nsmul_rec⟩ /-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a `finset`. -/ @[to_additive] protected def has_npow [has_one α] [has_mul α] : has_pow (finset α) ℕ := ⟨λ s n, npow_rec n s⟩ /-- Repeated pointwise addition/subtraction (not the same as pointwise repeated addition/subtraction!) of a `finset`. -/ protected def has_zsmul [has_zero α] [has_add α] [has_neg α] : has_scalar ℤ (finset α) := ⟨zsmul_rec⟩ /-- Repeated pointwise multiplication/division (not the same as pointwise repeated multiplication/division!) of a `finset`. -/ @[to_additive] protected def has_zpow [has_one α] [has_mul α] [has_inv α] : has_pow (finset α) ℤ := ⟨λ s n, zpow_rec n s⟩ localized "attribute [instance] finset.has_nsmul finset.has_npow finset.has_zsmul finset.has_zpow" in pointwise /-- `finset α` is a `semigroup` under pointwise operations if `α` is. -/ @[to_additive "`finset α` is an `add_semigroup` under pointwise operations if `α` is. "] protected def semigroup [semigroup α] : semigroup (finset α) := coe_injective.semigroup _ coe_mul /-- `finset α` is a `comm_semigroup` under pointwise operations if `α` is. -/ @[to_additive "`finset α` is an `add_comm_semigroup` under pointwise operations if `α` is. "] protected def comm_semigroup [comm_semigroup α] : comm_semigroup (finset α) := coe_injective.comm_semigroup _ coe_mul section mul_one_class variables [mul_one_class α] /-- `finset α` is a `mul_one_class` under pointwise operations if `α` is. -/ @[to_additive "`finset α` is an `add_zero_class` under pointwise operations if `α` is."] protected def mul_one_class : mul_one_class (finset α) := coe_injective.mul_one_class _ (coe_singleton 1) coe_mul localized "attribute [instance] finset.semigroup finset.add_semigroup finset.comm_semigroup finset.add_comm_semigroup finset.mul_one_class finset.add_zero_class" in pointwise end mul_one_class section monoid variables [monoid α] {s t : finset α} {a : α} @[simp, to_additive] lemma coe_pow (s : finset α) (n : ℕ) : ↑(s ^ n) = (s ^ n : set α) := begin change ↑(npow_rec n s) = _, induction n with n ih, { rw [npow_rec, pow_zero, coe_one] }, { rw [npow_rec, pow_succ, coe_mul, ih] } end /-- `finset α` is a `monoid` under pointwise operations if `α` is. -/ @[to_additive "`finset α` is an `add_monoid` under pointwise operations if `α` is. "] protected def monoid : monoid (finset α) := coe_injective.monoid _ coe_one coe_mul coe_pow localized "attribute [instance] finset.monoid finset.add_monoid" in pointwise end monoid /-- `finset α` is a `comm_monoid` under pointwise operations if `α` is. -/ @[to_additive "`finset α` is an `add_comm_monoid` under pointwise operations if `α` is. "] protected def comm_monoid [comm_monoid α] : comm_monoid (finset α) := coe_injective.comm_monoid _ coe_one coe_mul coe_pow -- TODO: Generalize the duplicated lemmas and instances below to `division_monoid` @[simp, to_additive] lemma coe_zpow [group α] (s : finset α) : ∀ n : ℤ, ↑(s ^ n) = (s ^ n : set α) | (int.of_nat n) := coe_pow _ _ | (int.neg_succ_of_nat n) := by { refine (coe_inv _).trans _, convert congr_arg has_inv.inv (coe_pow _ _) } @[simp] lemma coe_zpow' [group_with_zero α] (s : finset α) : ∀ n : ℤ, ↑(s ^ n) = (s ^ n : set α) | (int.of_nat n) := coe_pow _ _ | (int.neg_succ_of_nat n) := by { refine (coe_inv _).trans _, convert congr_arg has_inv.inv (coe_pow _ _) } /-- `finset α` is a `div_inv_monoid` under pointwise operations if `α` is. -/ @[to_additive "`finset α` is an `sub_neg_add_monoid` under pointwise operations if `α` is."] protected def div_inv_monoid [group α] : div_inv_monoid (finset α) := coe_injective.div_inv_monoid _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow /-- `finset α` is a `div_inv_monoid` under pointwise operations if `α` is. -/ protected def div_inv_monoid' [group_with_zero α] : div_inv_monoid (finset α) := coe_injective.div_inv_monoid _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow' localized "attribute [instance] finset.comm_monoid finset.add_comm_monoid finset.div_inv_monoid finset.sub_neg_add_monoid finset.div_inv_monoid'" in pointwise end instances section mul_zero_class variables [decidable_eq α] [mul_zero_class α] {s t : finset α} /-! Note that `set` is not a `mul_zero_class` because `0 * ∅ ≠ 0`. -/ lemma mul_zero_subset (s : finset α) : s * 0 ⊆ 0 := by simp [subset_iff, mem_mul] lemma zero_mul_subset (s : finset α) : 0 * s ⊆ 0 := by simp [subset_iff, mem_mul] lemma nonempty.mul_zero (hs : s.nonempty) : s * 0 = 0 := s.mul_zero_subset.antisymm $ by simpa [mem_mul] using hs lemma nonempty.zero_mul (hs : s.nonempty) : 0 * s = 0 := s.zero_mul_subset.antisymm $ by simpa [mem_mul] using hs end mul_zero_class section group variables [group α] {s t : finset α} {a b : α} /-! Note that `finset` is not a `group` because `s / s ≠ 1` in general. -/ section decidable_eq variables [decidable_eq α] @[simp, to_additive] lemma image_mul_left : image (λ b, a * b) t = preimage t (λ b, a⁻¹ * b) ((mul_right_injective _).inj_on _) := coe_injective $ by simp @[simp, to_additive] lemma image_mul_right : image (* b) t = preimage t (* b⁻¹) ((mul_left_injective _).inj_on _) := coe_injective $ by simp @[to_additive] lemma image_mul_left' : image (λ b, a⁻¹ * b) t = preimage t (λ b, a * b) ((mul_right_injective _).inj_on _) := by simp @[to_additive] lemma image_mul_right' : image (* b⁻¹) t = preimage t (* b) ((mul_left_injective _).inj_on _) := by simp end decidable_eq @[simp, to_additive] lemma preimage_mul_left_singleton : preimage {b} ((*) a) ((mul_right_injective _).inj_on _) = {a⁻¹ * b} := by { classical, rw [← image_mul_left', image_singleton] } @[simp, to_additive] lemma preimage_mul_right_singleton : preimage {b} (* a) ((mul_left_injective _).inj_on _) = {b * a⁻¹} := by { classical, rw [← image_mul_right', image_singleton] } @[simp, to_additive] lemma preimage_mul_left_one : preimage 1 ((*) a) ((mul_right_injective _).inj_on _) = {a⁻¹} := by { classical, rw [← image_mul_left', image_one, mul_one] } @[simp, to_additive] lemma preimage_mul_right_one : preimage 1 (* b) ((mul_left_injective _).inj_on _) = {b⁻¹} := by { classical, rw [← image_mul_right', image_one, one_mul] } @[to_additive] lemma preimage_mul_left_one' : preimage 1 ((*) a⁻¹) ((mul_right_injective _).inj_on _) = {a} := by rw [preimage_mul_left_one, inv_inv] @[to_additive] lemma preimage_mul_right_one' : preimage 1 (* b⁻¹) ((mul_left_injective _).inj_on _) = {b} := by rw [preimage_mul_right_one, inv_inv] end group section group_with_zero variables [decidable_eq α] [group_with_zero α] {s t : finset α} lemma div_zero_subset (s : finset α) : s / 0 ⊆ 0 := by simp [subset_iff, mem_div] lemma zero_div_subset (s : finset α) : 0 / s ⊆ 0 := by simp [subset_iff, mem_div] lemma nonempty.div_zero (hs : s.nonempty) : s / 0 = 0 := s.div_zero_subset.antisymm $ by simpa [mem_div] using hs lemma nonempty.zero_div (hs : s.nonempty) : 0 / s = 0 := s.zero_div_subset.antisymm $ by simpa [mem_div] using hs end group_with_zero /-! ### Scalar addition/multiplication of finsets -/ section has_scalar variables [decidable_eq β] [has_scalar α β] {s s₁ s₂ : finset α} {t t₁ t₂ u : finset β} {a : α} {b : β} /-- The pointwise product of two finsets `s` and `t`: `s • t = {x • y | x ∈ s, y ∈ t}`. -/ @[to_additive has_vadd "The pointwise sum of two finsets `s` and `t`: `s +ᵥ t = {x +ᵥ y | x ∈ s, y ∈ t}`."] protected def has_scalar : has_scalar (finset α) (finset β) := ⟨image₂ (•)⟩ localized "attribute [instance] finset.has_scalar finset.has_vadd" in pointwise @[to_additive] lemma smul_def : s • t = (s.product t).image (λ p : α × β, p.1 • p.2) := rfl @[to_additive] lemma image_smul_product : (s.product t).image (λ x : α × β, x.fst • x.snd) = s • t := rfl @[to_additive] lemma mem_smul {x : β} : x ∈ s • t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y • z = x := mem_image₂ @[simp, norm_cast, to_additive] lemma coe_smul (s : finset α) (t : finset β) : (↑(s • t) : set β) = (s : set α) • t := coe_image₂ _ _ _ @[to_additive] lemma smul_mem_smul : a ∈ s → b ∈ t → a • b ∈ s • t := mem_image₂_of_mem @[to_additive] lemma smul_card_le : (s • t).card ≤ s.card • t.card := card_image₂_le _ _ _ @[simp, to_additive] lemma empty_smul (t : finset β) : (∅ : finset α) • t = ∅ := image₂_empty_left @[simp, to_additive] lemma smul_empty (s : finset α) : s • (∅ : finset β) = ∅ := image₂_empty_right @[simp, to_additive] lemma smul_eq_empty : s • t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp, to_additive] lemma smul_nonempty_iff : (s • t).nonempty ↔ s.nonempty ∧ t.nonempty := image₂_nonempty_iff @[to_additive] lemma nonempty.smul : s.nonempty → t.nonempty → (s • t).nonempty := nonempty.image₂ @[to_additive] lemma nonempty.of_smul_left : (s • t).nonempty → s.nonempty := nonempty.of_image₂_left @[to_additive] lemma nonempty.of_smul_right : (s • t).nonempty → t.nonempty := nonempty.of_image₂_right @[simp, to_additive] lemma smul_singleton (b : β) : s • ({b} : finset β) = s.image (• b) := image₂_singleton_right @[simp, to_additive] lemma singleton_smul (a : α) : ({a} : finset α) • t = t.image ((•) a) := image₂_singleton_left @[simp, to_additive] lemma singleton_smul_singleton (a : α) (b : β) : ({a} : finset α) • ({b} : finset β) = {a • b} := image₂_singleton @[to_additive, mono] lemma smul_subset_smul : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ • t₁ ⊆ s₂ • t₂ := image₂_subset @[to_additive] lemma smul_subset_smul_left : t₁ ⊆ t₂ → s • t₁ ⊆ s • t₂ := image₂_subset_left @[to_additive] lemma smul_subset_smul_right : s₁ ⊆ s₂ → s₁ • t ⊆ s₂ • t := image₂_subset_right @[to_additive] lemma smul_subset_iff : s • t ⊆ u ↔ ∀ (a ∈ s) (b ∈ t), a • b ∈ u := image₂_subset_iff attribute [mono] vadd_subset_vadd @[to_additive] lemma union_smul [decidable_eq α] : (s₁ ∪ s₂) • t = s₁ • t ∪ s₂ • t := image₂_union_left @[to_additive] lemma smul_union : s • (t₁ ∪ t₂) = s • t₁ ∪ s • t₂ := image₂_union_right @[to_additive] lemma inter_smul_subset [decidable_eq α] : (s₁ ∩ s₂) • t ⊆ s₁ • t ∩ s₂ • t := image₂_inter_subset_left @[to_additive] lemma smul_inter_subset : s • (t₁ ∩ t₂) ⊆ s • t₁ ∩ s • t₂ := image₂_inter_subset_right /-- If a finset `u` is contained in the scalar product of two sets `s • t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' • t'`. -/ @[to_additive "If a finset `u` is contained in the scalar sum of two sets `s +ᵥ t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' +ᵥ t'`."] lemma subset_smul {s : set α} {t : set β} : ↑u ⊆ s • t → ∃ (s' : finset α) (t' : finset β), ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' • t' := subset_image₂ end has_scalar /-! ### Finset addition/multiplication -/ section has_vsub variables [decidable_eq α] [has_vsub α β] {s s₁ s₂ t t₁ t₂ : finset β} {u : finset α} {a : α} {b c : β} include α /-- The pointwise product of two finsets `s` and `t`: `s -ᵥ t = {x -ᵥ y | x ∈ s, y ∈ t}`. -/ protected def has_vsub : has_vsub (finset α) (finset β) := ⟨image₂ (-ᵥ)⟩ localized "attribute [instance] finset.has_vsub" in pointwise lemma vsub_def : s -ᵥ t = image₂ (-ᵥ) s t := rfl @[simp] lemma image_vsub_product : image₂ (-ᵥ) s t = s -ᵥ t := rfl lemma mem_vsub : a ∈ s -ᵥ t ↔ ∃ b c, b ∈ s ∧ c ∈ t ∧ b -ᵥ c = a := mem_image₂ @[simp, norm_cast] lemma coe_vsub (s t : finset β) : (↑(s -ᵥ t) : set α) = (s : set β) -ᵥ t := coe_image₂ _ _ _ lemma vsub_mem_vsub : b ∈ s → c ∈ t → b -ᵥ c ∈ s -ᵥ t := mem_image₂_of_mem lemma vsub_card_le : (s -ᵥ t : finset α).card ≤ s.card * t.card := card_image₂_le _ _ _ @[simp] lemma empty_vsub (t : finset β) : (∅ : finset β) -ᵥ t = ∅ := image₂_empty_left @[simp] lemma vsub_empty (s : finset β) : s -ᵥ (∅ : finset β) = ∅ := image₂_empty_right @[simp] lemma vsub_eq_empty : s -ᵥ t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff @[simp] lemma vsub_nonempty : (s -ᵥ t : finset α).nonempty ↔ s.nonempty ∧ t.nonempty := image₂_nonempty_iff lemma nonempty.vsub : s.nonempty → t.nonempty → (s -ᵥ t : finset α).nonempty := nonempty.image₂ lemma nonempty.of_vsub_left : (s -ᵥ t : finset α).nonempty → s.nonempty := nonempty.of_image₂_left lemma nonempty.of_vsub_right : (s -ᵥ t : finset α).nonempty → t.nonempty := nonempty.of_image₂_right @[simp] lemma vsub_singleton (b : β) : s -ᵥ ({b} : finset β) = s.image (-ᵥ b) := image₂_singleton_right @[simp] lemma singleton_vsub (a : β) : ({a} : finset β) -ᵥ t = t.image ((-ᵥ) a) := image₂_singleton_left @[simp] lemma singleton_vsub_singleton (a b : β) : ({a} : finset β) -ᵥ {b} = {a -ᵥ b} := image₂_singleton @[mono] lemma vsub_subset_vsub : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ -ᵥ t₁ ⊆ s₂ -ᵥ t₂ := image₂_subset lemma vsub_subset_vsub_left : t₁ ⊆ t₂ → s -ᵥ t₁ ⊆ s -ᵥ t₂ := image₂_subset_left lemma vsub_subset_vsub_right : s₁ ⊆ s₂ → s₁ -ᵥ t ⊆ s₂ -ᵥ t := image₂_subset_right lemma vsub_subset_iff : s -ᵥ t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), x -ᵥ y ∈ u := image₂_subset_iff section variables [decidable_eq β] lemma union_vsub : (s₁ ∪ s₂) -ᵥ t = (s₁ -ᵥ t) ∪ (s₂ -ᵥ t) := image₂_union_left lemma vsub_union : s -ᵥ (t₁ ∪ t₂) = (s -ᵥ t₁) ∪ (s -ᵥ t₂) := image₂_union_right lemma inter_vsub_subset : (s₁ ∩ s₂) -ᵥ t ⊆ (s₁ -ᵥ t) ∩ (s₂ -ᵥ t) := image₂_inter_subset_left lemma vsub_inter_subset : s -ᵥ (t₁ ∩ t₂) ⊆ (s -ᵥ t₁) ∩ (s -ᵥ t₂) := image₂_inter_subset_right end /-- If a finset `u` is contained in the pointwise subtraction of two sets `s -ᵥ t`, we can find two finsets `s'`, `t'` such that `s' ⊆ s`, `t' ⊆ t` and `u ⊆ s' -ᵥ t'`. -/ lemma subset_vsub {s t : set β} : ↑u ⊆ s -ᵥ t → ∃ s' t' : finset β, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' -ᵥ t' := subset_image₂ end has_vsub /-! ### Translation/scaling of finsets -/ section has_scalar variables [decidable_eq β] [has_scalar α β] {s s₁ s₂ t u : finset β} {a : α} {b : β} /-- The scaling of a finset `s` by a scalar `a`: `a • s = {a • x | x ∈ s}`. -/ @[to_additive has_vadd_finset "The translation of a finset `s` by a vector `a`: `a +ᵥ s = {a +ᵥ x | x ∈ s}`."] protected def has_scalar_finset : has_scalar α (finset β) := ⟨λ a, image $ (•) a⟩ localized "attribute [instance] finset.has_scalar_finset finset.has_vadd_finset" in pointwise @[to_additive] lemma smul_finset_def : a • s = s.image ((•) a) := rfl @[to_additive] lemma image_smul : s.image (λ x, a • x) = a • s := rfl @[to_additive] lemma mem_smul_finset {x : β} : x ∈ a • s ↔ ∃ y, y ∈ s ∧ a • y = x := by simp only [finset.smul_finset_def, and.assoc, mem_image, exists_prop, prod.exists, mem_product] @[simp, norm_cast, to_additive] lemma coe_smul_finset (s : finset β) : (↑(a • s) : set β) = a • s := coe_image @[to_additive] lemma smul_finset_mem_smul_finset : b ∈ s → a • b ∈ a • s := mem_image_of_mem _ @[to_additive] lemma smul_finset_card_le : (a • s).card ≤ s.card := card_image_le @[simp, to_additive] lemma smul_finset_empty (a : α) : a • (∅ : finset β) = ∅ := image_empty _ @[simp, to_additive] lemma smul_finset_eq_empty : a • s = ∅ ↔ s = ∅ := image_eq_empty @[simp, to_additive] lemma smul_finset_nonempty : (a • s).nonempty ↔ s.nonempty := nonempty.image_iff _ @[to_additive] lemma nonempty.smul_finset (hs : s.nonempty) : (a • s).nonempty := hs.image _ @[to_additive, mono] lemma smul_finset_subset_smul_finset : s ⊆ t → a • s ⊆ a • t := image_subset_image attribute [mono] add_subset_add @[simp, to_additive] lemma smul_finset_singleton (b : β) : a • ({b} : finset β) = {a • b} := image_singleton _ _ @[to_additive] lemma smul_finset_union : a • (s₁ ∪ s₂) = a • s₁ ∪ a • s₂ := image_union _ _ @[to_additive] lemma smul_finset_inter_subset : a • (s₁ ∩ s₂) ⊆ a • s₁ ∩ (a • s₂) := image_inter_subset _ _ _ end has_scalar open_locale pointwise section instances variables [decidable_eq γ] @[to_additive] instance smul_comm_class_set [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class α (finset β) (finset γ) := ⟨λ a s t, coe_injective $ by simp only [coe_smul_finset, coe_smul, smul_comm]⟩ @[to_additive] instance smul_comm_class_set' [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class (finset α) β (finset γ) := by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _ @[to_additive] instance smul_comm_class [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class (finset α) (finset β) (finset γ) := ⟨λ s t u, coe_injective $ by simp_rw [coe_smul, smul_comm]⟩ instance is_scalar_tower [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower α β (finset γ) := ⟨λ a b s, by simp only [←image_smul, image_image, smul_assoc]⟩ variables [decidable_eq β] instance is_scalar_tower' [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower α (finset β) (finset γ) := ⟨λ a s t, coe_injective $ by simp only [coe_smul_finset, coe_smul, smul_assoc]⟩ instance is_scalar_tower'' [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower (finset α) (finset β) (finset γ) := ⟨λ a s t, coe_injective $ by simp only [coe_smul_finset, coe_smul, smul_assoc]⟩ instance is_central_scalar [has_scalar α β] [has_scalar αᵐᵒᵖ β] [is_central_scalar α β] : is_central_scalar α (finset β) := ⟨λ a s, coe_injective $ by simp only [coe_smul_finset, coe_smul, op_smul_eq_smul]⟩ end instances end finset
a6aabda673726ff727f94b8b2b2cfd5f1f749734
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/algebra/ring.lean
f4e80e3c61bcae649c4d72bdca404be088de3035
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
8,340
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u class distrib (α : Type u) extends has_mul α, has_add α := (left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c)) variable {α : Type u} lemma left_distrib [distrib α] (a b c : α) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c def mul_add := @left_distrib lemma right_distrib [distrib α] (a b c : α) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c def add_mul := @right_distrib class mul_zero_class (α : Type u) extends has_mul α, has_zero α := (zero_mul : ∀ a : α, 0 * a = 0) (mul_zero : ∀ a : α, a * 0 = 0) @[simp] lemma zero_mul [mul_zero_class α] (a : α) : 0 * a = 0 := mul_zero_class.zero_mul a @[simp] lemma mul_zero [mul_zero_class α] (a : α) : a * 0 = 0 := mul_zero_class.mul_zero a class zero_ne_one_class (α : Type u) extends has_zero α, has_one α := (zero_ne_one : 0 ≠ (1:α)) @[simp] lemma zero_ne_one [s: zero_ne_one_class α] : 0 ≠ (1:α) := @zero_ne_one_class.zero_ne_one α s @[simp] lemma one_ne_zero [s: zero_ne_one_class α] : (1:α) ≠ 0 := take h, @zero_ne_one_class.zero_ne_one α s h.symm /- semiring -/ class semiring (α : Type u) extends add_comm_monoid α, monoid α, distrib α, mul_zero_class α section semiring variables [semiring α] lemma one_add_one_eq_two : 1 + 1 = (2 : α) := begin unfold bit0, reflexivity end theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma ne_zero_of_mul_ne_zero_right {a b : α} (h : a * b ≠ 0) : a ≠ 0 := suppose a = 0, have a * b = 0, by rw [this, zero_mul], h this lemma ne_zero_of_mul_ne_zero_left {a b : α} (h : a * b ≠ 0) : b ≠ 0 := suppose b = 0, have a * b = 0, by rw [this, mul_zero], h this lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] end semiring class comm_semiring (α : Type u) extends semiring α, comm_monoid α /- ring -/ class ring (α : Type u) extends add_comm_group α, monoid α, distrib α lemma ring.mul_zero [ring α] (a : α) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rw left_distrib, show a * 0 = 0, from (add_left_cancel this).symm lemma ring.zero_mul [ring α] (a : α) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add_left_cancel this).symm instance ring.to_semiring [s : ring α] : semiring α := { s with mul_zero := ring.mul_zero, zero_mul := ring.zero_mul } lemma neg_mul_eq_neg_mul [s : ring α] (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [-right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg [s : ring α] (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [-left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm [s : ring α] (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm [s : ring α] (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg [s : ring α] (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm [s : ring α] (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul [s : ring α] (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib [s : ring α] (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp def mul_sub := @mul_sub_left_distrib lemma mul_sub_right_distrib [s : ring α] (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp def sub_mul := @mul_sub_right_distrib class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul } section comm_ring variable [comm_ring α] lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := by simp [right_distrib, left_distrib] lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := by simp [right_distrib, left_distrib] lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [right_distrib, left_distrib] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two end comm_ring class no_zero_divisors (α : Type u) extends has_mul α, has_zero α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) lemma eq_zero_or_eq_zero_of_mul_eq_zero [no_zero_divisors α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero a b h lemma eq_zero_of_mul_self_eq_zero [no_zero_divisors α] {a : α} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h', h') (assume h', h') class integral_domain (α : Type u) extends comm_ring α, no_zero_divisors α, zero_ne_one_class α section integral_domain variable [integral_domain α] lemma mul_eq_zero_iff_eq_zero_or_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ lemma mul_ne_zero {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h₃, h₁ h₃) (assume h₄, h₂ h₄) lemma eq_of_mul_eq_mul_right {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, from sub_eq_zero_of_eq h, have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this lemma eq_of_mul_eq_mul_left {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, from sub_eq_zero_of_eq h, have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this lemma eq_zero_of_mul_eq_self_right {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := have hb : b - 1 ≠ 0, from suppose b - 1 = 0, have b = 0 + 1, from eq_add_of_sub_eq this, have b = 1, by rwa zero_add at this, h₁ this, have a * b - a = 0, by simp [h₂], have a * (b - 1) = 0, by rwa [mul_sub_left_distrib, mul_one], show a = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hb lemma eq_zero_of_mul_eq_self_left {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right h₁ (by rwa mul_comm at h₂) lemma mul_self_eq_mul_self_iff (a b : α) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (suppose a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul_comm, -mul_self_sub_mul_self_eq, this, sub_self], have a - b = 0 ∨ a + b = 0, from eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (suppose a - b = 0, or.inl (eq_of_sub_eq_zero this)) (suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (suppose a = b ∨ a = -b, or.elim this (suppose a = b, by rewrite this) (suppose a = -b, by rewrite [this, neg_mul_neg])) lemma mul_self_eq_one_iff (a : α) : a * a = 1 ↔ a = 1 ∨ a = -1 := have a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rwa mul_one at this end integral_domain /- TODO(Leo): remove the following annotations as soon as we have support for arithmetic in the SMT tactic framework -/ attribute [ematch] add_zero zero_add mul_one one_mul mul_zero zero_mul
89701ab89fbc9fe7c5e4d232404c507343a3902b
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/complex/basic.lean
8e80f3b820262ae3f2c0c2fadb3a75941b415956
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
18,875
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro The complex numbers, modelled as R^2 in the obvious way. -/ import data.real.basic tactic.ring algebra.field_power structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ def of_real (r : ℝ) : ℂ := ⟨r, 0⟩ instance : has_coe ℝ ℂ := ⟨of_real⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj @[simp] theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp def real_prod_equiv : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem real_prod_equiv_apply (z : ℂ) : real_prod_equiv z = (z.re, z.im) := rfl theorem real_prod_equiv_symm_re (x y : ℝ) : (real_prod_equiv.symm (x, y)).re = x := rfl theorem real_prod_equiv_symm_im (x y : ℝ) : (real_prod_equiv.symm (x, y)).im = y := rfl def conj (z : ℂ) : ℂ := ⟨z.re, -z.im⟩ @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_zero : conj 0 = 0 := ext_iff.2 $ by simp [conj] @[simp] lemma conj_one : conj 1 = 1 := ext_iff.2 $ by simp @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp @[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w := ext_iff.2 $ by simp @[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := rfl @[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w := ext_iff.2 $ by simp @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := ext_iff.2 $ by simp lemma conj_bijective : function.bijective conj := ⟨function.injective_of_has_left_inverse ⟨conj, conj_conj⟩, function.surjective_of_has_right_inverse ⟨conj, conj_conj⟩⟩ lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj z 0 @[simp] lemma eq_conj_iff_real (z : ℂ) : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, e.symm ▸ rfl⟩ def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq] @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq] @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by dsimp [norm_sq]; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] instance : comm_ring ℂ := by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; { intros, apply ext_iff.2; split; simp; ring } @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul] lemma conj_pow (z : ℂ) (n : ℕ) : conj (z ^ n) = conj z ^ n := by induction n; simp [*, conj_mul, pow_succ] @[simp] lemma conj_two : conj (2 : ℂ) = 2 := by apply complex.ext; simp lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re] noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ begin simp, by_cases r = 0, {simp [h]}, rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv] end protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] noncomputable instance : discrete_field ℂ := { inv := has_inv.inv, zero_ne_one := mt (congr_arg re) zero_ne_one, mul_inv_cancel := @complex.mul_inv_cancel, inv_mul_cancel := λ z h, by rw [mul_comm, complex.mul_inv_cancel h], inv_zero := complex.inv_zero, has_decidable_eq := classical.dec_eq _, ..complex.comm_ring } instance re.is_add_group_hom : is_add_group_hom complex.re := by refine_struct {..}; simp instance im.is_add_group_hom : is_add_group_hom complex.im := by refine_struct {..}; simp instance : is_ring_hom conj := by refine_struct {..}; simp instance of_real.is_ring_hom : is_ring_hom (coe : ℝ → ℂ) := by refine_struct {..}; simp lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc] @[simp] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := is_field_hom.map_div coe @[simp] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := is_field_hom.map_fpow of_real r n @[simp] theorem of_real_int_cast : ∀ n : ℤ, ((n : ℝ) : ℂ) = n := int.eq_cast (λ n, ((n : ℝ) : ℂ)) (by rw [int.cast_one, of_real_one]) (λ _ _, by rw [int.cast_add, of_real_add]) @[simp] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := by rw [← int.cast_coe_nat, of_real_int_cast]; refl @[simp] lemma conj_inv (z : ℂ) : conj z⁻¹ = (conj z)⁻¹ := if h : z = 0 then by simp [h] else (domain.mul_left_inj (mt conj_eq_zero.1 h)).1 $ by rw [← conj_mul]; simp [h, -conj_mul] @[simp] lemma conj_sub (z w : ℂ) : conj (z - w) = conj z - conj w := by simp @[simp] lemma conj_div (z w : ℂ) : conj (z / w) = conj z / conj w := by rw [division_def, conj_mul, conj_inv]; refl @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := if h : z = 0 then by simp [h] else (domain.mul_left_inj (mt norm_sq_eq_zero.1 h)).1 $ by rw [← norm_sq_mul]; simp [h, -norm_sq_mul] @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := by rw [division_def, norm_sq_mul, norm_sq_inv]; refl instance char_zero_complex : char_zero ℂ := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h @[simp] theorem of_real_rat_cast : ∀ n : ℚ, ((n : ℝ) : ℂ) = n := by apply rat.eq_cast (λ n, ((n : ℝ) : ℂ)); simp theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero'] @[simp] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs @[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) @[simp] lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@two_pos ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_re_le_abs _) lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_im_le_abs _) @[simp] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← conj_sub, abs_conj]; exact hi j hj⟩ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) end complex
6bf0c1db113cb77d8da57c2c9cd680c73cf7fef0
df561f413cfe0a88b1056655515399c546ff32a5
/7-advanced-multiplication-world/l4.lean
591b94c62fa6b6ad05dac2e7d8bfe62eeb927a2c
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
682
lean
/- induction a with k Pk, exfalso, apply ha, refl, cases k, repeat { rw ← one_eq_succ_zero }, repeat { rw one_mul }, intro h, exact h, intro h, have h2 := Pk (succ_ne_zero k), rw succ_mul at h, Don't think this works, fun attempt tho -/ induction c with k Pk generalizing b, rw mul_zero, rw mul_eq_zero_iff, intro h, cases h, exfalso, exact ha h, exact h, intro h, cases b, rw mul_zero at h, symmetry at h, have h2 := eq_zero_or_eq_zero_of_mul_eq_zero a (succ k), have h3 := h2 h, cases h3, exfalso, exact ha h3, symmetry at h3, exact h3, repeat { rw mul_succ at h }, rw add_right_cancel_iff at h, have h4 := Pk b, have h5 := h4 h, rw ← succ_eq_succ_iff at h5, exact h5,
ed71b8ea98a89e1bf8c5d90c7fb4ceeac2908bea
4fa161becb8ce7378a709f5992a594764699e268
/src/measure_theory/giry_monad.lean
e964a67a2b0defed0c810acf25fef4f5e9ad5796
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
8,526
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import measure_theory.integration /-! # The Giry monad Let X be a measurable space. The collection of all measures on X again forms a measurable space. This construction forms a monad on measurable spaces and measurable functions, called the Giry monad. Note that most sources use the term "Giry monad" for the restriction to *probability* measures. Here we include all measures on X. See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level monad to an honest monad of the functor `Measure : Meas ⥤ Meas`. ## References * <https://ncatlab.org/nlab/show/Giry+monad> ## Tags giry monad -/ noncomputable theory open_locale classical big_operators open classical set filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ε : Type*} namespace measure_theory namespace measure variables [measurable_space α] [measurable_space β] /-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/ instance : measurable_space (measure α) := ⨆ (s : set α) (hs : is_measurable s), (borel ennreal).comap (λμ, μ s) lemma measurable_coe {s : set α} (hs : is_measurable s) : measurable (λμ : measure α, μ s) := measurable_space.comap_le_iff_le_map.1 $ le_supr_of_le s $ le_supr_of_le hs $ le_refl _ lemma measurable_of_measurable_coe (f : β → measure α) (h : ∀(s : set α) (hs : is_measurable s), measurable (λb, f b s)) : measurable f := supr_le $ assume s, supr_le $ assume hs, measurable_space.comap_le_iff_le_map.2 $ by rw [measurable_space.map_comp]; exact h s hs lemma measurable_map (f : α → β) (hf : measurable f) : measurable (λμ : measure α, μ.map f) := measurable_of_measurable_coe _ $ assume s hs, suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)), by simpa [map_apply, hs, hf], measurable_coe (hf.preimage hs) lemma measurable_dirac : measurable (measure.dirac : α → measure α) := measurable_of_measurable_coe _ $ assume s hs, begin simp [hs, supr_eq_if], exact measurable_const.if hs measurable_const end lemma measurable_integral (f : α → ennreal) (hf : measurable f) : measurable (λμ : measure α, μ.integral f) := suffices measurable (λμ : measure α, (⨆n:ℕ, @simple_func.integral α { volume := μ } (simple_func.eapprox f n)) : _ → ennreal), begin convert this, funext μ, exact @lintegral_eq_supr_eapprox_integral α {volume := μ} f hf end, measurable_supr $ assume n, begin dunfold simple_func.integral, refine finset.measurable_sum (simple_func.eapprox f n).range (λ i, _), refine measurable_const.ennreal_mul _, exact measurable_coe ((simple_func.eapprox f n).preimage_measurable _) end /-- Monadic join on `measure` in the category of measurable spaces and measurable functions. -/ def join (m : measure (measure α)) : measure α := measure.of_measurable (λs hs, m.integral (λμ, μ s)) (by simp [integral]) begin assume f hf h, simp [measure_Union h hf], apply lintegral_tsum, assume i, exact measurable_coe (hf i) end @[simp] lemma join_apply {m : measure (measure α)} : ∀{s : set α}, is_measurable s → join m s = m.integral (λμ, μ s) := measure.of_measurable_apply lemma measurable_join : measurable (join : measure (measure α) → measure α) := measurable_of_measurable_coe _ $ assume s hs, by simp [hs]; exact measurable_integral _ (measurable_coe hs) lemma integral_join {m : measure (measure α)} {f : α → ennreal} (hf : measurable f) : integral (join m) f = integral m (λμ, integral μ f) := begin transitivity, apply lintegral_eq_supr_eapprox_integral, { exact hf }, have : ∀n x, @volume α { volume := join m} (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) = m.integral (λμ, @volume α { volume := μ } ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}))) := assume n x, join_apply (simple_func.measurable_sn _ _), conv { to_lhs, congr, funext, rw [simple_func.integral] }, simp [this], transitivity, have : ∀(s : ℕ → finset ennreal) (f : ℕ → ennreal → measure α → ennreal) (hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, ∑ r in s n, r * f n r μ)), (⨆n:ℕ, ∑ r in s n, r * integral m (f n r)) = integral m (λμ, ⨆n:ℕ, ∑ r in s n, r * f n r μ), { assume s f hf hm, symmetry, transitivity, apply lintegral_supr, { assume n, exact finset.measurable_sum _ (assume r, measurable_const.ennreal_mul (hf _ _)) }, { exact hm }, congr, funext n, transitivity, apply lintegral_finset_sum, { assume r, exact measurable_const.ennreal_mul (hf _ _) }, congr, funext r, apply lintegral_const_mul, exact hf _ _ }, specialize this (λn, simple_func.range (simple_func.eapprox f n)), specialize this (λn r μ, @volume α { volume := μ } (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})), refine this _ _; clear this, { assume n r, apply measurable_coe, exact simple_func.measurable_sn _ _ }, { change monotone (λn μ, @simple_func.integral α {volume := μ} (simple_func.eapprox f n)), assume n m h μ, apply simple_func.integral_le_integral, apply simple_func.monotone_eapprox, assumption }, congr, funext μ, symmetry, apply lintegral_eq_supr_eapprox_integral, exact hf end /-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable functions. When the function `f` is not measurable the result is not well defined. -/ def bind (m : measure α) (f : α → measure β) : measure β := join (map f m) @[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β} (hs : is_measurable s) (hf : measurable f) : bind m f s = m.integral (λa, f a s) := by rw [bind, join_apply hs, integral_map (measurable_coe hs) hf] lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) := measurable_join.comp (measurable_map _ hg) lemma integral_bind {m : measure α} {g : α → measure β} {f : β → ennreal} (hg : measurable g) (hf : measurable f) : integral (bind m g) f = integral m (λa, integral (g a) f) := begin transitivity, exact integral_join hf, exact integral_map (measurable_integral _ hf) hg end lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ} (hf : measurable f) (hg : measurable g) : bind (bind m f) g = bind m (λa, bind (f a) g) := measure.ext $ assume s hs, begin rw [bind_apply hs hg, bind_apply hs ((measurable_bind' hg).comp hf), integral_bind hf], { congr, funext a, exact (bind_apply hs hg).symm }, exact (measurable_coe hs).comp hg end lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a := measure.ext $ assume s hs, by rw [bind_apply hs hf, integral_dirac a ((measurable_coe hs).comp hf)] lemma dirac_bind {m : measure α} : bind m dirac = m := measure.ext $ assume s hs, begin rw [bind_apply hs measurable_dirac], simp [dirac_apply _ hs], transitivity, apply lintegral_supr_const, assumption, exact one_mul _ end lemma map_dirac {f : α → β} (hf : measurable f) (a : α) : map f (dirac a) = dirac (f a) := measure.ext $ assume s hs, by rw [dirac_apply (f a) hs, map_apply hf hs, dirac_apply a (hf s hs), set.mem_preimage] lemma join_eq_bind (μ : measure (measure α)) : join μ = bind μ id := by rw [bind, map_id] lemma join_map_map {f : α → β} (hf : measurable f) (μ : measure (measure α)) : join (map (map f) μ) = map f (join μ) := measure.ext $ assume s hs, begin rw [join_apply hs, map_apply hf hs, join_apply, integral_map (measurable_coe hs) (measurable_map f hf)], { congr, funext ν, exact map_apply hf hs }, exact hf s hs end lemma join_map_join (μ : measure (measure (measure α))) : join (map join μ) = join (join μ) := begin show bind μ join = join (join μ), rw [join_eq_bind, join_eq_bind, bind_bind measurable_id measurable_id], apply congr_arg (bind μ), funext ν, exact join_eq_bind ν end lemma join_map_dirac (μ : measure α) : join (map dirac μ) = μ := dirac_bind lemma join_dirac (μ : measure α) : join (dirac μ) = μ := eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id _) end measure end measure_theory
95afc39fdf7e52c79132051670c9138c9e70b564
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/data/multiset.lean
ba7d0ed9a77f3a76450031d2349071c40317c62e
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
105,784
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.list.basic data.list.perm data.list.sort data.quot data.string algebra.order_functions algebra.group_power algebra.ordered_group open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • ` := add_monoid.smul instance list.perm.setoid (α : Type*) : setoid (list α) := setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩ /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.perm.setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe (l₁ l₂ : list α) : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) {s t : multiset α} : a::s = a::t ↔ s = t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) (s) : p s := quot.induction_on s $ λ l, by induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_of_forall_not_mem H; refl theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := λ s, quot.induction_on s $ λ l, subperm.refl _, le_trans := λ s t u, quotient.induction_on₃ s t u $ @subperm.trans _, le_antisymm := λ s t, quotient.induction_on₂ s t $ λ l₁ l₂ h₁ h₂, quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card ({a} : multiset α) = 1 := calc card ({a} : multiset α) = card (0 : multiset α) + 1 : multiset.card_cons a 0 ... = 1 : by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] lemma strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero (n : ℕ) : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ @[simp] theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive multiset.sum_repeat] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, -map_const, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive multiset.sum_bind] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_multiset variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) end decidable_pi_multiset /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp [max_min_distrib_left], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono (assume a b, h) lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] end rel /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil _ @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ λ l₁, let l₂ (a) : list (σ a) := classical.some (quotient.exists_rep (t a)) in have t = λ a, l₂ a, from eq.symm $ funext $ λ a, classical.some_spec (quotient.exists_rep (t a)), by rw [this]; simpa using nodup_sigma theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on { pi.empty δ } (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = {pi.empty δ} := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _ , nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := multiset.induction_on m begin assume f, have : f = pi.empty δ, { funext a ha, exact ha.elim }, subst this, split, { intros _ a ha, exact ha.elim }, { intros, simp, exact mem_cons_self _ 0 } end begin assume a m ih f, simp [iff_def], split, { intros b hb f' hf' eq a' ha', subst eq, rw [ih] at hf', by_cases a' = a, { subst h, rw [pi.cons_same], exact hb }, { rw [pi.cons_ne _ h], exact hf' _ _ } }, { assume hf, refine ⟨f a (mem_cons_self a _), hf a (mem_cons_self a _), (λa ha, f a (mem_cons_of_mem ha)), _, _⟩, { rw [ih], assume a' h', exact hf _ _ }, { funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } } end end pi end multiset
334e170c60f6e204d6f7c9f692a54e466a9e1a4f
4727251e0cd73359b15b664c3170e5d754078599
/src/data/dlist/instances.lean
cc0c8faa21507b3ab129a66aa9dac8e39787e45e
[ "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
981
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.traversable.equiv import control.traversable.instances import data.dlist /-! # Traversable instance for dlists This file provides the equivalence between `list α` and `dlist α` and the traversable instance for `dlist`. -/ open function equiv namespace dlist variables (α : Type*) /-- The natural equivalence between lists and difference lists, using `dlist.of_list` and `dlist.to_list`. -/ def list_equiv_dlist : list α ≃ dlist α := by refine { to_fun := dlist.of_list, inv_fun := dlist.to_list, .. }; simp [function.right_inverse,left_inverse,to_list_of_list,of_list_to_list] instance : traversable dlist := equiv.traversable list_equiv_dlist instance : is_lawful_traversable dlist := equiv.is_lawful_traversable list_equiv_dlist instance {α} : inhabited (dlist α) := ⟨dlist.empty⟩ end dlist
f66a7241e98c1aadb7dbfc6949a79b0225ef0595
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/445.lean
3f19bcb976a8630948caa4ce004aed95703550b6
[ "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
1,610
lean
import Lean def f : Nat → Bool | 0 => true | n + 1 => (match n with | 0 => true | _ + 1 => true) && f n def g (i j : Nat) : Nat := if i < 5 then 0 else match j with | Nat.zero => 1 | Nat.succ j => g i j def h (i j : Nat) : Nat := i + match j with | Nat.zero => 1 | Nat.succ j => h i j def r (i j : Nat) : Nat := i + match j with | Nat.zero => 1 | Nat.succ j => i * match j with | Nat.zero => 2 | Nat.succ j => r i j def s (i j : Nat) : Nat := let z := match j with | Nat.zero => i | Nat.succ j => s i j z + z example : f 0 = true := rfl example : f (i+1) = ((match i with | 0 => true | _ + 1 => true) && f i) := rfl example : g i (j + 1) = if i < 5 then 0 else g i j := rfl example : g i 0 = if i < 5 then 0 else 1 := rfl example : h i 0 = i + 1 := rfl example : h i (j + 1) = i + h i j := rfl example : r i 0 = i + 1 := rfl example : r i 1 = i + i * 2 := rfl example : r i (j + 2) = i + i * r i j := rfl example : s i (j + 1) = let z := s i j; z + z := rfl open Lean open Lean.Meta open Lean.Elab open Lean.Elab.Command elab "unfold " e:term : command => runTermElabM none fun xs => do let e ← instantiateMVars (← Term.withSynthesize <| Term.elabTerm e none) match (← unfoldDefinition? e) with | some e => logInfo m!"{e}" | none => throwError "" section end variable (i j : Nat) unfold f 0 unfold f (i+1) unfold g i 0 unfold g i (j+1) unfold h i 0 unfold h i (j + 1) unfold r i 0 unfold r i 1 unfold r i (j + 2) unfold r i j.succ.succ unfold s i (j + 1)
ffe57ff389bb3d84bc156bf3dd7282e3da5334fa
485c57241aa5e06451e90d4521fb46f57829cc24
/proLogic.lean
fb35c5e9ea597ef4242a3b21cc35b07c1db795ca
[]
no_license
ngamt/Lean
8bde6955335078b475c9057c97b59d65f3312ca7
08eda4561ea483e04c7e977277f4e2f0cdc834b3
refs/heads/master
1,584,465,933,497
1,527,755,565,000
1,527,755,565,000
133,787,626
0
0
null
null
null
null
UTF-8
Lean
false
false
658
lean
example (m n : ℕ) : m + n = n + m := by simp theorem t1(p q: Prop):p → q → p:= assume hp:p, assume hq:q, show p, from hp --theorem t2(p q r: Prop)(H1:q → r)(H1:q → r):= theorem and_swap(p q : Prop):p ∧ q ↔ q ∧ p:= begin apply iff.intro, intro H1, exact and.intro(and.right H1)(and.left H1), intro H2, exact and.intro(and.right H2)(and.left H2), end #check and_swap theorem or_swap(p q : Prop):p ∨ q ↔ q ∨ p:= begin apply iff.intro, intro H1, apply or.elim H1, intro H2, exact or.inr H2, intro H3, exact or.inl H3, intro H4, apply or.elim H4, intro H2, exact or.inr H2, intro H3, exact or.inl H3, end #check or_swap
6e04cfe43f166c7270be024e81ef1b2964a5e7fd
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Util/SCC.lean
887e2926d928452cb7e47f7e23dc973d36b46dc9
[ "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
3,180
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap namespace Lean.SCC /- Very simple implementation of Tarjan's SCC algorithm. Performance is not a goal here since we use this module to compiler mutually recursive definitions, where each function (and nested let-rec) in the mutual block is a vertex. So, the graphs are small. -/ open Std section variable (α : Type) [BEq α] [Hashable α] structure Data where index? : Option Nat := none lowlink? : Option Nat := none onStack : Bool := false structure State where stack : List α := [] nextIndex : Nat := 0 data : Std.HashMap α Data := {} sccs : List (List α) := [] abbrev M := StateM (State α) end variable {α : Type} [BEq α] [Hashable α] private def getDataOf (a : α) : M α Data := do let s ← get match s.data.find? a with | some d => pure d | none => pure {} private def push (a : α) : M α Unit := modify fun s => { s with stack := a :: s.stack, nextIndex := s.nextIndex + 1, data := s.data.insert a { index? := s.nextIndex, lowlink? := s.nextIndex, onStack := true } } private def modifyDataOf (a : α) (f : Data → Data) : M α Unit := modify fun s => { s with data := match s.data.find? a with | none => s.data | some d => s.data.insert a (f d) } private def resetOnStack (a : α) : M α Unit := modifyDataOf a fun d => { d with onStack := false } private def updateLowLinkOf (a : α) (v : Option Nat) : M α Unit := modifyDataOf a fun d => { d with lowlink? := match d.lowlink?, v with | i, none => i | none, i => i | some i, some j => if i < j then i else j } private def addSCC (a : α) : M α Unit := do let rec add | [], newSCC => modify fun s => { s with stack := [], sccs := newSCC :: s.sccs } | b::bs, newSCC => do resetOnStack b; let newSCC := b::newSCC; if a != b then add bs newSCC else modify fun s => { s with stack := bs, sccs := newSCC :: s.sccs } add (← get).stack [] @[specialize] private partial def sccAux (successorsOf : α → List α) (a : α) : M α Unit := do push a (successorsOf a).forM fun b => do let bData ← getDataOf b; if bData.index?.isNone then -- `b` has not been visited yet sccAux successorsOf b; let bData ← getDataOf b; updateLowLinkOf a bData.lowlink? else if bData.onStack then do -- `b` is on the stack. So, it must be in the current SCC -- The edge `(a, b)` is pointing to an SCC already found and must be ignored updateLowLinkOf a bData.index? else pure () let aData ← getDataOf a; if aData.lowlink? == aData.index? then addSCC a @[specialize] def scc (vertices : List α) (successorsOf : α → List α) : List (List α) := let main : M α Unit := vertices.forM fun a => do let aData ← getDataOf a if aData.index?.isNone then sccAux successorsOf a let (_, s) := main.run {} s.sccs.reverse end Lean.SCC
30868fd62b3fca3ff71f85acfac5eeea530f8ed4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/shrinking_lemma.lean
0212e4856a501c39a0fe64b77b7d7f7e43cc11bf
[ "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
12,337
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Reid Barton -/ import topology.separation /-! # The shrinking lemma > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove a few versions of the shrinking lemma. The lemma says that in a normal topological space a point finite open covering can be “shrunk”: for a point finite open covering `u : ι → set X` there exists a refinement `v : ι → set X` such that `closure (v i) ⊆ u i`. For finite or countable coverings this lemma can be proved without the axiom of choice, see [ncatlab](https://ncatlab.org/nlab/show/shrinking+lemma) for details. We only formalize the most general result that works for any covering but needs the axiom of choice. We prove two versions of the lemma: * `exists_subset_Union_closure_subset` deals with a covering of a closed set in a normal space; * `exists_Union_eq_closure_subset` deals with a covering of the whole space. ## Tags normal space, shrinking lemma -/ open set function open_locale classical noncomputable theory variables {ι X : Type*} [topological_space X] [normal_space X] namespace shrinking_lemma /-- Auxiliary definition for the proof of `shrinking_lemma`. A partial refinement of a covering `⋃ i, u i` of a set `s` is a map `v : ι → set X` and a set `carrier : set ι` such that * `s ⊆ ⋃ i, v i`; * all `v i` are open; * if `i ∈ carrier v`, then `closure (v i) ⊆ u i`; * if `i ∉ carrier`, then `v i = u i`. This type is equipped with the folowing partial order: `v ≤ v'` if `v.carrier ⊆ v'.carrier` and `v i = v' i` for `i ∈ v.carrier`. We will use Zorn's lemma to prove that this type has a maximal element, then show that the maximal element must have `carrier = univ`. -/ @[nolint has_nonempty_instance] -- the trivial refinement needs `u` to be a covering structure partial_refinement (u : ι → set X) (s : set X) := (to_fun : ι → set X) (carrier : set ι) (is_open' : ∀ i, is_open (to_fun i)) (subset_Union' : s ⊆ ⋃ i, to_fun i) (closure_subset' : ∀ i ∈ carrier, closure (to_fun i) ⊆ (u i)) (apply_eq' : ∀ i ∉ carrier, to_fun i = u i) namespace partial_refinement variables {u : ι → set X} {s : set X} instance : has_coe_to_fun (partial_refinement u s) (λ _, ι → set X) := ⟨to_fun⟩ lemma subset_Union (v : partial_refinement u s) : s ⊆ ⋃ i, v i := v.subset_Union' lemma closure_subset (v : partial_refinement u s) {i : ι} (hi : i ∈ v.carrier) : closure (v i) ⊆ (u i) := v.closure_subset' i hi lemma apply_eq (v : partial_refinement u s) {i : ι} (hi : i ∉ v.carrier) : v i = u i := v.apply_eq' i hi protected lemma is_open (v : partial_refinement u s) (i : ι) : is_open (v i) := v.is_open' i protected lemma subset (v : partial_refinement u s) (i : ι) : v i ⊆ u i := if h : i ∈ v.carrier then subset.trans subset_closure (v.closure_subset h) else (v.apply_eq h).le attribute [ext] partial_refinement instance : partial_order (partial_refinement u s) := { le := λ v₁ v₂, v₁.carrier ⊆ v₂.carrier ∧ ∀ i ∈ v₁.carrier, v₁ i = v₂ i, le_refl := λ v, ⟨subset.refl _, λ _ _, rfl⟩, le_trans := λ v₁ v₂ v₃ h₁₂ h₂₃, ⟨subset.trans h₁₂.1 h₂₃.1, λ i hi, (h₁₂.2 i hi).trans (h₂₃.2 i $ h₁₂.1 hi)⟩, le_antisymm := λ v₁ v₂ h₁₂ h₂₁, have hc : v₁.carrier = v₂.carrier, from subset.antisymm h₁₂.1 h₂₁.1, ext _ _ (funext $ λ x, if hx : x ∈ v₁.carrier then h₁₂.2 _ hx else (v₁.apply_eq hx).trans (eq.symm $ v₂.apply_eq $ hc ▸ hx)) hc } /-- If two partial refinements `v₁`, `v₂` belong to a chain (hence, they are comparable) and `i` belongs to the carriers of both partial refinements, then `v₁ i = v₂ i`. -/ lemma apply_eq_of_chain {c : set (partial_refinement u s)} (hc : is_chain (≤) c) {v₁ v₂} (h₁ : v₁ ∈ c) (h₂ : v₂ ∈ c) {i} (hi₁ : i ∈ v₁.carrier) (hi₂ : i ∈ v₂.carrier) : v₁ i = v₂ i := begin wlog hle : v₁ ≤ v₂, { cases hc.total h₁ h₂; [skip, symmetry]; apply_assumption; assumption' }, exact hle.2 _ hi₁, end /-- The carrier of the least upper bound of a non-empty chain of partial refinements is the union of their carriers. -/ def chain_Sup_carrier (c : set (partial_refinement u s)) : set ι := ⋃ v ∈ c, carrier v /-- Choice of an element of a nonempty chain of partial refinements. If `i` belongs to one of `carrier v`, `v ∈ c`, then `find c ne i` is one of these partial refinements. -/ def find (c : set (partial_refinement u s)) (ne : c.nonempty) (i : ι) : partial_refinement u s := if hi : ∃ v ∈ c, i ∈ carrier v then hi.some else ne.some lemma find_mem {c : set (partial_refinement u s)} (i : ι) (ne : c.nonempty) : find c ne i ∈ c := by { rw find, split_ifs, exacts [h.some_spec.fst, ne.some_spec] } lemma mem_find_carrier_iff {c : set (partial_refinement u s)} {i : ι} (ne : c.nonempty) : i ∈ (find c ne i).carrier ↔ i ∈ chain_Sup_carrier c := begin rw find, split_ifs, { have : i ∈ h.some.carrier ∧ i ∈ chain_Sup_carrier c, from ⟨h.some_spec.snd, mem_Union₂.2 h⟩, simp only [this] }, { have : i ∉ ne.some.carrier ∧ i ∉ chain_Sup_carrier c, from ⟨λ hi, h ⟨_, ne.some_spec, hi⟩, mt mem_Union₂.1 h⟩, simp only [this] } end lemma find_apply_of_mem {c : set (partial_refinement u s)} (hc : is_chain (≤) c) (ne : c.nonempty) {i v} (hv : v ∈ c) (hi : i ∈ carrier v) : find c ne i i = v i := apply_eq_of_chain hc (find_mem _ _) hv ((mem_find_carrier_iff _).2 $ mem_Union₂.2 ⟨v, hv, hi⟩) hi /-- Least upper bound of a nonempty chain of partial refinements. -/ def chain_Sup (c : set (partial_refinement u s)) (hc : is_chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, {i | x ∈ u i}.finite) (hU : s ⊆ ⋃ i, u i) : partial_refinement u s := begin refine ⟨λ i, find c ne i i, chain_Sup_carrier c, λ i, (find _ _ _).is_open i, λ x hxs, mem_Union.2 _, λ i hi, (find c ne i).closure_subset ((mem_find_carrier_iff _).2 hi), λ i hi, (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi)⟩, rcases em (∃ i ∉ chain_Sup_carrier c, x ∈ u i) with ⟨i, hi, hxi⟩|hx, { use i, rwa (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi) }, { simp_rw [not_exists, not_imp_not, chain_Sup_carrier, mem_Union₂] at hx, haveI : nonempty (partial_refinement u s) := ⟨ne.some⟩, choose! v hvc hiv using hx, rcases (hfin x hxs).exists_maximal_wrt v _ (mem_Union.1 (hU hxs)) with ⟨i, hxi : x ∈ u i, hmax : ∀ j, x ∈ u j → v i ≤ v j → v i = v j⟩, rcases mem_Union.1 ((v i).subset_Union hxs) with ⟨j, hj⟩, use j, have hj' : x ∈ u j := (v i).subset _ hj, have : v j ≤ v i, from (hc.total (hvc _ hxi) (hvc _ hj')).elim (λ h, (hmax j hj' h).ge) id, rwa find_apply_of_mem hc ne (hvc _ hxi) (this.1 $ hiv _ hj') } end /-- `chain_Sup hu c hc ne hfin hU` is an upper bound of the chain `c`. -/ lemma le_chain_Sup {c : set (partial_refinement u s)} (hc : is_chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, {i | x ∈ u i}.finite) (hU : s ⊆ ⋃ i, u i) {v} (hv : v ∈ c) : v ≤ chain_Sup c hc ne hfin hU := ⟨λ i hi, mem_bUnion hv hi, λ i hi, (find_apply_of_mem hc _ hv hi).symm⟩ /-- If `s` is a closed set, `v` is a partial refinement, and `i` is an index such that `i ∉ v.carrier`, then there exists a partial refinement that is strictly greater than `v`. -/ lemma exists_gt (v : partial_refinement u s) (hs : is_closed s) (i : ι) (hi : i ∉ v.carrier) : ∃ v' : partial_refinement u s, v < v' := begin have I : s ∩ (⋂ j ≠ i, (v j)ᶜ) ⊆ v i, { simp only [subset_def, mem_inter_iff, mem_Inter, and_imp], intros x hxs H, rcases mem_Union.1 (v.subset_Union hxs) with ⟨j, hj⟩, exact (em (j = i)).elim (λ h, h ▸ hj) (λ h, (H j h hj).elim) }, have C : is_closed (s ∩ (⋂ j ≠ i, (v j)ᶜ)), from is_closed.inter hs (is_closed_bInter $ λ _ _, is_closed_compl_iff.2 $ v.is_open _), rcases normal_exists_closure_subset C (v.is_open i) I with ⟨vi, ovi, hvi, cvi⟩, refine ⟨⟨update v i vi, insert i v.carrier, _, _, _, _⟩, _, _⟩, { intro j, by_cases h : j = i; simp [h, ovi, v.is_open] }, { refine λ x hx, mem_Union.2 _, rcases em (∃ j ≠ i, x ∈ v j) with ⟨j, hji, hj⟩|h, { use j, rwa update_noteq hji }, { push_neg at h, use i, rw update_same, exact hvi ⟨hx, mem_bInter h⟩ } }, { rintro j (rfl|hj), { rwa [update_same, ← v.apply_eq hi] }, { rw update_noteq (ne_of_mem_of_not_mem hj hi), exact v.closure_subset hj } }, { intros j hj, rw [mem_insert_iff, not_or_distrib] at hj, rw [update_noteq hj.1, v.apply_eq hj.2] }, { refine ⟨subset_insert _ _, λ j hj, _⟩, exact (update_noteq (ne_of_mem_of_not_mem hj hi) _ _).symm }, { exact λ hle, hi (hle.1 $ mem_insert _ _) } end end partial_refinement end shrinking_lemma open shrinking_lemma variables {u : ι → set X} {s : set X} /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_subset_Union_closure_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, {i | x ∈ u i}.finite) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := begin classical, haveI : nonempty (partial_refinement u s) := ⟨⟨u, ∅, uo, us, λ _, false.elim, λ _ _, rfl⟩⟩, have : ∀ c : set (partial_refinement u s), is_chain (≤) c → c.nonempty → ∃ ub, ∀ v ∈ c, v ≤ ub, from λ c hc ne, ⟨partial_refinement.chain_Sup c hc ne uf us, λ v hv, partial_refinement.le_chain_Sup _ _ _ _ hv⟩, rcases zorn_nonempty_partial_order this with ⟨v, hv⟩, suffices : ∀ i, i ∈ v.carrier, from ⟨v, v.subset_Union, λ i, v.is_open _, λ i, v.closure_subset (this i)⟩, contrapose! hv, rcases hv with ⟨i, hi⟩, rcases v.exists_gt hs i hi with ⟨v', hlt⟩, exact ⟨v', hlt.le, hlt.ne'⟩ end /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each new closed set is contained in the corresponding original open set. See also `exists_subset_Union_closure_subset` for a stronger statement. -/ lemma exists_subset_Union_closed_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, {i | x ∈ u i}.finite) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, hsv, hvo, hv⟩ := exists_subset_Union_closure_subset hs uo uf us in ⟨λ i, closure (v i), subset.trans hsv (Union_mono $ λ i, subset_closure), λ i, is_closed_closure, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_Union_eq_closure_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, {i | x ∈ u i}.finite) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closure_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each of the new closed sets is contained in the corresponding original open set. See also `exists_Union_eq_closure_subset` for a stronger statement. -/ lemma exists_Union_eq_closed_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, {i | x ∈ u i}.finite) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closed_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩
bcf537a1c60059b26e3bb30a0324c35e13fca681
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/computability/partrec_code.lean
75119770bd87fe1abc2b070b5d8f9301c581ba4a
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
37,490
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Godel numbering for partial recursive functions. -/ import computability.partrec open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrec₂.unpaired'.2 $ begin refine partrec.map ((@partrec₂.unpaired' (λ (a b : ℕ), nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.to₂, have := rfind (partrec₂.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrec₂.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).to₂), simp at this, exact this end inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) protected def const : ℕ → code | 0 := zero | (n+1) := comp succ (const n) protected def id : code := pair left right def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) def encode_code : code → ℕ | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 def of_nat_code : ℕ → code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end private theorem encode_of_nat_code : ∀ n, encode_code (of_nat_code n) = n | 0 := rfl | 1 := rfl | 2 := rfl | 3 := rfl | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, λ c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.le_mkpair_left _ _) this, lt_of_le_of_lt (nat.le_mkpair_right _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code, -add_comm], exact nat.bit0_lt (nat.lt_succ_self _), end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code, -add_comm], exact nat.lt_succ_self _, end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_refl _), end section open primrec theorem pair_prim : primrec₂ pair := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem comp_prim : primrec₂ comp := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem prec_prim : primrec₂ prec := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end theorem rec_prim {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec (λ a : α × code × code × σ × σ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : α → code → code → σ → σ → σ} (hco : primrec (λ a : α × code × code × σ × σ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : α → code → code → σ → σ → σ} (hpc : primrec (λ a : α × code × code × σ × σ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : α → code → σ → σ} (hrf : primrec (λ a : α × code × σ, rf a.1 a.2.1 a.2.2)) : let F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /- TODO(Mario): less copy-paste from previous proof -/ theorem rec_computable {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have m₂ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : computable₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp computable.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end def eval : code → ℕ →. ℕ | zero := pure 0 | succ := nat.succ | left := λ n, n.unpair.1 | right := λ n, n.unpair.2 | (pair cf cg) := λ n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := λ n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (λ a n, n.elim (eval cf a) (λ y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) instance : has_mem (ℕ →. ℕ) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (code.const n) m = roption.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = roption.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, code.const, nat.iterate_succ'] theorem curry_prim : primrec₂ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem exists_code {f : ℕ →. ℕ} : nat.partrec f ↔ ∃ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, roption.map_id'] }, end, λ h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ def evaln : ∀ k : ℕ, code → ℕ → option ℕ | 0 _ := λ m, none | (k+1) zero := λ n, guard (n ≤ k) >> pure 0 | (k+1) succ := λ n, guard (n ≤ k) >> pure (nat.succ n) | (k+1) left := λ n, guard (n ≤ k) >> pure n.unpair.1 | (k+1) right := λ n, guard (n ≤ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := λ n, guard (n ≤ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := λ n, guard (n ≤ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := λ n, guard (n ≤ k) >> n.unpaired (λ a n, n.cases (evaln (k+1) cf a) $ λ y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := λ n, guard (n ≤ k) >> n.unpaired (λ a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : ∀ {o : option ℕ}, x ∈ guard (n ≤ k) >> o → n < k + 1, { cases c; rw [evaln] at h; exact this h }, simp [(>>)], exact λ _ h _, nat.lt_succ_of_le h end theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0 k₂ c n x hl h := by simp [evaln] at h; cases h | (k+1) (k₂+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ guard (n ≤ k) >> o₁ → x ∈ guard (n ≤ k₂) >> o₂, { simp [(>>)], introv h h₁ h₂ h₃, exact ⟨le_trans h₂ h, h₁ h₃⟩ }, simp at h ⊢, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊢; refine this hl' (λ h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊢, exact h.imp (λ a, and.imp (Exists.imp (λ b, and.imp_left (hf _ _))) (Exists.imp (λ b, and.imp_left (hg _ _)))) }, { -- comp cf cg simp at h ⊢, exact h.imp (λ a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact λ y h₁ h₂, ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ } }, { -- rfind' cf simp at h ⊢, refine h.imp (λ x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊢; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨_, ⟨y, ef, rfl⟩, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine λ y h₁ h₂, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ h₂ } } }, { -- rfind' cf rcases h with ⟨m, h₁, h₂⟩, by_cases m0 : m = 0; simp [m0] at h₂, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, λ m, (nat.not_lt_zero _).elim⟩, by injection h₂ with h₂; simp [h₂]⟩ }, { have := evaln_sound h₂, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, refine ⟨y+1, ⟨by simpa using hy₁, λ i im, _⟩, by simp⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hy₂ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := ⟨λ h, begin suffices : ∃ k, x ∈ evaln (k+1) c n, { exact let ⟨k, h⟩ := this in ⟨k+1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊢, iterate 4 { exact ⟨⟨_, le_refl _⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hk₁⟩, rcases hg hy with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, ⟨_, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, rfl⟩, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hk₁⟩, rcases hf hx with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = n₂, induction n₂ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hk₁⟩, rcases hg hx with ⟨k₂, hk₂⟩, refine ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_left_of_le $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hk₂⟩, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, suffices : ∃ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hy₂, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hy₂ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hk₁⟩, rcases IH m.succ (by simpa [nat.succ_eq_add_one] using hy₁) (λ i hi, by simpa [nat.succ_eq_add_one] using hy₂ (nat.succ_lt_succ hi)) with ⟨k₂, hk₂⟩, simp at hk₁, exact ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, a, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, by simpa [nat.succ_eq_add_one, a0] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ } } end, λ ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option ℕ))) (p : ℕ × code) (n : ℕ) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (λ p:_×(_×_)×_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option ℕ))) : option (list (option ℕ)) := option.some $ let a := of_nat (ℕ × code) L.length, k := a.1, c := a.2 in (list.range k).map (λ n, k.cases none $ λ k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (λ cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (λ cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (λ cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (λ y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (λ cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (λ _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (ℕ × code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrec₂.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrec₂.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrec₂.mkpair.comp z $ primrec₂.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrec₂.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrec₂.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (λ b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_ge_len, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end theorem evaln_prim : primrec (λ (a : (ℕ × code) × ℕ), evaln a.1.1 a.1.2 a.2) := have primrec₂ (λ (_:unit) (n : ℕ), let a := of_nat (ℕ × code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).to₂ $ λ _ p, begin simp [G], rw (_ : (of_nat (ℕ × code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (λ n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : ∀ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) → lup ((list.range (mkpair k (encode c))).map (λ n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.to₂).of_eq $ λ ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (λ k, evaln k c n) := roption.ext $ λ x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrec₂ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq $ λ a, by simp [eval_eq_rfind_opt] theorem fixed_point {f : code → code} (hf : computable f) : ∃ c : code, eval (f c) = eval c := begin let g : ℕ → ℕ →. ℕ := λ x y, roption.bind (eval (of_nat code x) x) (λ b, eval (of_nat code b) y), have : partrec₂ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).to₂, rcases exists_code.1 this with ⟨cg, eg⟩, have := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, rcases exists_code.1 this with ⟨cF, eF⟩, refine ⟨curry cg (encode cF), funext $ λ n, _⟩, have := congr_fun eF (encode cF), simp at this, simp [eg, this, roption.map_id', g] end theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ λ c e, funext $ λ n, by simp [e.symm, ef, roption.map_id'] end end nat.partrec.code
b33f6ff9e2045949be8a58095a5b36e7b1d21755
626e312b5c1cb2d88fca108f5933076012633192
/src/ring_theory/power_series/basic.lean
13150f47cb64e4a55290b2f5317d4a5b26438572
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
64,490
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.mv_polynomial import linear_algebra.std_basis import ring_theory.ideal.local_ring import ring_theory.ideal.operations import ring_theory.multiplicity import ring_theory.algebra_tower import tactic.linarith import algebra.big_operators.nat_antidiagonal /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m ≤ n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default _⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (mv_power_series σ A) := pi.module _ _ _ instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower section semiring variables (R) [semiring R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R := linear_map.std_basis R _ n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := function.funext_iff lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) : monomial R n = linear_map.std_basis R _ n := by convert rfl -- unify the `decidable` arguments lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply, function.update_apply, pi.zero_apply] @[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := linear_map.std_basis_same R _ n a lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coeff R m (monomial R n a) = 0 := linear_map.std_basis_ne R _ _ _ h a lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) : m = n := by_contra $ λ h', h $ coeff_monomial_ne h' a @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one [decidable_eq σ] : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := coeff_monomial _ _ _ lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial_same 0 1 lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] lemma coeff_monomial_mul (a : R) : coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_mul_monomial (a : R) : coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_add_monomial_mul (a : R) : coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ := begin rw [coeff_monomial_mul, if_pos, nat_add_sub_cancel_left], exact le_add_right le_rfl end lemma coeff_add_mul_monomial (a : R) : coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a := begin rw [coeff_mul_monomial, if_pos, nat_add_sub_cancel], exact le_add_left le_rfl end protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1 protected lemma mul_one : φ * 1 = φ := ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1 protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := begin ext1 n, simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _; simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp, exists_prop], { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl, simp [add_assoc] }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl, apply mul_assoc }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl, refl }, { rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl, refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm] using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, simp only [coeff_mul_monomial, coeff_monomial], split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl }, { rw [← h₂, nat_sub_add_cancel h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, nat_add_sub_cancel] at h₂, exact (h₂ rfl).elim }, { exact zero_mul b }, { rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, map_zero' := (monomial R (0 : _)).map_zero, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := coeff_monomial _ _ _ lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := coeff_monomial _ _ _ lemma coeff_index_single_X [decidable_eq σ] (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := coeff_monomial_same _ _ lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero, monomial_zero_one] }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := by simpa using coeff_add_mul_monomial n 0 φ a @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := by simpa using coeff_add_monomial_mul 0 n φ a lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_mul_monomial, if_neg this] end lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_monomial_mul, if_neg this] end variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], map_zero' := linear_map.map_zero _, .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map (constant_coeff σ R).to_monoid_hom @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl @[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) : map σ f (monomial R n a) = monomial S n (f a) := by { ext m, simp [coeff_monomial, apply_ite f] } @[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) := map_monomial _ _ _ @[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [X] end map section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R (mv_power_series σ A) := { commutes' := λ a φ, by { ext n, simp [algebra.commutes] }, smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] }, to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R), .. mv_power_series.module } theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) := begin change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _, simp, end instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], inhabit σ, refine ⟨X (default σ), _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, not_forall], refine ⟨finsupp.single (default σ) 1, _⟩, simp [algebra_map_apply, coeff_C], end⟩⟩ end algebra section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := ∑ m in Iic_finset n, mv_polynomial.monomial m (coeff R m φ) lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc_fun n φ).coeff m = if m ≤ n then coeff R m φ else 0 := by simp [trunc_fun, mv_polynomial.coeff_sum] variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := by { ext, simp [coeff_trunc_fun] }, map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc R n φ).coeff m = if m ≤ n then coeff R m φ else 0 := by simp [trunc, coeff_trunc_fun] @[simp] lemma trunc_one : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, simp }, { symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), }, { symmetry, rw mv_polynomial.coeff_one, refine if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, rw [coe_add, coe_add, pi.add_apply, pi.add_apply, nat_add_sub_cancel_left, add_comm], }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, begin rw inv.aux, convert rfl -- unify `decidable` instances end /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : units R) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : units R) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : units R) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal, { rw [finsupp.mem_antidiagonal, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance is_local_ring [local_ring R] : local_ring (mv_power_series σ R) := { is_local := by { intro φ, rcases local_ring.is_local (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit, rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ variables [local_ring R] [local_ring S] instance : local_ring (mv_power_series σ R) := { is_local := local_ring.is_local } end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k} (h : constant_coeff σ k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := ⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv _ h]⟩ protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul] protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ @[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ R) (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ R) : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ R) : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end mv_polynomial /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (power_series A) := by apply_instance instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower instance {A} [semiring A] [comm_semiring R] [algebra R A] : algebra R (power_series A) := by apply_instance end section semiring variables (R) [semiring R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial_same (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := mv_power_series.coeff_monomial_same _ _ @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R 0) = constant_coeff R := by { rw [coeff, finsupp.single_zero], refl } lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := coeff_C n 1 lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (a • φ) = a * coeff R n φ := rfl @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin simp only [coeff, finsupp.single_add], convert φ.coeff_add_mul_monomial (single () n) (single () 1) _, rw mul_one end @[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) : coeff R (n + 1) (X * φ) = coeff R n φ := begin simp only [coeff, finsupp.single_add, add_comm n 1], convert φ.coeff_add_monomial_mul (single () 1) (single () n) _, rw one_mul, end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h /-- Split off the constant coefficient. -/ lemma eq_shift_mul_X_add_const (φ : power_series R) : φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, mul_zero, ring_hom.map_mul], }, { simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end /-- Split off the constant coefficient. -/ lemma eq_X_mul_shift_add_const (φ : power_series R) : φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, zero_mul, ring_hom.map_mul], }, { simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring R] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end open finset nat /-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/ noncomputable def rescale (a : R) : power_series R →+* power_series R := { to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f), map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], }, map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one], split_ifs, { rw [h, pow_zero], }, refl, }, map_add' := by { intros, ext, exact mul_add _ _ _, }, map_mul' := λ f g, by { ext, rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum], apply sum_congr rfl, simp only [coeff_mk, prod.forall, nat.mem_antidiagonal], intros b c H, rw [←H, pow_add, mul_mul_mul_comm] }, } @[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) : coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _ @[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) := begin ext, simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk, power_series.coeff_mk _ _, coeff_C], split_ifs, { simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], }, { rw [zero_pow' n h, zero_mul], }, end lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) := by simp @[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) := by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul, ring_hom.coe_mk], } section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : polynomial R := ∑ m in Ico 0 (n + 1), polynomial.monomial m (coeff R m φ) lemma coeff_trunc (m) (n) (φ : power_series R) : (trunc n φ).coeff m = if m ≤ n then coeff R m φ else 0 := by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff] @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : R) : trunc n (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : units R) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : units R) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : units R) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h /-- Two ways of removing the constant coefficient of a power series are the same. -/ lemma sub_const_eq_shift_mul_X (φ : power_series R) : φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X := sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ) lemma sub_const_eq_X_mul_shift (φ : power_series R) : φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) := sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ) end ring section comm_ring variables {A : Type*} [comm_ring A] @[simp] lemma rescale_neg_one_X : rescale (-1 : A) X = -X := begin ext, simp only [linear_map.map_neg, coeff_rescale, coeff_X], split_ifs with h; simp [h] end /-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/ noncomputable def eval_neg_hom : power_series A →+* power_series A := rescale (-1 : A) @[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X := rescale_neg_one_X end comm_ring section integral_domain variable [integral_domain R] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nontrivial, .. power_series.comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) := begin intros p q h, rw power_series.ext_iff at *, intros n, specialize h n, rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h, apply h.resolve_right, intro h', exact ha (pow_eq_zero h'), end end integral_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl theorem algebra_map_apply {r : R} : algebra_map R (power_series A) r = C A (algebra_map R A r) := mv_power_series.algebra_map_apply instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) := mv_power_series.subalgebra.nontrivial end algebra section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring R] /-- The order of a formal power series `φ` is the greatest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series R) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series R) (h : ∃ n, coeff R n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, dsimp only, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series R) (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series R) (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series R) (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := multiplicity.zero _ /-- The `0` power series is the unique power series with infinite order.-/ @[simp] lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin split, { intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] }, { rintros rfl, exact order_zero } end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply nat_le_order, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, linear_map.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] /-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product with any other power series is `0`. -/ lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) : coeff R n (φ * ψ) = 0 := begin suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0, rw [this, finset.sum_const_zero], rw [coeff_mul], apply finset.sum_congr rfl (λ x hx, _), refine mul_eq_zero_of_right (coeff R x.fst φ) (ψ.coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)), rw finset.nat.mem_antidiagonal at hx, norm_cast, linarith, end lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R} (n : ℕ) (h : ↑n < ψ.order) : coeff R n (φ * (1 - ψ)) = coeff R n φ := by simp [coeff_mul_of_lt_order h, mul_sub] lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι) (φ : power_series R) (f : ι → power_series R) : (∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ := begin apply finset.induction_on s, { simp }, { intros a s ha ih t, simp only [finset.mem_insert, forall_eq_or_imp] at t, rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1], exact ih t.2 }, end end order_basic section order_zero_ne_one variables [comm_semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial R) (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, norm_cast] lemma coeff_coe (φ : polynomial R) (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] } @[simp, norm_cast] lemma coe_zero : ((0 : polynomial R) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : polynomial R) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add (φ ψ : polynomial R) : ((φ + ψ : polynomial R) : power_series R) = φ + ψ := by { ext, simp } @[simp, norm_cast] lemma coe_mul (φ ψ : polynomial R) : ((φ * ψ : polynomial R) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : polynomial R) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_X : ((X : polynomial R) : power_series R) = power_series.X := coe_monomial _ _ /-- The coercion from polynomials to power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_power_series.ring_hom : polynomial R →+* power_series R := { to_fun := (coe : polynomial R → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end polynomial
bdea27a30075eb2f4996ebaa33a1f5a0fa8b4d2f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/affine_space/affine_map.lean
b3e18b6b58f8270cafb56b9473a4b3b37433a6d8
[ "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
22,395
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import algebra.add_torsor import data.set.intervals.unordered_interval import linear_algebra.affine_space.basic import linear_algebra.bilinear_map import linear_algebra.pi import linear_algebra.prod import tactic.abel /-! # Affine maps This file defines affine maps. ## Main definitions * `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`. ## Notations * `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`; * `affine_space V P`: a localized notation for `add_torsor V P` defined in `linear_algebra.affine_space.basic`. ## Implementation notes `out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ open_locale affine /-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] := (to_fun : P1 → P2) (linear : V1 →ₗ[k] V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2 instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2]: has_coe_to_fun (P1 →ᵃ[k] P2) (λ _, P1 → P2) := ⟨affine_map.to_fun⟩ namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : V₁ →ᵃ[k] V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] [add_comm_group V3] [module k V3] [affine_space V3 P3] [add_comm_group V4] [module k V4] [affine_space V4 P4] include V1 V2 /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, have : f = g := funext h, subst g, congr' with v, cases (add_torsor.nonempty : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ lemma coe_fn_injective : @function.injective (P1 →ᵃ[k] P2) (P1 → P2) coe_fn := λ f g H, ext $ congr_fun H protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y := congr_arg _ h protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x := h ▸ rfl variables (k P1) /-- Constant function as an `affine_map`. -/ def const (p : P2) : P1 →ᵃ[k] P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl variables {k P1} lemma linear_eq_zero_iff_exists_const (f : P1 →ᵃ[k] P2) : f.linear = 0 ↔ ∃ q, f = const k P1 q := begin refine ⟨λ h, _, λ h, _⟩, { use f (classical.arbitrary P1), ext, rw [coe_const, function.const_apply, ← @vsub_eq_zero_iff_eq V2, ← f.linear_map_vsub, h, linear_map.zero_apply], }, { rcases h with ⟨q, rfl⟩, exact const_linear k P1 q, }, end instance nonempty : nonempty (P1 →ᵃ[k] P2) := (add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : P1 →ᵃ[k] P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩, add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩, sub := λ f g, ⟨f - g, f.linear - g.linear, λ p v, by simp [sub_add_comm]⟩, sub_eq_add_neg := λ f g, ext $ λ p, sub_eq_add_neg _ _, neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩, add_assoc := λ f₁ f₂ f₃, ext $ λ p, add_assoc _ _ _, zero_add := λ f, ext $ λ p, zero_add (f p), add_zero := λ f, ext $ λ p, add_zero (f p), add_comm := λ f g, ext $ λ p, add_comm (f p) (g p), add_left_neg := λ f, ext $ λ p, add_left_neg (f p) } @[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl @[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g := rfl @[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl @[simp] lemma sub_linear (f g : P1 →ᵃ[k] V2) : (f - g).linear = f.linear - g.linear := rfl @[simp] lemma neg_linear (f : P1 →ᵃ[k] V2) : (-f).linear = -f.linear := rfl /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps from `P1` to the vector space `V2` corresponding to `P2`. -/ instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [vadd_vadd, add_right_comm]⟩, zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p), add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) } @[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) : (f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p := rfl /-- `prod.fst` as an `affine_map`. -/ def fst : (P1 × P2) →ᵃ[k] P1 := { to_fun := prod.fst, linear := linear_map.fst k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl @[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl /-- `prod.snd` as an `affine_map`. -/ def snd : (P1 × P2) →ᵃ[k] P2 := { to_fun := prod.snd, linear := linear_map.snd k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl @[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl variables (k P1) omit V2 /-- Identity map as an affine map. -/ def id : P1 →ᵃ[k] P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl @[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k P1 p = p := rfl variables {k P1} instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩ include V2 V3 /-- Composition of affine maps. -/ def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) : f.comp g p = f (g p) := rfl omit V3 @[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl include V3 V4 lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl omit V2 V3 V4 instance : monoid (P1 →ᵃ[k] P1) := { one := id k P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl /-- `affine_map.linear` on endomorphisms is a `monoid_hom`. -/ @[simps] def linear_hom : (P1 →ᵃ[k] P1) →* (V1 →ₗ[k] V1) := { to_fun := linear, map_one' := rfl, map_mul' := λ _ _, rfl } include V2 @[simp] lemma injective_iff_linear_injective (f : P1 →ᵃ[k] P2) : function.injective f.linear ↔ function.injective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_injective, equiv.injective_comp], end @[simp] lemma surjective_iff_linear_surjective (f : P1 →ᵃ[k] P2) : function.surjective f.linear ↔ function.surjective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_surjective, equiv.surjective_comp], end lemma image_vsub_image {s t : set P1} (f : P1 →ᵃ[k] P2) : (f '' s) -ᵥ (f '' t) = f.linear '' (s -ᵥ t) := begin ext v, simp only [set.mem_vsub, set.mem_image, exists_exists_and_eq_and, exists_and_distrib_left, ← f.linear_map_vsub], split, { rintros ⟨x, hx, y, hy, hv⟩, exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩, }, { rintros ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩, exact ⟨x, hx, y, hy, rfl⟩, }, end omit V2 /-! ### Definition of `affine_map.line_map` and lemmas about it -/ /-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/ def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 := ((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀ lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ := by simp [line_map_apply_module', smul_sub, sub_smul]; abel omit V1 lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a := rfl lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b := line_map_apply_module a b c include V1 lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) : line_map p (v +ᵥ p) c = c • v +ᵥ p := by rw [line_map_apply, vadd_vsub] @[simp] lemma line_map_linear (p₀ p₁ : P1) : (line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) := add_zero _ lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply] @[simp] lemma line_map_same (p : P1) : line_map p p = const k k p := ext $ line_map_same_apply p @[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ := by simp [line_map_apply] @[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ := by simp [line_map_apply] include V2 @[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) : f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c := by simp [line_map_apply] @[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) : f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) := ext $ f.apply_line_map p₀ p₁ @[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c := fst.apply_line_map p₀ p₁ c @[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c := snd.apply_line_map p₀ p₁ c omit V2 lemma line_map_symm (p₀ p₁ : P1) : line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) := by { rw [comp_line_map], simp } lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c := by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] } @[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) := vadd_vsub _ _ @[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) : p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) := by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev] @[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) := by rw [← line_map_apply_one_sub, line_map_vsub_left] @[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) : p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) := by rw [← line_map_apply_one_sub, left_vsub_line_map] lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) : line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c := ((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) : line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c := -- Why Lean fails to find this instance without a hint? by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact ((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) := begin ext x, calc f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd] ... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp end /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) := by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add] omit V1 lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k) (a b : k) : f '' set.interval a b = set.interval (f a) (f b) := begin have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0), { ext x, change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0, rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd], simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] }, rw [this, set.image_comp], simp only [set.image_add_const_interval, set.image_mul_const_interval] end section variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)] [Π i, module k (V i)] [Π i, add_torsor (V i) (P i)] include V /-- Evaluation at a point as an affine map. -/ def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i := { to_fun := λ f, f i, linear := @linear_map.proj k ι _ V _ _ i, map_vadd' := λ p v, rfl } @[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl @[simp] lemma proj_linear (i : ι) : (@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) : line_map f g c i = line_map (f i) (g i) c := (proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c end end affine_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} [comm_ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] include V1 /-- If `k` is a commutative ring, then the set of affine maps with codomain in a `k`-module is a `k`-module. -/ instance : module k (P1 →ᵃ[k] V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _, smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _, add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _ } @[simp] lemma coe_smul (c : k) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl @[simp] lemma smul_linear (t : k) (f : P1 →ᵃ[k] V2) : (t • f).linear = t • f.linear := rfl /-- The space of affine maps between two modules is linearly equivalent to the product of the domain with the space of linear maps, by taking the value of the affine map at `(0 : V1)` and the linear part. -/ @[simps] def to_const_prod_linear_map : (V1 →ᵃ[k] V2) ≃ₗ[k] V2 × (V1 →ₗ[k] V2) := { to_fun := λ f, ⟨f 0, f.linear⟩, inv_fun := λ p, p.2.to_affine_map + const k V1 p.1, left_inv := λ f, by { ext, rw f.decomp, simp, }, right_inv := by { rintros ⟨v, f⟩, ext; simp, }, map_add' := by simp, map_smul' := by simp, } /-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 := r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c lemma homothety_def (c : P1) (r : k) : homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl @[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_apply_same (c : P1) (r : k) : homothety c r c = c := line_map_same_apply c r lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) := by { ext p, simp [homothety_apply, mul_smul] } @[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by simp only [homothety_def, add_smul, vadd_vadd] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 := ⟨homothety c, homothety_one c, homothety_mul c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) := ⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c), function.swap (homothety_add c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine c : k →ᵃ[k] _) = homothety c := rfl end affine_map
bf4d6f92a2394cce5d234608243b8bd242aa1d67
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/basic.lean
79d858fd130905abce34be93f6fc5fc32fd70ce9
[ "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
56,679
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, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import algebra.support /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ noncomputable theory open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open.inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma topological_space_eq_iff {t t' : topological_space α} : t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s := ⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩ lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open.union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open.inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open.inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open.and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open.inter /-- A set is closed if its complement is open -/ class is_closed (s : set α) : Prop := (is_open_compl : is_open sᶜ) @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := ⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ } @[simp] lemma is_closed_univ : is_closed (univ : set α) := by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty } lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open.inter h₁ h₂ } lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) : is_closed (⋂ i ∈ s, f i) := is_closed_Inter $ λ i, is_closed_Inter $ h i @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ := is_closed_compl_iff.2 hs lemma is_open.sdiff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open.inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed.inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ } lemma is_closed.sdiff {s t : set α} (h₁ : is_closed s) (h₂ : is_open t) : is_closed (s \ t) := is_closed.inter h₁ (is_closed_compl_iff.mpr h₂) lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed.union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed.union (is_closed_compl_iff.mpr hp) hq lemma is_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open.inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open.sdiff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ @[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma diff_subset_closure_iff {s t : set α} : s \ t ⊆ closure t ↔ s ⊆ closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ @[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty := by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff] alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed.union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin rw [interior, closure, compl_sUnion, compl_image_set_of], simp only [compl_subset_compl, is_open_compl_iff], end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _ /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier] @[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ := by rw [hs.frontier_eq, inter_diff_self] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm lemma is_open.inter_frontier_eq_empty_of_disjoint {s t : set α} (ht : is_open t) (hd : disjoint s t) : t ∩ frontier s = ∅ := begin rw [inter_comm, ← subset_compl_iff_disjoint], exact subset.trans frontier_subset_closure (closure_minimal (λ _, disjoint_left.1 hd) (is_closed_compl_iff.2 ht)) end /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ @[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s localized "notation `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) := begin rw nhds_def, exact has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ end /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_mem_nhds h lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := is_open.mem_nhds hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, split, { rintros ⟨s_in, s_op⟩, exact ⟨mem_of_mem_nhds s_in, s_op⟩ }, { rintros ⟨a_in, s_op⟩, exact ⟨is_open.mem_nhds s_op a_in, s_op⟩ }, end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`: it contains an open set containing `s`. -/ lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := begin have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx), choose! Z hZ hZ' using this, refine ⟨⋃ x ∈ s, Z x, _, _, bUnion_subset hZ'⟩, { intros x hx, simp only [mem_Union], exact ⟨x, hx, (hZ x hx).1⟩ }, { apply is_open_Union, intros x, by_cases hx : x ∈ s ; simp [hx], exact (hZ x hx).2 } end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s: it contains an open set containing `s`. -/ lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := exists_open_set_nhds (by simpa using h) /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha lemma tendsto_at_top_of_eventually_const {ι : Type*} [semilattice_sup ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : tendsto u at_top (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_top.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma tendsto_at_bot_of_eventually_const {ι : Type*} [semilattice_inf ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : tendsto u at_bot (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_bot.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure_sets.2 $ mem_of_mem_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α} {pF : ιF → Prop} {sF : ιF → set α} {F : filter α} (ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) : cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty := ha.inf_basis_ne_bot_iff hF lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩ lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] @[simp] lemma interior_mem_nhds {s : set α} {a : α} : interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a := ⟨λ h, mem_sets_of_superset h interior_subset, λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩ lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_cluster_pt.trans ne_bot_iff lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis' {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty := mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $ by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans $ by simp only [set.nonempty, mem_inter_eq, exists_prop, and_comm] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := begin rintro a ⟨hs, ht⟩, have : s ∈ 𝓝 a := is_open.mem_nhds h hs, rw mem_closure_iff_nhds_ne_bot at ht ⊢, rwa [← inf_principal, ← inf_assoc, inf_eq_left.2 (le_principal_iff.2 this)], end lemma closure_inter_open' {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) := by simpa only [inter_comm] using closure_inter_open h /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) : (s ∩ t).nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩ lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite.point_finite {f : β → set α} (hf : locally_finite f) (x : α) : finite {b | x ∈ f b} := let ⟨t, hxt, ht⟩ := hf x in ht.subset $ λ b hb, ⟨x, hb, mem_of_mem_nhds hxt⟩ lemma locally_finite_of_fintype [fintype β] (f : β → set α) : locally_finite f := assume x, ⟨univ, univ_mem_sets, finite.of_fintype _⟩ lemma locally_finite.subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma locally_finite.comp_injective {ι} {f : β → set α} {g : ι → β} (hf : locally_finite f) (hg : function.injective g) : locally_finite (f ∘ g) := λ x, let ⟨t, htx, htf⟩ := hf x in ⟨t, htx, htf.preimage (hg.inj_on _)⟩ lemma locally_finite.closure {f : β → set α} (hf : locally_finite f) : locally_finite (λ i, closure (f i)) := begin intro x, rcases hf x with ⟨s, hsx, hsf⟩, refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset $ λ i hi, _⟩, exact (hi.mono (closure_inter_open' is_open_interior)).of_closure.mono (inter_subset_inter_right _ interior_subset) end lemma locally_finite.is_closed_Union {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_compl_iff.1 $ is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ (f i)ᶜ, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have ∀i, (f i)ᶜ ∈ (𝓝 a), by simp only [mem_nhds_iff]; exact assume i, ⟨(f i)ᶜ, subset.refl _, (h₂ i).is_open_compl, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | (f i ∩ t).nonempty })⟩ := h₁ a in calc 𝓝 a ≤ 𝓟 (t ∩ (⋂ i∈{i | (f i ∩ t).nonempty }, (f i)ᶜ)) : by simp * ... ≤ 𝓟 (⋃i, f i)ᶜ : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, exists_imp_distrib, ne_empty_iff_nonempty, set.nonempty], exact assume x xt ht i xfi, ht i x xfi xt xfi end lemma locally_finite.closure_Union {f : β → set α} (h : locally_finite f) : closure (⋃ i, f i) = ⋃ i, closure (f i) := subset.antisymm (closure_minimal (Union_subset_Union $ λ _, subset_closure) $ h.closure.is_closed_Union $ λ _, is_closed_closure) (Union_subset $ λ i, closure_mono $ subset_Union _ _) end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : α → β) : Prop := (is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s)) lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩ lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) : continuous_at f x ↔ continuous_at g x := by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds] lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) : continuous_at g x := (continuous_at_congr h).1 hf lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} : f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) := by rw [← mem_compl_eq, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la) {f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩ lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : α → α) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, is_open.mem_nhds hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := tendsto_const_nhds lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, continuous_at_const lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔ ∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal_sets], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_sets_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) : closure s ⊆ f ⁻¹' (closure (f '' s)) := by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h } lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := set.maps_to.closure ht hf ha /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ end dense_range end continuous
fc36304dde8fb4060515e34d00729c07b76c75be
297c4ceafbbaed2a59b6215504d09e6bf201a2ee
/finset/basic.lean
e5907d41dec848c9ab71ba9dd9fbd09a692433a5
[]
no_license
minchaowu/Kruskal.lean3
559c91b82033ce44ea61593adcec9cfff725c88d
a14516f47b21e636e9df914fc6ebe64cbe5cd38d
refs/heads/master
1,611,010,001,429
1,497,935,421,000
1,497,935,421,000
82,000,982
1
0
null
null
null
null
UTF-8
Lean
false
false
27,185
lean
import ..library_dev.data.list.set ..library_dev.data.list.perm .quot .misc open list subtype nat definition nodup_list (A : Type) := {l : list A // nodup l} variable {A : Type} definition to_nodup_list_of_nodup {l : list A} (n : nodup l) : nodup_list A := ⟨l,n⟩ definition to_nodup_list [decidable_eq A] (l : list A) : nodup_list A := @to_nodup_list_of_nodup A (erase_dup l) (nodup_erase_dup l) private definition eqv (l₁ l₂ : nodup_list A) := perm (l₁.1) (l₂.1) local infix ~ := eqv private definition eqv.refl (l : nodup_list A) : l ~ l := perm.refl _ private definition eqv.symm {l₁ l₂ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₁ := perm.symm private definition eqv.trans {l₁ l₂ l₃ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := perm.trans attribute [instance] definition finset.nodup_list_setoid (A : Type) : setoid (nodup_list A) := setoid.mk (@eqv A) (mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)) definition finset (A : Type) : Type := quotient (finset.nodup_list_setoid A) namespace finset -- give finset notation higher priority than set notation, so that it is tried first -- protected definition prio : num := num.succ std.priority.default definition to_finset_of_nodup (l : list A) (n : nodup l) : finset A := ⟦to_nodup_list_of_nodup n⟧ definition to_finset [decidable_eq A] (l : list A) : finset A := ⟦to_nodup_list l⟧ -- lemma to_finset_eq_of_nodup [decidable_eq A] {l : list A} (n : nodup l) : -- to_finset_of_nodup l n = to_finset l := -- have P : to_nodup_list_of_nodup n = to_nodup_list l, from -- begin -- rewrite [↑to_nodup_list, ↑to_nodup_list_of_nodup], -- congruence, -- rewrite [erase_dup_eq_of_nodup n] -- end, -- quot.sound (eq.subst P !setoid.refl) attribute [instance] definition has_decidable_eq [decidable_eq A] : decidable_eq (finset A) := λ s₁ s₂, quot.rec_on_subsingleton₂ s₁ s₂ (λ l₁ l₂, match perm.decidable_perm (l₁.1) (l₂.1) with | decidable.is_true e := decidable.is_true (quot.sound e) | decidable.is_false n := decidable.is_false (λ e : ⟦l₁⟧ = ⟦l₂⟧, absurd (quot.exact' e) n) end) definition mem (a : A) (s : finset A) : Prop := quot.lift_on s (λ l, a ∈ l.1) (λ l₁ l₂ (e : l₁ ~ l₂), propext (iff.intro (λ ainl₁, perm.mem_perm e ainl₁) (λ ainl₂, perm.mem_perm (perm.symm e) ainl₂))) infix ∈ := mem notation a ∉ b := ¬ mem a b theorem mem_of_mem_list {a : A} {l : nodup_list A} : a ∈ l.1 → a ∈ ⟦l⟧ := λ ainl, ainl theorem mem_list_of_mem {a : A} {l : nodup_list A} : a ∈ ⟦l⟧ → a ∈ l.1 := λ ainl, ainl attribute [instance] definition decidable_mem [h : decidable_eq A] : ∀ (a : A) (s : finset A), decidable (a ∈ s) := λ a s, quot.rec_on_subsingleton s (λ l, match list.decidable_mem a l.1 with | decidable.is_true p := decidable.is_true (mem_of_mem_list p) | decidable.is_false n := decidable.is_false (λ p, absurd (mem_list_of_mem p) n) end) theorem mem_to_finset [decidable_eq A] {a : A} {l : list A} : a ∈ l → a ∈ to_finset l := λ ainl, mem_erase_dup ainl theorem mem_to_finset_of_nodup {a : A} {l : list A} (n : nodup l) : a ∈ l → a ∈ to_finset_of_nodup l n := λ ainl, ainl /- extensionality -/ theorem ext {s₁ s₂ : finset A} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ e, quot.sound (perm.perm_ext (l₁.2) (l₂.2) e)) /- empty -/ definition empty : finset A := to_finset_of_nodup [] nodup_nil -- notation [priority finset.prio] `∅` := empty _ attribute [simp] theorem not_mem_empty (a : A) : a ∉ empty := λ aine, aine attribute [simp] theorem mem_empty_iff (x : A) : mem x empty ↔ false := iff_false_intro (not_mem_empty _) theorem mem_empty_eq (x : A) : mem x empty = false := propext (mem_empty_iff _) theorem eq_empty_of_forall_not_mem {s : finset A} (H : ∀x : A, ¬ mem x s) : s = empty := ext (λ x, iff_false_intro (H x)) -- /- universe -/ -- definition univ [h : fintype A] : finset A := -- to_finset_of_nodup (@fintype.elems A h) (@fintype.unique A h) -- theorem mem_univ [fintype A] (x : A) : x ∈ univ := -- fintype.complete x -- theorem mem_univ_eq [fintype A] (x : A) : x ∈ univ = true := propext (iff_true_intro !mem_univ) /- card -/ definition card (s : finset A) : nat := quot.lift_on s (λ l, length l.1) (λ l₁ l₂ p, perm.length_eq_length_of_perm p) theorem card_empty : card (@empty A) = 0 := rfl lemma ne_empty_of_card_eq_succ {s : finset A} {n : nat} : card s = succ n → s ≠ empty := begin intros, intro eq, rw [eq] at a, contradiction end /- insert -/ section insert variable [h : decidable_eq A] include h definition insert (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (insert a l.1) (nodup_insert l.2)) -- implicit 'a' (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (perm.perm_insert a p)) -- set builder notation -- notation [priority finset.prio] `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem mem_insert (a : A) (s : finset A) : a ∈ insert a s := quot.induction_on s (λ l : nodup_list A, mem_to_finset_of_nodup _ (list.mem_insert_self _ _)) theorem mem_insert_of_mem {a : A} {s : finset A} (b : A) : a ∈ s → a ∈ insert b s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), mem_to_finset_of_nodup _ (list.mem_insert_of_mem ainl)) theorem eq_or_mem_of_mem_insert {x a : A} {s : finset A} : x ∈ insert a s → x = a ∨ x ∈ s := quot.induction_on s (λ l : nodup_list A, λ H, list.eq_or_mem_of_mem_insert H) theorem mem_of_mem_insert_of_ne {x a : A} {s : finset A} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_iff (x a : A) (s : finset A) : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.intro eq_or_mem_of_mem_insert (λ h, or.elim h (λ l, by rw l; apply mem_insert) (λ r, mem_insert_of_mem _ r)) theorem mem_insert_eq (x a : A) (s : finset A) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (mem_insert_iff _ _ _) theorem mem_singleton_iff (x a : A) : x ∈ insert a empty ↔ (x = a) := by rewrite [mem_insert_eq, mem_empty_eq, or_false] theorem mem_singleton (a : A) : a ∈ insert a empty := mem_insert a empty theorem mem_singleton_of_eq {x a : A} (H : x = a) : x ∈ insert a empty := by rewrite H; apply mem_insert theorem eq_of_mem_singleton {x a : A} (H : x ∈ insert a empty) : x = a := iff.mp (mem_singleton_iff _ _) H theorem eq_of_singleton_eq {a b : A} (H : insert a empty = insert b empty) : a = b := have a ∈ insert b empty, by rewrite -H; apply mem_singleton, eq_of_mem_singleton this -- #check @eq.substr theorem insert_eq_of_mem {a : A} {s : finset A} (H : a ∈ s) : insert a s = s := ext (λ x, iff.intro (λ l, or.elim (eq_or_mem_of_mem_insert l) (λll, by rw ll;exact H) (λ rr, rr)) (λ r, mem_insert_of_mem _ r)) theorem singleton_ne_empty (a : A) : insert a empty ≠ empty := begin intro H, apply not_mem_empty a, rewrite -H, apply mem_insert end -- useful in proofs by induction theorem forall_of_forall_insert {P : A → Prop} {a : A} {s : finset A} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x ((mem_insert_of_mem _)xs) theorem insert.comm (x y : A) (s : finset A) : insert x (insert y s) = insert y (insert x s) := ext (take a, begin repeat {rw mem_insert_eq}, rw [propext or.left_comm] end) theorem card_insert_of_mem {a : A} {s : finset A} : a ∈ s → card (insert a s) = card s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), list.length_insert_of_mem ainl) theorem card_insert_of_not_mem {a : A} {s : finset A} : a ∉ s → card (insert a s) = card s + 1 := quot.induction_on s (λ (l : nodup_list A) (nainl : a ∉ ⟦l⟧), list.length_insert_of_not_mem nainl) theorem card_insert_le (a : A) (s : finset A) : card (insert a s) ≤ card s + 1 := if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ else by rewrite [card_insert_of_not_mem H] attribute [recursor 6] protected theorem induction {P : finset A → Prop} (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀{s : finset A}, a ∉ s → P s → P (insert a s)) : ∀s, P s := take s, quot.induction_on s (take u, subtype.rec_on u (take l, list.rec_on l (assume nodup_l, H1) (take a l', assume IH nodup_al', have aux₁: a ∉ l', from not_mem_of_nodup_cons nodup_al', have ndl' : nodup l', from nodup_of_nodup_cons nodup_al', have p1 : P (quot.mk _ (subtype.mk l' ndl')), from IH ndl', have ¬ mem a (quot.mk _ (subtype.mk l' ndl')), from aux₁, have P (insert a (quot.mk _ (subtype.mk l' _))), from H2 this p1, have hperm : perm (list.insert a l') (a :: l'), from perm.perm_insert_cons_of_not_mem aux₁, begin apply @eq.subst _ P _ _ _ this, apply quot.sound, exact hperm end))) protected theorem induction_on {P : finset A → Prop} (s : finset A) (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀{s : finset A}, a ∉ s → P s → P (insert a s)) : P s := finset.induction H1 H2 s theorem exists_mem_of_ne_empty {s : finset A} : s ≠ empty → ∃ a : A, a ∈ s := @finset.induction_on _ _ (λ x, x ≠ empty → ∃ a : A, mem a x) s (λ h, absurd rfl h) (by intros a s nin ih h; existsi a; apply mem_insert) theorem eq_empty_of_card_eq_zero {s : finset A} : card s = 0 → s = empty := @finset.induction_on _ _ (λ x, card x = 0 → x = empty) s (λ h, rfl) (by intros a s' H1 Ih H; rw (card_insert_of_not_mem H1) at H; contradiction) end insert /- erase -/ section erase variable [h : decidable_eq A] include h definition erase (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (erase' a l.1) (nodup_erase_of_nodup a l.2)) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (perm.erase_perm_erase_of_perm a p)) theorem not_mem_erase (a : A) (s : finset A) : a ∉ erase a s := quot.induction_on s (λ l, list.mem_erase_of_nodup _ l.2) theorem card_erase_of_mem {a : A} {s : finset A} : a ∈ s → card (erase a s) = pred (card s) := quot.induction_on s (λ l ainl, list.length_erase_of_mem ainl) theorem card_erase_of_not_mem {a : A} {s : finset A} : a ∉ s → card (erase a s) = card s := quot.induction_on s (λ l nainl, list.length_erase_of_not_mem nainl) theorem erase_empty (a : A) : erase a empty = empty := rfl theorem ne_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ≠ a := by intros h beqa; subst b; exact absurd h (not_mem_erase _ _) theorem mem_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ∈ s := quot.induction_on s (λ l bin, mem_of_mem_erase bin) theorem mem_erase_of_ne_of_mem {a b : A} {s : finset A} : a ≠ b → a ∈ s → a ∈ erase b s := quot.induction_on s (λ l n ain, list.mem_erase_of_ne_of_mem n ain) theorem mem_erase_iff (a b : A) (s : finset A) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : A) (s : finset A) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext (mem_erase_iff _ _ _) open decidable theorem erase_insert {a : A} {s : finset A} : a ∉ s → erase a (insert a s) = s := λ anins, finset.ext (λ b, by_cases (λ beqa : b = a, iff.intro (λ bin, by subst b; exact absurd bin (not_mem_erase _ _)) (λ bin, by subst b; contradiction)) (λ bnea : b ≠ a, iff.intro (λ bin, have b ∈ insert a s, from mem_of_mem_erase bin, mem_of_mem_insert_of_ne this bnea) (λ bin, have b ∈ insert a s, from mem_insert_of_mem _ bin, mem_erase_of_ne_of_mem bnea this))) theorem insert_erase {a : A} {s : finset A} : a ∈ s → insert a (erase a s) = s := λ ains, finset.ext (λ b, by_cases (suppose b = a, iff.intro (λ bin, by subst b; assumption) (λ bin, by subst b; apply mem_insert)) (assume neq, iff.intro (λ bin, mem_of_mem_erase (mem_of_mem_insert_of_ne bin neq)) (λ bin, mem_insert_of_mem _ (mem_erase_of_ne_of_mem neq bin)))) end erase section union variable [h : decidable_eq A] include h definition union (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.union l₁.1 l₂.1) (nodup_union_of_nodup_of_nodup l₁.2 l₂.2)) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm.perm_union p₁ p₂)) infix ∪ := union theorem mem_union_left {a : A} {s₁ : finset A} (s₂ : finset A) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁, list.mem_union_left ainl₁ _) theorem mem_union_l {a : A} {s₁ : finset A} {s₂ : finset A} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : A} {s₂ : finset A} (s₁ : finset A) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₂, list.mem_union_right _ ainl₂) theorem mem_union_r {a : A} {s₂ : finset A} {s₁ : finset A} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_or_mem_of_mem_union ainl₁l₂) theorem mem_union_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext (mem_union_iff _ _ _) theorem union_comm (s₁ s₂ : finset A) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext (λ a, by repeat {rw mem_union_eq}; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext (λ a, by repeat {rw mem_union_eq}; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := left_comm _ union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := right_comm _ union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : finset A) : s ∪ s = s := ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : finset A) : s ∪ empty = s := ext (λ a, iff.intro (suppose a ∈ s ∪ empty, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i (not_mem_empty _))) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : finset A) : empty ∪ s = s := calc empty ∪ s = s ∪ empty : union_comm _ _ ... = s : union_empty _ theorem insert_eq (a : A) (s : finset A) : insert a s = (insert a empty) ∪ s := ext (take x, by rewrite [mem_insert_iff, mem_union_iff, mem_singleton_iff]) theorem insert_union (a : A) (s t : finset A) : insert a (s ∪ t) = insert a s ∪ t := by rewrite [insert_eq, insert_eq a s, union_assoc] end union /- inter -/ section inter variable [h : decidable_eq A] include h definition inter (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.inter l₁.1 l₂.1) (nodup_inter_of_nodup _ l₁.2)) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm.perm_inter p₁ p₂)) infix ∩ := inter theorem mem_of_mem_inter_left {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_left ainl₁l₂) theorem mem_of_mem_inter_right {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_right ainl₁l₂) theorem mem_inter {a : A} {s₁ s₂ : finset A} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁ ainl₂, list.mem_inter_of_mem_of_mem ainl₁ ainl₂) theorem mem_inter_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext (mem_inter_iff _ _ _) theorem inter_comm (s₁ s₂ : finset A) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext (λ a, by repeat {rw mem_inter_eq}; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext (λ a, by repeat {rw mem_inter_eq}; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := left_comm _ inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := right_comm _ inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : finset A) : s ∩ s = s := ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : finset A) : s ∩ empty = empty := ext (λ a, iff.intro (suppose a ∈ s ∩ empty, absurd (mem_of_mem_inter_right this) (not_mem_empty _)) (assume h, absurd h (not_mem_empty _))) theorem empty_inter (s : finset A) : empty ∩ s = empty := calc empty ∩ s = s ∩ empty : inter_comm _ _ ... = empty : inter_empty _ theorem singleton_inter_of_mem {a : A} {s : finset A} (H : a ∈ s) : insert a empty ∩ s = insert a empty := ext (take x, begin rewrite [mem_inter_eq, mem_singleton_iff], exact iff.intro (suppose x = a ∧ x ∈ s, and.left this) (suppose x = a, and.intro this (eq.subst (eq.symm this) H)) end) theorem singleton_inter_of_not_mem {a : A} {s : finset A} (H : a ∉ s) : insert a empty ∩ s = empty := ext (take x, begin rewrite [mem_inter_eq, mem_singleton_iff, mem_empty_eq], exact iff.intro (suppose x = a ∧ x ∈ s, H (eq.subst (and.left this) (and.right this))) (false.elim) end) end inter /- distributivity laws -/ section inter variable [h : decidable_eq A] include h theorem inter_distrib_left (s t u : finset A) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (λ x, by rw [mem_inter_eq];repeat {rw mem_union_eq};repeat {rw mem_inter_eq}; super) theorem inter_distrib_right (s t u : finset A) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, by rw [mem_inter_eq]; repeat {rw mem_union_eq}; repeat {rw mem_inter_eq}; super) theorem union_distrib_left (s t u : finset A) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, by rw [mem_union_eq]; repeat {rw mem_inter_eq}; repeat {rw mem_union_eq}; super) theorem union_distrib_right (s t u : finset A) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, by rw [mem_union_eq]; repeat {rw mem_inter_eq}; repeat {rw mem_union_eq}; super) end inter /- subset -/ -- definition subset (s₁ s₂ : finset A) : Prop := -- quot.lift_on₂ s₁ s₂ -- (λ l₁ l₂, sublist l₁.1 l₂.1) -- (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro -- (λ s₁ a i, perm.mem_perm p₂ (s₁ a (perm.mem_perm (perm.symm p₁) i))) -- (λ s₂ a i, perm.mem_perm (perm.symm p₂) (s₂ a (perm.mem_perm p₁ i))))) definition sublist' {T : Type} (l₁ l₂ : list T) := ∀ ⦃a : T⦄, a ∈ l₁ → a ∈ l₂ definition subset (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, sublist' l₁.1 l₂.1) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ s₁ a i, perm.mem_perm p₂ (s₁ (perm.mem_perm (perm.symm p₁) i))) (λ s₂ a i, perm.mem_perm (perm.symm p₂) (s₂ (perm.mem_perm p₁ i))))) infix ⊆ := subset theorem empty_subset (s : finset A) : empty ⊆ s := quot.induction_on s (λ l, list.nil_subset l.1) -- theorem subset_univ [h : fintype A] (s : finset A) : s ⊆ univ := -- quot.induction_on s (λ l a i, fintype.complete a) theorem subset.refl (s : finset A) : s ⊆ s := quot.induction_on s (λ l, list.subset.refl l.1) theorem subset.trans {s₁ s₂ s₃ : finset A} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := quot.induction_on₃ s₁ s₂ s₃ (λ l₁ l₂ l₃ h₁ h₂, list.subset.trans h₁ h₂) theorem mem_of_subset_of_mem {s₁ s₂ : finset A} {a : A} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h₁ h₂, h₁ h₂) theorem subset.antisymm {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext (take x, iff.intro (assume H, mem_of_subset_of_mem H₁ H) (assume H, mem_of_subset_of_mem H₂ H)) -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : finset A} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ H, H) theorem subset_insert [h : decidable_eq A] (s : finset A) (a : A) : s ⊆ insert a s := subset_of_forall (take x, suppose x ∈ s, mem_insert_of_mem _ this) theorem eq_empty_of_subset_empty {x : finset A} (H : x ⊆ empty) : x = empty := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : finset A) : x ⊆ empty ↔ x = empty := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl empty) section variable [decA : decidable_eq A] include decA theorem erase_subset_erase (a : A) {s t : finset A} (H : s ⊆ t) : erase a s ⊆ erase a t := begin apply subset_of_forall, intro x, repeat {rw mem_erase_eq}, intro H', show x ∈ t ∧ x ≠ a, from and.intro (mem_of_subset_of_mem H (and.left H')) (and.right H') end theorem erase_subset (a : A) (s : finset A) : erase a s ⊆ s := begin apply subset_of_forall, intro x, rewrite mem_erase_eq, intro H, apply and.left H end theorem erase_eq_of_not_mem {a : A} {s : finset A} (anins : a ∉ s) : erase a s = s := eq_of_subset_of_subset (erase_subset _ _) (subset_of_forall (take x, assume xs : x ∈ s, have x ≠ a, from assume H', anins (eq.subst H' xs), mem_erase_of_ne_of_mem this xs)) theorem erase_insert_subset (a : A) (s : finset A) : erase a (insert a s) ⊆ s := decidable.by_cases (assume ains : a ∈ s, by rewrite [insert_eq_of_mem ains]; apply erase_subset) (assume nains : a ∉ s, by rewrite [erase_insert nains]; apply subset.refl) theorem erase_subset_of_subset_insert {a : A} {s t : finset A} (H : s ⊆ insert a t) : erase a s ⊆ t := subset.trans (erase_subset_erase _ H) (erase_insert_subset _ _) theorem insert_erase_subset (a : A) (s : finset A) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, by rewrite[erase_eq_of_not_mem nains]; apply subset_insert) theorem insert_subset_insert (a : A) {s t : finset A} (H : s ⊆ t) : insert a s ⊆ insert a t := begin apply subset_of_forall, intro x, repeat {rw mem_insert_eq}, intro H', cases H' with xeqa xins, exact (or.inl xeqa), exact (or.inr (mem_of_subset_of_mem H xins)) end theorem subset_insert_of_erase_subset {s t : finset A} {a : A} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (insert_subset_insert _ H) theorem subset_insert_iff (s t : finset A) (a : A) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro erase_subset_of_subset_insert subset_insert_of_erase_subset end /- upto -/ section upto definition upto (n : nat) : finset nat := to_finset_of_nodup (list.upto n) (nodup_upto n) theorem card_upto : ∀ n, card (upto n) = n := list.length_upto theorem lt_of_mem_upto {n a : nat} : a ∈ upto n → a < n := @list.lt_of_mem_upto n a theorem mem_upto_succ_of_mem_upto {n a : nat} : a ∈ upto n → a ∈ upto (succ n) := list.mem_upto_succ_of_mem_upto theorem mem_upto_of_lt {n a : nat} : a < n → a ∈ upto n := @list.mem_upto_of_lt n a theorem mem_upto_iff (a n : nat) : a ∈ upto n ↔ a < n := iff.intro lt_of_mem_upto mem_upto_of_lt theorem mem_upto_eq (a n : nat) : a ∈ upto n = (a < n) := propext (mem_upto_iff _ _) end upto theorem upto_zero : upto 0 = empty := rfl theorem upto_succ (n : ℕ) : upto (succ n) = upto n ∪ (insert n empty) := begin apply ext, intro x, rw [mem_union_iff], repeat {rw mem_upto_iff}, simp [mem_singleton_iff, nat.le_iff_lt_or_eq, lt_succ_iff_le] end /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff {A : Type} (P : A → Prop) : (∃ x, mem x empty ∧ P x) ↔ false := iff.intro (assume H, let ⟨x,H1⟩ := H in not_mem_empty _ (H1^.left)) (assume H, false.elim H) theorem exists_mem_empty_eq {A : Type} (P : A → Prop) : (∃ x, mem x empty ∧ P x) = false := propext (exists_mem_empty_iff _) theorem exists_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) ↔ P a ∨ (∃ x, x ∈ s ∧ P x) := iff.intro (assume H, let ⟨x,H1,H2⟩ := H in or.elim (eq_or_mem_of_mem_insert H1) (suppose x = a, or.inl (eq.subst this H2)) (suppose x ∈ s, or.inr (exists.intro x (and.intro this H2)))) (assume H, or.elim H (suppose P a, exists.intro a (and.intro (mem_insert _ _) this)) (suppose ∃ x, x ∈ s ∧ P x, let ⟨x,H2,H3⟩ := this in exists.intro x (and.intro (mem_insert_of_mem _ H2) H3))) theorem exists_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) = (P a ∨ (∃ x, x ∈ s ∧ P x)) := propext (exists_mem_insert_iff _ _ _) theorem forall_mem_empty_iff {A : Type} (P : A → Prop) : (∀ x, mem x empty → P x) ↔ true := iff.intro (assume H, trivial) (assume H, take x, assume H', absurd H' (not_mem_empty _)) theorem forall_mem_empty_eq {A : Type} (P : A → Prop) : (∀ x, mem x empty → P x) = true := propext (forall_mem_empty_iff _) theorem forall_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) ↔ P a ∧ (∀ x, x ∈ s → P x) := iff.intro (assume H, and.intro (H _ (mem_insert _ _)) (take x, assume H', H _ (mem_insert_of_mem _ H'))) (assume H, take x, assume H' : x ∈ insert a s, or.elim (eq_or_mem_of_mem_insert H') (suppose x = a, eq.subst (eq.symm this) (and.left H)) (suppose x ∈ s, and.right H _ this)) theorem forall_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) = (P a ∧ (∀ x, x ∈ s → P x)) := propext (forall_mem_insert_iff _ _ _) end finset
607430aa8cf8a155d66e1ffd249b9a3dc2ccf5e5
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Compiler/ExternAttr.lean
b910dff069aa6e523c551245925a442f81b43025
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,959
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.Expr import Lean.Environment import Lean.Attributes import Lean.ProjFns import Lean.Meta.Basic namespace Lean inductive ExternEntry where | adhoc (backend : Name) | inline (backend : Name) (pattern : String) | standard (backend : Name) (fn : String) | foreign (backend : Name) (fn : String) /- - `@[extern]` encoding: ```.entries = [adhoc `all]``` - `@[extern "level_hash"]` encoding: ```.entries = [standard `all "levelHash"]``` - `@[extern cpp "lean::string_size" llvm "lean_str_size"]` encoding: ```.entries = [standard `cpp "lean::string_size", standard `llvm "leanStrSize"]``` - `@[extern cpp inline "#1 + #2"]` encoding: ```.entries = [inline `cpp "#1 + #2"]``` - `@[extern cpp "foo" llvm adhoc]` encoding: ```.entries = [standard `cpp "foo", adhoc `llvm]``` - `@[extern 2 cpp "io_prim_println"]` encoding: ```.arity? = 2, .entries = [standard `cpp "ioPrimPrintln"]``` -/ structure ExternAttrData where arity? : Option Nat := none entries : List ExternEntry deriving Inhabited -- def externEntry := parser! optional ident >> optional (nonReservedSymbol "inline ") >> strLit -- @[builtinAttrParser] def extern := parser! nonReservedSymbol "extern " >> optional numLit >> many externEntry private def syntaxToExternAttrData (stx : Syntax) : AttrM ExternAttrData := do let arity? := if stx[1].isNone then none else some <| stx[1][0].isNatLit?.getD 0 let entriesStx := stx[2].getArgs if entriesStx.size == 0 && arity? == none then return { entries := [ ExternEntry.adhoc `all ] } let mut entries := #[] for entryStx in entriesStx do let backend := if entryStx[0].isNone then `all else entryStx[0][0].getId let str ← match entryStx[2].isStrLit? with | none => throwErrorAt! entryStx[2] "string literal expected" | some str => pure str if entryStx[1].isNone then entries := entries.push <| ExternEntry.standard backend str else entries := entries.push <| ExternEntry.inline backend str return { arity? := arity?, entries := entries.toList } @[extern "lean_add_extern"] constant addExtern (env : Environment) (n : Name) : ExceptT String Id Environment builtin_initialize externAttr : ParametricAttribute ExternAttrData ← registerParametricAttribute { name := `extern descr := "builtin and foreign functions" getParam := fun _ stx => syntaxToExternAttrData stx afterSet := fun declName _ => do let mut env ← getEnv if env.isProjectionFn declName || env.isConstructor declName then do env ← ofExcept $ addExtern env declName setEnv env else pure () } @[export lean_get_extern_attr_data] def getExternAttrData (env : Environment) (n : Name) : Option ExternAttrData := externAttr.getParam env n private def parseOptNum : Nat → String.Iterator → Nat → String.Iterator × Nat | 0, it, r => (it, r) | n+1, it, r => if !it.hasNext then (it, r) else let c := it.curr if '0' <= c && c <= '9' then parseOptNum n it.next (r*10 + (c.toNat - '0'.toNat)) else (it, r) def expandExternPatternAux (args : List String) : Nat → String.Iterator → String → String | 0, it, r => r | i+1, it, r => if ¬ it.hasNext then r else let c := it.curr if c ≠ '#' then expandExternPatternAux args i it.next (r.push c) else let it := it.next let (it, j) := parseOptNum it.remainingBytes it 0 let j := j-1 expandExternPatternAux args i it (r ++ args.getD j "") def expandExternPattern (pattern : String) (args : List String) : String := expandExternPatternAux args pattern.length pattern.mkIterator "" def mkSimpleFnCall (fn : String) (args : List String) : String := fn ++ "(" ++ ((args.intersperse ", ").foldl (·++·) "") ++ ")" def ExternEntry.backend : ExternEntry → Name | ExternEntry.adhoc n => n | ExternEntry.inline n _ => n | ExternEntry.standard n _ => n | ExternEntry.foreign n _ => n def getExternEntryForAux (backend : Name) : List ExternEntry → Option ExternEntry | [] => none | e::es => if e.backend == `all then some e else if e.backend == backend then some e else getExternEntryForAux backend es def getExternEntryFor (d : ExternAttrData) (backend : Name) : Option ExternEntry := getExternEntryForAux backend d.entries def isExtern (env : Environment) (fn : Name) : Bool := getExternAttrData env fn |>.isSome /- We say a Lean function marked as `[extern "<c_fn_nane>"]` is for all backends, and it is implemented using `extern "C"`. Thus, there is no name mangling. -/ def isExternC (env : Environment) (fn : Name) : Bool := match getExternAttrData env fn with | some { entries := [ ExternEntry.standard `all _ ], .. } => true | _ => false def getExternNameFor (env : Environment) (backend : Name) (fn : Name) : Option String := do let data ← getExternAttrData env fn let entry ← getExternEntryFor data backend match entry with | ExternEntry.standard _ n => pure n | ExternEntry.foreign _ n => pure n | _ => failure def getExternConstArity (declName : Name) : CoreM (Option Nat) := do let env ← getEnv match getExternAttrData env declName with | none => pure none | some data => match data.arity? with | some arity => pure arity | none => let cinfo ← getConstInfo declName let (arity, _) ← (Meta.forallTelescopeReducing cinfo.type fun xs _ => pure xs.size : MetaM Nat).run pure (some arity) @[export lean_get_extern_const_arity] def getExternConstArityExport (env : Environment) (declName : Name) : IO (Option Nat) := do try let (arity?, _) ← (getExternConstArity declName).toIO {} { env := env } pure arity? catch _ => pure none end Lean
80e369eab2443ae63b9e77484b3acfdfc9a6449c
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/crash.lean
42a10394419ea4db3951f3f44d5ff047549fbd46
[ "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
144
lean
-- section hypothesis P : Prop. definition crash := assume H : P, have H' : ¬ P, from H, _. end
bbc6a825c3f16eafc9914619dfe2a3eb2b93ceda
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/big_operators/default.lean
deda0d18906845df3cbffd322de84342b8197e4d
[ "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
416
lean
-- Import this file to pull in everything about "big operators". -- When preparing a contribution to mathlib, it is best to minimize the imports you use. import algebra.big_operators.order import algebra.big_operators.intervals import algebra.big_operators.ring import algebra.big_operators.pi import algebra.big_operators.finsupp import algebra.big_operators.nat_antidiagonal import algebra.big_operators.part_enat
063464aa076cf482d4aeed392d2e5990fe3299ad
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/600a.lean
b01a921363086662cb979ea5ae693488f8242772
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
20
lean
/- - -/ print "ok"
ca001c4d56c6dfcba2bca8e861876b53a5697d0c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/roots_of_unity.lean
13c9423bcb84e3e1b90a9192857207c0889838b6
[ "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
40,398
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.nat.parity import data.polynomial.ring_division import group_theory.specific_groups.cyclic import ring_theory.integral_domain import number_theory.divisors import data.zmod.basic import tactic.zify import field_theory.separable import field_theory.finite.basic /-! # Roots of unity and primitive roots of unity We define roots of unity in the context of an arbitrary commutative monoid, as a subgroup of the group of units. We also define a predicate `is_primitive_root` on commutative monoids, expressing that an element is a primitive root of unity. ## Main definitions * `roots_of_unity n M`, for `n : ℕ+` is the subgroup of the units of a commutative monoid `M` consisting of elements `x` that satisfy `x ^ n = 1`. * `is_primitive_root ζ k`: an element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. * `primitive_roots k R`: the finset of primitive `k`-th roots of unity in an integral domain `R`. ## Main results * `roots_of_unity.is_cyclic`: the roots of unity in an integral domain form a cyclic group. * `is_primitive_root.zmod_equiv_gpowers`: `zmod k` is equivalent to the subgroup generated by a primitive `k`-th root of unity. * `is_primitive_root.gpowers_eq`: in an integral domain, the subgroup generated by a primitive `k`-th root of unity is equal to the `k`-th roots of unity. * `is_primitive_root.card_primitive_roots`: if an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. ## Implementation details It is desirable that `roots_of_unity` is a subgroup, and it will mainly be applied to rings (e.g. the ring of integers in a number field) and fields. We therefore implement it as a subgroup of the units of a commutative monoid. We have chosen to define `roots_of_unity n` for `n : ℕ+`, instead of `n : ℕ`, because almost all lemmas need the positivity assumption, and in particular the type class instances for `fintype` and `is_cyclic`. On the other hand, for primitive roots of unity, it is desirable to have a predicate not just on units, but directly on elements of the ring/field. For example, we want to say that `exp (2 * pi * I / n)` is a primitive `n`-th root of unity in the complex numbers, without having to turn that number into a unit first. This creates a little bit of friction, but lemmas like `is_primitive_root.is_unit` and `is_primitive_root.coe_units_iff` should provide the necessary glue. -/ open_locale classical big_operators noncomputable theory open polynomial open finset variables {M N G G₀ R S : Type*} variables [comm_monoid M] [comm_monoid N] [comm_group G] [comm_group_with_zero G₀] variables [integral_domain R] [integral_domain S] section roots_of_unity variables {k l : ℕ+} /-- `roots_of_unity k M` is the subgroup of elements `m : units M` that satisfy `m ^ k = 1` -/ def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup (units M) := { carrier := { ζ | ζ ^ (k : ℕ) = 1 }, one_mem' := one_pow _, mul_mem' := λ ζ ξ hζ hξ, by simp only [*, set.mem_set_of_eq, mul_pow, one_mul] at *, inv_mem' := λ ζ hζ, by simp only [*, set.mem_set_of_eq, inv_pow, one_inv] at * } @[simp] lemma mem_roots_of_unity (k : ℕ+) (ζ : units M) : ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl lemma roots_of_unity_le_of_dvd (h : k ∣ l) : roots_of_unity k M ≤ roots_of_unity l M := begin obtain ⟨d, rfl⟩ := h, intros ζ h, simp only [mem_roots_of_unity, pnat.mul_coe, pow_mul, one_pow, *] at *, end lemma map_roots_of_unity (f : units M →* units N) (k : ℕ+) : (roots_of_unity k M).map f ≤ roots_of_unity k N := begin rintros _ ⟨ζ, h, rfl⟩, simp only [←monoid_hom.map_pow, *, mem_roots_of_unity, set_like.mem_coe, monoid_hom.map_one] at * end lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : units R} : ζ ∈ roots_of_unity k R ↔ (ζ : R) ∈ nth_roots k (1 : R) := by simp only [mem_roots_of_unity, mem_nth_roots k.pos, units.ext_iff, units.coe_one, units.coe_pow] variables (k R) /-- Equivalence between the `k`-th roots of unity in `R` and the `k`-th roots of `1`. This is implemented as equivalence of subtypes, because `roots_of_unity` is a subgroup of the group of units, whereas `nth_roots` is a multiset. -/ def roots_of_unity_equiv_nth_roots : roots_of_unity k R ≃ {x // x ∈ nth_roots k (1 : R)} := begin refine { to_fun := λ x, ⟨x, mem_roots_of_unity_iff_mem_nth_roots.mp x.2⟩, inv_fun := λ x, ⟨⟨x, x ^ (k - 1 : ℕ), _, _⟩, _⟩, left_inv := _, right_inv := _ }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, all_goals { rcases x with ⟨x, hx⟩, rw [mem_nth_roots k.pos] at hx, simp only [subtype.coe_mk, ← pow_succ, ← pow_succ', hx, nat.sub_add_cancel (show 1 ≤ (k : ℕ), from k.one_le)] }, { show (_ : units R) ^ (k : ℕ) = 1, simp only [units.ext_iff, hx, units.coe_mk, units.coe_one, subtype.coe_mk, units.coe_pow] } end variables {k R} @[simp] lemma roots_of_unity_equiv_nth_roots_apply (x : roots_of_unity k R) : (roots_of_unity_equiv_nth_roots R k x : R) = x := rfl @[simp] lemma roots_of_unity_equiv_nth_roots_symm_apply (x : {x // x ∈ nth_roots k (1 : R)}) : ((roots_of_unity_equiv_nth_roots R k).symm x : R) = x := rfl variables (k R) instance roots_of_unity.fintype : fintype (roots_of_unity k R) := fintype.of_equiv {x // x ∈ nth_roots k (1 : R)} $ (roots_of_unity_equiv_nth_roots R k).symm instance roots_of_unity.is_cyclic : is_cyclic (roots_of_unity k R) := is_cyclic_of_subgroup_integral_domain ((units.coe_hom R).comp (roots_of_unity k R).subtype) (units.ext.comp subtype.val_injective) lemma card_roots_of_unity : fintype.card (roots_of_unity k R) ≤ k := calc fintype.card (roots_of_unity k R) = fintype.card {x // x ∈ nth_roots k (1 : R)} : fintype.card_congr (roots_of_unity_equiv_nth_roots R k) ... ≤ (nth_roots k (1 : R)).attach.card : multiset.card_le_of_le (multiset.erase_dup_le _) ... = (nth_roots k (1 : R)).card : multiset.card_attach ... ≤ k : card_nth_roots k 1 variables {k R} @[norm_cast] lemma roots_of_unity.coe_pow (ζ : roots_of_unity k R) (m : ℕ) : ↑(ζ ^ m) = (ζ ^ m : R) := begin change ↑(↑(ζ ^ m) : units R) = ↑(ζ : units R) ^ m, rw [subgroup.coe_pow, units.coe_pow], end /-- Restrict a ring homomorphism between integral domains to the nth roots of unity -/ def ring_hom.restrict_roots_of_unity (σ : R →+* S) (n : ℕ+) : roots_of_unity n R →* roots_of_unity n S := let h : ∀ ξ : roots_of_unity n R, (σ ξ) ^ (n : ℕ) = 1 := λ ξ, by { change (σ (ξ : units R)) ^ (n : ℕ) = 1, rw [←σ.map_pow, ←units.coe_pow, show ((ξ : units R) ^ (n : ℕ) = 1), from ξ.2, units.coe_one, σ.map_one] } in { to_fun := λ ξ, ⟨@unit_of_invertible _ _ _ (invertible_of_pow_eq_one _ _ (h ξ) n.2), by { ext, rw units.coe_pow, exact h ξ }⟩, map_one' := by { ext, exact σ.map_one }, map_mul' := λ ξ₁ ξ₂, by { ext, rw [subgroup.coe_mul, units.coe_mul], exact σ.map_mul _ _ } } @[simp] lemma ring_hom.restrict_roots_of_unity_coe_apply (σ : R →+* S) (ζ : roots_of_unity k R) : ↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ := rfl /-- Restrict a ring isomorphism between integral domains to the nth roots of unity -/ def ring_equiv.restrict_roots_of_unity (σ : R ≃+* S) (n : ℕ+) : roots_of_unity n R ≃* roots_of_unity n S := { to_fun := σ.to_ring_hom.restrict_roots_of_unity n, inv_fun := σ.symm.to_ring_hom.restrict_roots_of_unity n, left_inv := λ ξ, by { ext, exact σ.symm_apply_apply ξ }, right_inv := λ ξ, by { ext, exact σ.apply_symm_apply ξ }, map_mul' := (σ.to_ring_hom.restrict_roots_of_unity n).map_mul } @[simp] lemma ring_equiv.restrict_roots_of_unity_coe_apply (σ : R ≃+* S) (ζ : roots_of_unity k R) : ↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ := rfl @[simp] lemma ring_equiv.restrict_roots_of_unity_symm (σ : R ≃+* S) : (σ.restrict_roots_of_unity k).symm = σ.symm.restrict_roots_of_unity k := rfl lemma ring_hom.map_root_of_unity_eq_pow_self (σ : R →+* R) (ζ : roots_of_unity k R) : ∃ m : ℕ, σ ζ = ζ ^ m := begin obtain ⟨m, hm⟩ := (σ.restrict_roots_of_unity k).map_cyclic, rw [←σ.restrict_roots_of_unity_coe_apply, hm, gpow_eq_mod_order_of, ←int.to_nat_of_nonneg (m.mod_nonneg (int.coe_nat_ne_zero.mpr (pos_iff_ne_zero.mp (order_of_pos ζ)))), gpow_coe_nat, roots_of_unity.coe_pow], exact ⟨(m % (order_of ζ)).to_nat, rfl⟩, end end roots_of_unity /-- An element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. -/ structure is_primitive_root (ζ : M) (k : ℕ) : Prop := (pow_eq_one : ζ ^ (k : ℕ) = 1) (dvd_of_pow_eq_one : ∀ l : ℕ, ζ ^ l = 1 → k ∣ l) section primitive_roots variables {k : ℕ} /-- `primitive_roots k R` is the finset of primitive `k`-th roots of unity in the integral domain `R`. -/ def primitive_roots (k : ℕ) (R : Type*) [integral_domain R] : finset R := (nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k) @[simp] lemma mem_primitive_roots {ζ : R} (h0 : 0 < k) : ζ ∈ primitive_roots k R ↔ is_primitive_root ζ k := begin rw [primitive_roots, mem_filter, multiset.mem_to_finset, mem_nth_roots h0, and_iff_right_iff_imp], exact is_primitive_root.pow_eq_one end end primitive_roots namespace is_primitive_root variables {k l : ℕ} lemma iff_def (ζ : M) (k : ℕ) : is_primitive_root ζ k ↔ (ζ ^ k = 1) ∧ (∀ l : ℕ, ζ ^ l = 1 → k ∣ l) := ⟨λ ⟨h1, h2⟩, ⟨h1, h2⟩, λ ⟨h1, h2⟩, ⟨h1, h2⟩⟩ lemma mk_of_lt (ζ : M) (hk : 0 < k) (h1 : ζ ^ k = 1) (h : ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1) : is_primitive_root ζ k := begin refine ⟨h1, _⟩, intros l hl, apply dvd_trans _ (k.gcd_dvd_right l), suffices : k.gcd l = k, { rw this }, rw eq_iff_le_not_lt, refine ⟨nat.le_of_dvd hk (k.gcd_dvd_left l), _⟩, intro h', apply h _ (nat.gcd_pos_of_pos_left _ hk) h', exact pow_gcd_eq_one _ h1 hl end section comm_monoid variables {ζ : M} (h : is_primitive_root ζ k) lemma pow_eq_one_iff_dvd (l : ℕ) : ζ ^ l = 1 ↔ k ∣ l := ⟨h.dvd_of_pow_eq_one l, by { rintro ⟨i, rfl⟩, simp only [pow_mul, h.pow_eq_one, one_pow, pnat.mul_coe] }⟩ lemma is_unit (h : is_primitive_root ζ k) (h0 : 0 < k) : is_unit ζ := begin apply is_unit_of_mul_eq_one ζ (ζ ^ (k - 1)), rw [← pow_succ, nat.sub_add_cancel h0, h.pow_eq_one] end lemma pow_ne_one_of_pos_of_lt (h0 : 0 < l) (hl : l < k) : ζ ^ l ≠ 1 := mt (nat.le_of_dvd h0 ∘ h.dvd_of_pow_eq_one _) $ not_le_of_lt hl lemma pow_inj (h : is_primitive_root ζ k) ⦃i j : ℕ⦄ (hi : i < k) (hj : j < k) (H : ζ ^ i = ζ ^ j) : i = j := begin wlog hij : i ≤ j, apply le_antisymm hij, rw ← nat.sub_eq_zero_iff_le, apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt (nat.sub_le_self _ _) hj), apply h.dvd_of_pow_eq_one, rw [← ((h.is_unit (lt_of_le_of_lt (nat.zero_le _) hi)).pow i).mul_left_inj, ← pow_add, nat.sub_add_cancel hij, H, one_mul] end lemma one : is_primitive_root (1 : M) 1 := { pow_eq_one := pow_one _, dvd_of_pow_eq_one := λ l hl, one_dvd _ } @[simp] lemma one_right_iff : is_primitive_root ζ 1 ↔ ζ = 1 := begin split, { intro h, rw [← pow_one ζ, h.pow_eq_one] }, { rintro rfl, exact one } end @[simp] lemma coe_units_iff {ζ : units M} : is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k := by simp only [iff_def, units.ext_iff, units.coe_pow, units.coe_one] lemma pow_of_coprime (h : is_primitive_root ζ k) (i : ℕ) (hi : i.coprime k) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : k = 0, { subst k, simp only [*, pow_one, nat.coprime_zero_right] at * }, rcases h.is_unit (nat.pos_of_ne_zero h0) with ⟨ζ, rfl⟩, rw [← units.coe_pow], rw coe_units_iff at h ⊢, refine { pow_eq_one := by rw [← pow_mul', pow_mul, h.pow_eq_one, one_pow], dvd_of_pow_eq_one := _ }, intros l hl, apply h.dvd_of_pow_eq_one, rw [← pow_one ζ, ← gpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, gpow_add, mul_pow, ← gpow_coe_nat, ← gpow_mul, mul_right_comm], simp only [gpow_mul, hl, h.pow_eq_one, one_gpow, one_pow, one_mul, gpow_coe_nat] end lemma pow_of_prime (h : is_primitive_root ζ k) {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ k) : is_primitive_root (ζ ^ p) k := h.pow_of_coprime p (hprime.coprime_iff_not_dvd.2 hdiv) lemma pow_iff_coprime (h : is_primitive_root ζ k) (h0 : 0 < k) (i : ℕ) : is_primitive_root (ζ ^ i) k ↔ i.coprime k := begin refine ⟨_, h.pow_of_coprime i⟩, intro hi, obtain ⟨a, ha⟩ := i.gcd_dvd_left k, obtain ⟨b, hb⟩ := i.gcd_dvd_right k, suffices : b = k, { rwa [this, ← one_mul k, nat.mul_left_inj h0, eq_comm] at hb { occs := occurrences.pos [1] } }, rw [ha] at hi, rw [mul_comm] at hb, apply nat.dvd_antisymm ⟨i.gcd k, hb⟩ (hi.dvd_of_pow_eq_one b _), rw [← pow_mul', ← mul_assoc, ← hb, pow_mul, h.pow_eq_one, one_pow] end end comm_monoid section comm_group variables {ζ : G} lemma gpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 := by { rw gpow_coe_nat, exact h.pow_eq_one } lemma gpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [gpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj, ← gpow_neg, ← hl', gpow_coe_nat, one_inv] } end lemma inv (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, one_inv, eq_self_iff_true, inv_pow], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj, ← inv_pow, hl, one_inv] end } @[simp] lemma inv_iff : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv h⟩, intro h, rw [← inv_inv ζ], exact inv h } lemma gpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, rw gpow_coe_nat, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff, ← gpow_neg, ← hi', gpow_coe_nat], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end @[simp] lemma coe_subgroup_iff (H : subgroup G) {ζ : H} : is_primitive_root (ζ : G) k ↔ is_primitive_root ζ k := by simp only [iff_def, ← subgroup.coe_pow, ← H.coe_one, ← subtype.ext_iff] end comm_group section comm_group_with_zero variables {ζ : G₀} lemma fpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 := by { rw gpow_coe_nat, exact h.pow_eq_one } lemma fpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [gpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj', ← fpow_neg, ← hl', gpow_coe_nat, inv_one] } end lemma inv' (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, inv_one, eq_self_iff_true, inv_pow'], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj', ← inv_pow', hl, inv_one] end } @[simp] lemma inv_iff' : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv' h⟩, intro h, rw [← inv_inv' ζ], exact inv' h } lemma fpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, rw gpow_coe_nat, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff', ← fpow_neg, ← hi', gpow_coe_nat], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end end comm_group_with_zero section integral_domain variables {ζ : R} @[simp] lemma primitive_roots_zero : primitive_roots 0 R = ∅ := begin rw [← finset.val_eq_zero, ← multiset.subset_zero, ← nth_roots_zero (1 : R), primitive_roots], simp only [finset.not_mem_empty, forall_const, forall_prop_of_false, multiset.to_finset_zero, finset.filter_true_of_mem, finset.empty_val, not_false_iff, multiset.zero_subset, nth_roots_zero] end @[simp] lemma primitive_roots_one : primitive_roots 1 R = {(1 : R)} := begin apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.one_right_iff, mem_primitive_roots zero_lt_one] }, { intros x hx, rw [mem_primitive_roots zero_lt_one, is_primitive_root.one_right_iff] at hx, exact hx } end lemma neg_one (p : ℕ) [char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 := mk_of_lt (-1 : R) dec_trivial (by simp only [one_pow, neg_sq]) $ begin intros l hl0 hl2, obtain rfl : l = 1, { unfreezingI { clear_dependent R p }, dec_trivial! }, simp only [pow_one, ne.def], intro h, suffices h2 : p ∣ 2, { have := char_p.char_ne_one R p, unfreezingI { clear_dependent R }, have aux := nat.le_of_dvd dec_trivial h2, revert this hp h2, revert p, dec_trivial }, simp only [← char_p.cast_eq_zero_iff R p, nat.cast_bit0, nat.cast_one], rw [bit0, ← h, neg_add_self] { occs := occurrences.pos [1] } end lemma eq_neg_one_of_two_right (h : is_primitive_root ζ 2) : ζ = -1 := begin apply (eq_or_eq_neg_of_sq_eq_sq ζ 1 _).resolve_left, { rw [← pow_one ζ], apply h.pow_ne_one_of_pos_of_lt; dec_trivial }, { simp only [h.pow_eq_one, one_pow] } end end integral_domain section integral_domain variables {ζ : units R} (h : is_primitive_root ζ k) protected lemma mem_roots_of_unity {n : ℕ+} (h : is_primitive_root ζ n) : ζ ∈ roots_of_unity n R := h.pow_eq_one /-- The (additive) monoid equivalence between `zmod k` and the powers of a primitive root of unity `ζ`. -/ def zmod_equiv_gpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.gpowers ζ) := add_equiv.of_bijective (add_monoid_hom.lift_of_right_inverse (int.cast_add_hom $ zmod k) _ zmod.int_cast_right_inverse ⟨{ to_fun := λ i, additive.of_mul (⟨_, i, rfl⟩ : subgroup.gpowers ζ), map_zero' := by { simp only [gpow_zero], refl }, map_add' := by { intros i j, simp only [gpow_add], refl } }, (λ i hi, begin simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k, add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hi ⊢, obtain ⟨i, rfl⟩ := hi, simp only [gpow_mul, h.pow_eq_one, one_gpow, gpow_coe_nat], refl end)⟩) begin split, { rw add_monoid_hom.injective_iff, intros i hi, rw subtype.ext_iff at hi, have := (h.gpow_eq_one_iff_dvd _).mp hi, rw [← (char_p.int_cast_eq_zero_iff (zmod k) k _).mpr this, eq_comm], exact zmod.int_cast_right_inverse i }, { rintro ⟨ξ, i, rfl⟩, refine ⟨int.cast_add_hom _ i, _⟩, rw [add_monoid_hom.lift_of_right_inverse_comp_apply], refl } end @[simp] lemma zmod_equiv_gpowers_apply_coe_int (i : ℤ) : h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) := add_monoid_hom.lift_of_right_inverse_comp_apply _ _ zmod.int_cast_right_inverse _ _ @[simp] lemma zmod_equiv_gpowers_apply_coe_nat (i : ℕ) : h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) := begin have : (i : zmod k) = (i : ℤ), by norm_cast, simp only [this, zmod_equiv_gpowers_apply_coe_int, gpow_coe_nat], refl end @[simp] lemma zmod_equiv_gpowers_symm_apply_gpow (i : ℤ) : h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i := by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_int] @[simp] lemma zmod_equiv_gpowers_symm_apply_gpow' (i : ℤ) : h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_gpowers_symm_apply_gpow i @[simp] lemma zmod_equiv_gpowers_symm_apply_pow (i : ℕ) : h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i := by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_nat] @[simp] lemma zmod_equiv_gpowers_symm_apply_pow' (i : ℕ) : h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_gpowers_symm_apply_pow i lemma gpowers_eq {k : ℕ+} {ζ : units R} (h : is_primitive_root ζ k) : subgroup.gpowers ζ = roots_of_unity k R := begin apply set_like.coe_injective, haveI : fact (0 < (k : ℕ)) := ⟨k.pos⟩, haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_gpowers).to_equiv, refine @set.eq_of_subset_of_card_le (units R) (subgroup.gpowers ζ) (roots_of_unity k R) F (roots_of_unity.fintype R k) (subgroup.gpowers_subset $ show ζ ∈ roots_of_unity k R, from h.pow_eq_one) _, calc fintype.card (roots_of_unity k R) ≤ k : card_roots_of_unity R k ... = fintype.card (zmod k) : (zmod.card k).symm ... = fintype.card (subgroup.gpowers ζ) : fintype.card_congr (h.zmod_equiv_gpowers).to_equiv end lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) (hξ : ξ ∈ roots_of_unity k R) : ∃ (i : ℕ) (hi : i < k), ζ ^ i = ξ := begin obtain ⟨n, rfl⟩ : ∃ n : ℤ, ζ ^ n = ξ, by rwa [← h.gpowers_eq] at hξ, have hk0 : (0 : ℤ) < k := by exact_mod_cast k.pos, let i := n % k, have hi0 : 0 ≤ i := int.mod_nonneg _ (ne_of_gt hk0), lift i to ℕ using hi0 with i₀ hi₀, refine ⟨i₀, _, _⟩, { zify, rw [hi₀], exact int.mod_lt_of_pos _ hk0 }, { have aux := h.gpow_eq_one, rw [← coe_coe] at aux, rw [← gpow_coe_nat, hi₀, ← int.mod_add_div n k, gpow_add, gpow_mul, aux, one_gpow, mul_one] } end lemma eq_pow_of_pow_eq_one {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (hξ : ξ ^ k = 1) (h0 : 0 < k) : ∃ i < k, ζ ^ i = ξ := begin obtain ⟨ζ, rfl⟩ := h.is_unit h0, obtain ⟨ξ, rfl⟩ := is_unit_of_pow_eq_one ξ k hξ h0, obtain ⟨k, rfl⟩ : ∃ k' : ℕ+, k = k' := ⟨⟨k, h0⟩, rfl⟩, simp only [← units.coe_pow, ← units.ext_iff], rw coe_units_iff at h, apply h.eq_pow_of_mem_roots_of_unity, rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, hξ, units.coe_one] end lemma is_primitive_root_iff' {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) : is_primitive_root ξ k ↔ ∃ (i < (k : ℕ)) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_mem_roots_of_unity hξ.pow_eq_one, rw h.pow_iff_coprime k.pos at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma is_primitive_root_iff {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (h0 : 0 < k) : is_primitive_root ξ k ↔ ∃ (i < k) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_pow_eq_one hξ.pow_eq_one h0, rw h.pow_iff_coprime h0 at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma card_roots_of_unity' {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin haveI : fact (0 < ↑n) := ⟨n.pos⟩, let e := h.zmod_equiv_gpowers, haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ e.to_equiv, calc fintype.card (roots_of_unity n R) = fintype.card (subgroup.gpowers ζ) : fintype.card_congr $ by rw h.gpowers_eq ... = fintype.card (zmod n) : fintype.card_congr e.to_equiv.symm ... = n : zmod.card n end lemma card_roots_of_unity {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin obtain ⟨ζ, hζ⟩ := h.is_unit n.pos, rw [← hζ, is_primitive_root.coe_units_iff] at h, exact h.card_roots_of_unity' end /-- The cardinality of the multiset `nth_roots ↑n (1 : R)` is `n` if there is a primitive root of unity in `R`. -/ lemma card_nth_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).card = n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.card_zero, nth_roots_zero] }, rw eq_iff_le_not_lt, use card_nth_roots n 1, { rw [not_lt], have hcard : fintype.card {x // x ∈ nth_roots n (1 : R)} ≤ (nth_roots n (1 : R)).attach.card := multiset.card_le_of_le (multiset.erase_dup_le _), rw multiset.card_attach at hcard, rw ← pnat.to_pnat'_coe hpos at hcard h ⊢, set m := nat.to_pnat' n, rw [← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at hcard, exact hcard } end /-- The multiset `nth_roots ↑n (1 : R)` has no repeated elements if there is a primitive root of unity in `R`. -/ lemma nth_roots_nodup {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).nodup := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.nodup_zero, nth_roots_zero] }, apply (@multiset.erase_dup_eq_self R _ _).1, rw eq_iff_le_not_lt, split, { exact multiset.erase_dup_le (nth_roots n (1 : R)) }, { by_contra ha, replace ha := multiset.card_lt_of_lt ha, rw card_nth_roots h at ha, have hrw : (nth_roots n (1 : R)).erase_dup.card = fintype.card {x // x ∈ (nth_roots n (1 : R))}, { set fs := (⟨(nth_roots n (1 : R)).erase_dup, multiset.nodup_erase_dup _⟩ : finset R), rw [← finset.card_mk, ← fintype.card_of_subtype fs _], intro x, simp only [multiset.mem_erase_dup, finset.mem_mk] }, rw ← pnat.to_pnat'_coe hpos at h hrw ha, set m := nat.to_pnat' n, rw [hrw, ← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at ha, exact nat.lt_asymm ha ha } end @[simp] lemma card_nth_roots_finset {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots_finset n R).card = n := by rw [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), card_mk, h.card_nth_roots] open_locale nat /-- If an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. -/ lemma card_primitive_roots {ζ : R} {k : ℕ} (h : is_primitive_root ζ k) (h0 : 0 < k) : (primitive_roots k R).card = φ k := begin symmetry, refine finset.card_congr (λ i _, ζ ^ i) _ _ _, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i - hi, rw mem_primitive_roots h0, exact h.pow_of_coprime i hi.symm }, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i j hi - hj - H, exact h.pow_inj hi hj H }, { simp only [exists_prop, true_and, mem_filter, mem_range, mem_univ], intros ξ hξ, rw [mem_primitive_roots h0, h.is_primitive_root_iff h0] at hξ, rcases hξ with ⟨i, hin, hi, H⟩, exact ⟨i, ⟨hin, hi.symm⟩, H⟩ } end /-- The sets `primitive_roots k R` are pairwise disjoint. -/ lemma disjoint {k l : ℕ} (hk : 0 < k) (hl : 0 < l) (h : k ≠ l) : disjoint (primitive_roots k R) (primitive_roots l R) := begin intro z, simp only [finset.inf_eq_inter, finset.mem_inter, mem_primitive_roots, hk, hl, iff_def], rintro ⟨⟨hzk, Hzk⟩, ⟨hzl, Hzl⟩⟩, apply_rules [h, nat.dvd_antisymm, Hzk, Hzl, hzk, hzl] end /-- If there is a `n`-th primitive root of unity in `R` and `b` divides `n`, then there is a `b`-th primitive root of unity in `R`. -/ lemma pow {ζ : R} {n : ℕ} {a b : ℕ} (hn : 0 < n) (h : is_primitive_root ζ n) (hprod : n = a * b) : is_primitive_root (ζ ^ a) b := begin subst n, simp only [iff_def, ← pow_mul, h.pow_eq_one, eq_self_iff_true, true_and], intros l hl, have ha0 : a ≠ 0, { rintro rfl, simpa only [nat.not_lt_zero, zero_mul] using hn }, rwa ← mul_dvd_mul_iff_left ha0, exact h.dvd_of_pow_eq_one _ hl end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots' {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors ↑n).bUnion (λ i, (primitive_roots i R)) := begin symmetry, apply finset.eq_of_subset_of_card_le, { intros x, simp only [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), exists_prop, finset.mem_bUnion, finset.mem_filter, finset.mem_range, mem_nth_roots, finset.mem_mk, nat.mem_divisors, and_true, ne.def, pnat.ne_zero, pnat.pos, not_false_iff], rintro ⟨a, ⟨d, hd⟩, ha⟩, have hazero : 0 < a, { contrapose! hd with ha0, simp only [nonpos_iff_eq_zero, zero_mul, *] at *, exact n.ne_zero }, rw mem_primitive_roots hazero at ha, rw [hd, pow_mul, ha.pow_eq_one, one_pow] }, { apply le_of_eq, rw [h.card_nth_roots_finset, finset.card_bUnion], { rw [← nat.sum_totient n, nat.filter_dvd_eq_divisors (pnat.ne_zero n), sum_congr rfl] { occs := occurrences.pos [1] }, simp only [finset.mem_filter, finset.mem_range, nat.mem_divisors], rintro k ⟨H, hk⟩, have hdvd := H, rcases H with ⟨d, hd⟩, rw mul_comm at hd, rw (h.pow n.pos hd).card_primitive_roots (pnat.pos_of_div_pos hdvd) }, { intros i hi j hj hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hi hj, exact disjoint (pnat.pos_of_div_pos hi) (pnat.pos_of_div_pos hj) hdiff } } end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots {ζ : R} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors n).bUnion (λ i, (primitive_roots i R)) := @nth_roots_one_eq_bUnion_primitive_roots' _ _ _ ⟨n, hpos⟩ h end integral_domain section minpoly open minpoly variables {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) include n μ h hpos /--`μ` is integral over `ℤ`. -/ lemma is_integral : is_integral ℤ μ := begin use (X ^ n - 1), split, { exact (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm) }, { simp only [((is_primitive_root.iff_def μ n).mp h).left, eval₂_one, eval₂_X_pow, eval₂_sub, sub_self] } end variables [char_zero K] /--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/ lemma minpoly_dvd_X_pow_sub_one : minpoly ℤ μ ∣ X ^ n - 1 := begin apply integer_dvd (is_integral h hpos) (polynomial.monic.is_primitive (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm)), simp only [((is_primitive_root.iff_def μ n).mp h).left, aeval_X_pow, ring_hom.eq_int_cast, int.cast_one, aeval_one, alg_hom.map_sub, sub_self] end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is separable. -/ lemma separable_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬p ∣ n) : separable (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := begin have hdvd : (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) ∣ X ^ n - 1, { simpa [map_pow, map_X, map_one, ring_hom.coe_of, map_sub] using ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))) (minpoly_dvd_X_pow_sub_one h hpos) }, refine separable.of_dvd (separable_X_pow_sub_C 1 _ one_ne_zero) hdvd, by_contra hzero, exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 (not_not.1 hzero)) end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is squarefree. -/ lemma squarefree_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬ p ∣ n) : squarefree (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := (separable_minpoly_mod h hpos hdiv).squarefree /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `expand ℤ p Q`. -/ lemma minpoly_dvd_expand {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ n) : minpoly ℤ μ ∣ expand ℤ p (minpoly ℤ (μ ^ p)) := begin apply minpoly.integer_dvd (h.is_integral hpos), { apply monic.is_primitive, rw [polynomial.monic, leading_coeff, nat_degree_expand, mul_comm, coeff_expand_mul' (nat.prime.pos hprime), ← leading_coeff, ← polynomial.monic], exact minpoly.monic (is_integral (pow_of_prime h hprime hdiv) hpos) }, { rw [aeval_def, coe_expand, ← comp, eval₂_eq_eval_map, map_comp, map_pow, map_X, eval_comp, eval_pow, eval_X, ← eval₂_eq_eval_map, ← aeval_def], exact minpoly.aeval _ _ } end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q ^ p` modulo `p`. -/ lemma minpoly_dvd_pow_mod {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) ^ p := begin set Q := minpoly ℤ (μ ^ p), have hfrob : map (int.cast_ring_hom (zmod p)) Q ^ p = map (int.cast_ring_hom (zmod p)) (expand ℤ p Q), by rw [← zmod.expand_card, map_expand hprime.1.pos], rw [hfrob], apply ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))), exact minpoly_dvd_expand h hpos hprime.1 hdiv end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q` modulo `p`. -/ lemma minpoly_dvd_mod_p {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) := (unique_factorization_monoid.dvd_pow_iff_dvd_of_squarefree (squarefree_minpoly_mod h hpos hdiv) hprime.1.ne_zero).1 (minpoly_dvd_pow_mod h hpos hdiv) /-- If `p` is a prime that does not divide `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ p` are the same. -/ lemma minpoly_eq_pow {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : minpoly ℤ μ = minpoly ℤ (μ ^ p) := begin by_contra hdiff, set P := minpoly ℤ μ, set Q := minpoly ℤ (μ ^ p), have Pmonic : P.monic := minpoly.monic (h.is_integral hpos), have Qmonic : Q.monic := minpoly.monic ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have Pirr : irreducible P := minpoly.irreducible (h.is_integral hpos), have Qirr : irreducible Q := minpoly.irreducible ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have PQprim : is_primitive (P * Q) := Pmonic.is_primitive.mul Qmonic.is_primitive, have prod : P * Q ∣ X ^ n - 1, { rw [(is_primitive.int.dvd_iff_map_cast_dvd_map_cast (P * Q) (X ^ n - 1) PQprim (monic_X_pow_sub_C (1 : ℤ) (ne_of_gt hpos)).is_primitive), map_mul], refine is_coprime.mul_dvd _ _ _, { have aux := is_primitive.int.irreducible_iff_irreducible_map_cast Pmonic.is_primitive, refine (dvd_or_coprime _ _ (aux.1 Pirr)).resolve_left _, rw map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic, intro hdiv, refine hdiff (eq_of_monic_of_associated Pmonic Qmonic _), exact associated_of_dvd_dvd hdiv (dvd_symm_of_irreducible Pirr Qirr hdiv) }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic).2, exact minpoly_dvd_X_pow_sub_one h hpos }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Qmonic).2, exact minpoly_dvd_X_pow_sub_one (pow_of_prime h hprime.1 hdiv) hpos } }, replace prod := ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))) prod, rw [ring_hom.coe_of, map_mul, map_sub, map_one, map_pow, map_X] at prod, obtain ⟨R, hR⟩ := minpoly_dvd_mod_p h hpos hdiv, rw [hR, ← mul_assoc, ← map_mul, ← sq, map_pow] at prod, have habs : map (int.cast_ring_hom (zmod p)) P ^ 2 ∣ map (int.cast_ring_hom (zmod p)) P ^ 2 * R, { use R }, replace habs := lt_of_lt_of_le (enat.coe_lt_coe.2 one_lt_two) (multiplicity.le_multiplicity_of_pow_dvd (dvd_trans habs prod)), have hfree : squarefree (X ^ n - 1 : polynomial (zmod p)), { refine squarefree_X_pow_sub_C 1 _ one_ne_zero, by_contra hzero, exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 (not_not.1 hzero)) }, cases (multiplicity.squarefree_iff_multiplicity_le_one (X ^ n - 1)).1 hfree (map (int.cast_ring_hom (zmod p)) P) with hle hunit, { exact not_lt_of_le hle habs }, { replace hunit := degree_eq_zero_of_is_unit hunit, rw degree_map_eq_of_leading_coeff_ne_zero _ _ at hunit, { exact (ne_of_lt (minpoly.degree_pos (is_integral h hpos))).symm hunit }, simp only [Pmonic, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] }, end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ m` are the same. -/ lemma minpoly_eq_pow_coprime {m : ℕ} (hcop : nat.coprime m n) : minpoly ℤ μ = minpoly ℤ (μ ^ m) := begin revert n hcop, refine unique_factorization_monoid.induction_on_prime m _ _ _, { intros n hn h hpos, congr, simpa [(nat.coprime_zero_left n).mp hn] using h }, { intros u hunit n hcop h hpos, congr, simp [nat.is_unit_iff.mp hunit] }, { intros a p ha hprime hind n hcop h hpos, rw hind (nat.coprime.coprime_mul_left hcop) h hpos, clear hind, replace hprime := nat.prime_iff.2 hprime, have hdiv := (nat.prime.coprime_iff_not_dvd hprime).1 (nat.coprime.coprime_mul_right hcop), haveI := fact.mk hprime, rw [minpoly_eq_pow (h.pow_of_coprime a (nat.coprime.coprime_mul_left hcop)) hpos hdiv], congr' 1, ring_exp } end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomial of a primitive `n`-th root of unity `μ` has `μ ^ m` as root. -/ lemma pow_is_root_minpoly {m : ℕ} (hcop : nat.coprime m n) : is_root (map (int.cast_ring_hom K) (minpoly ℤ μ)) (μ ^ m) := by simpa [minpoly_eq_pow_coprime h hpos hcop, eval_map, aeval_def (μ ^ m) _] using minpoly.aeval ℤ (μ ^ m) /-- `primitive_roots n K` is a subset of the roots of the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma is_roots_of_minpoly : primitive_roots n K ⊆ (map (int.cast_ring_hom K) (minpoly ℤ μ)).roots.to_finset := begin intros x hx, obtain ⟨m, hle, hcop, rfl⟩ := (is_primitive_root_iff h hpos).1 ((mem_primitive_roots hpos).1 hx), simpa [multiset.mem_to_finset, mem_roots (map_monic_ne_zero $ minpoly.monic $ is_integral h hpos)] using pow_is_root_minpoly h hpos hcop end /-- The degree of the minimal polynomial of `μ` is at least `totient n`. -/ lemma totient_le_degree_minpoly : nat.totient n ≤ (minpoly ℤ μ).nat_degree := let P : polynomial ℤ := minpoly ℤ μ,-- minimal polynomial of `μ` P_K : polynomial K := map (int.cast_ring_hom K) P -- minimal polynomial of `μ` sent to `K[X]` in calc n.totient = (primitive_roots n K).card : (h.card_primitive_roots hpos).symm ... ≤ P_K.roots.to_finset.card : finset.card_le_of_subset (is_roots_of_minpoly h hpos) ... ≤ P_K.roots.card : multiset.to_finset_card_le _ ... ≤ P_K.nat_degree : (card_roots' $ map_monic_ne_zero (minpoly.monic $ is_integral h hpos)) ... ≤ P.nat_degree : nat_degree_map_le _ _ end minpoly end is_primitive_root
42d9155600b60f0aa5acc7f6085adcf96293e35b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/geom_sum.lean
6448180fcf0e40c594ef53da8172d08cde1a5d9f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
13,339
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import algebra.group_with_zero.power import algebra.big_operators.order import algebra.big_operators.ring import algebra.big_operators.intervals /-! # Partial sums of geometric series This file determines the values of the geometric series $\sum_{i=0}^{n-1} x^i$ and $\sum_{i=0}^{n-1} x^i y^{n-1-i}$ and variants thereof. ## Main definitions * `geom_sum` defines for each $x$ in a semiring and each natural number $n$ the partial sum $\sum_{i=0}^{n-1} x^i$ of the geometric series. * `geom_sum₂` defines for each $x,y$ in a semiring and each natural number $n$ the partial sum $\sum_{i=0}^{n-1} x^i y^{n-1-i}$ of the geometric series. ## Main statements * `geom_sum_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-x^m}{x-1}$ in a division ring. * `geom_sum₂_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-y^{n-m}x^m}{x-y}$ in a field. Several variants are recorded, generalising in particular to the case of a noncommutative ring in which `x` and `y` commute. Even versions not using division or subtraction, valid in each semiring, are recorded. -/ universe u variable {α : Type u} open finset opposite open_locale big_operators /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i$. -/ def geom_sum [semiring α] (x : α) (n : ℕ) := ∑ i in range n, x ^ i theorem geom_sum_def [semiring α] (x : α) (n : ℕ) : geom_sum x n = ∑ i in range n, x ^ i := rfl @[simp] theorem geom_sum_zero [semiring α] (x : α) : geom_sum x 0 = 0 := rfl @[simp] theorem geom_sum_one [semiring α] (x : α) : geom_sum x 1 = 1 := by { rw [geom_sum_def, sum_range_one, pow_zero] } @[simp] lemma op_geom_sum [ring α] (x : α) (n : ℕ) : op (geom_sum x n) = geom_sum (op x) n := by simp [geom_sum_def] /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i y^{n-1-i}$. -/ def geom_sum₂ [semiring α] (x y : α) (n : ℕ) := ∑ i in range n, x ^ i * (y ^ (n - 1 - i)) theorem geom_sum₂_def [semiring α] (x y : α) (n : ℕ) : geom_sum₂ x y n = ∑ i in range n, x ^ i * y ^ (n - 1 - i) := rfl @[simp] theorem geom_sum₂_zero [semiring α] (x y : α) : geom_sum₂ x y 0 = 0 := rfl @[simp] theorem geom_sum₂_one [semiring α] (x y : α) : geom_sum₂ x y 1 = 1 := by { have : 1 - 1 - 0 = 0 := rfl, rw [geom_sum₂_def, sum_range_one, this, pow_zero, pow_zero, mul_one] } @[simp] lemma op_geom_sum₂ [ring α] (x y : α) (n : ℕ) : op (geom_sum₂ x y n) = geom_sum₂ (op y) (op x) n := begin simp only [geom_sum₂_def, op_sum, op_mul, op_pow], rw ← sum_range_reflect, refine sum_congr rfl (λ j j_in, _), rw [mem_range, nat.lt_iff_add_one_le] at j_in, congr, apply nat.sub_sub_self, exact nat.le_sub_right_of_add_le j_in end @[simp] theorem geom_sum₂_with_one [semiring α] (x : α) (n : ℕ) : geom_sum₂ x 1 n = geom_sum x n := sum_congr rfl (λ i _, by { rw [one_pow, mul_one] }) /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sum₂_mul_add [semiring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := begin let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i), change (∑ i in range n, (f n) i) * x + y ^ n = (x + y) ^ n, induction n with n ih, { rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] }, { have f_last : f (n + 1) n = (x + y) ^ n := by { dsimp [f], rw [nat.sub_sub, nat.add_comm, nat.sub_self, pow_zero, mul_one] }, have f_succ : ∀ i, i ∈ range n → f (n + 1) i = y * f n i := λ i hi, by { dsimp [f], have : commute y ((x + y) ^ i) := (h.symm.add_right (commute.refl y)).pow_right i, rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)], congr' 2, rw [nat.add_sub_cancel, nat.sub_sub, add_comm 1 i], have : i + 1 + (n - (i + 1)) = n := nat.add_sub_of_le (mem_range.mp hi), rw [add_comm (i + 1)] at this, rw [← this, nat.add_sub_cancel, add_comm i 1, ← add_assoc, nat.add_sub_cancel] }, rw [pow_succ (x + y), add_mul, sum_range_succ_comm, add_mul, f_last, add_assoc], rw (((commute.refl x).add_right h).pow_right n).eq, congr' 1, rw [sum_congr rfl f_succ, ← mul_sum, pow_succ y, mul_assoc, ← mul_add y, ih] } end theorem geom_sum₂_self {α : Type*} [comm_ring α] (x : α) (n : ℕ) : geom_sum₂ x x n = n * x ^ (n-1) := calc ∑ i in finset.range n, x ^ i * x ^ (n - 1 - i) = ∑ i in finset.range n, x ^ (i + (n - 1 - i)) : by simp_rw [← pow_add] ... = ∑ i in finset.range n, x ^ (n - 1) : finset.sum_congr rfl (λ i hi, congr_arg _ $ nat.add_sub_cancel' $ nat.le_pred_of_lt $ finset.mem_range.1 hi) ... = (finset.range n).card • (x ^ (n - 1)) : finset.sum_const _ ... = n * x ^ (n - 1) : by rw [finset.card_range, nsmul_eq_mul] /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) : (geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := (commute.all x y).geom_sum₂_mul_add n theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) : (geom_sum (x + 1) n) * x + 1 = (x + 1) ^ n := begin have := (commute.one_right x).geom_sum₂_mul_add n, rw [one_pow, geom_sum₂_with_one] at this, exact this end protected theorem commute.geom_sum₂_mul [ring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n := begin have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n, rw [sub_add_cancel] at this, rw [← this, add_sub_cancel] end lemma commute.mul_neg_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (y - x) * (geom_sum₂ x y n) = y ^ n - x ^ n := begin rw ← op_inj_iff, simp only [op_mul, op_sub, op_geom_sum₂, op_pow], exact (commute.op h.symm).geom_sum₂_mul n end lemma commute.mul_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (x - y) * (geom_sum₂ x y n) = x ^ n - y ^ n := by rw [← neg_sub (y ^ n), ← h.mul_neg_geom_sum₂, ← neg_mul_eq_neg_mul_symm, neg_sub] theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) : (geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n := (commute.all x y).geom_sum₂_mul n theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : (geom_sum x n) * (x - 1) = x ^ n - 1 := begin have := (commute.one_right x).geom_sum₂_mul n, rw [one_pow, geom_sum₂_with_one] at this, exact this end lemma mul_geom_sum [ring α] (x : α) (n : ℕ) : (x - 1) * (geom_sum x n) = x ^ n - 1 := begin rw ← op_inj_iff, simpa using geom_sum_mul (op x) n, end theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) : (geom_sum x n) * (1 - x) = 1 - x ^ n := begin have := congr_arg has_neg.neg (geom_sum_mul x n), rw [neg_sub, ← mul_neg_eq_neg_mul_symm, neg_sub] at this, exact this end lemma mul_neg_geom_sum [ring α] (x : α) (n : ℕ) : (1 - x) * (geom_sum x n) = 1 - x ^ n := begin rw ← op_inj_iff, simpa using geom_sum_mul_neg (op x) n, end protected theorem commute.geom_sum₂ [division_ring α] {x y : α} (h' : commute x y) (h : x ≠ y) (n : ℕ) : (geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h'.geom_sum₂_mul, mul_div_cancel _ this] theorem geom₂_sum [field α] {x y : α} (h : x ≠ y) (n : ℕ) : (geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) := (commute.all x y).geom_sum₂ h n theorem geom_sum_eq [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (geom_sum x n) = (x ^ n - 1) / (x - 1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] protected theorem commute.mul_geom_sum₂_Ico [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := begin rw [sum_Ico_eq_sub _ hmn, ← geom_sum₂_def], have : ∑ k in range m, x ^ k * y ^ (n - 1 - k) = ∑ k in range m, x ^ k * (y ^ (n - m) * y ^ (m - 1 - k)), { refine sum_congr rfl (λ j j_in, _), rw ← pow_add, congr, rw [mem_range, nat.lt_iff_add_one_le, add_comm] at j_in, have h' : n - m + (m - (1 + j)) = n - (1 + j) := nat.sub_add_sub_cancel hmn j_in, rw [nat.sub_sub m, h', nat.sub_sub] }, rw this, simp_rw pow_mul_comm y (n-m) _, simp_rw ← mul_assoc, rw [← sum_mul, ← geom_sum₂_def, mul_sub, h.mul_geom_sum₂, ← mul_assoc, h.mul_geom_sum₂, sub_mul, ← pow_add, nat.add_sub_of_le hmn, sub_sub_sub_cancel_right (x ^ n) (x ^ m * y ^ (n - m)) (y ^ n)], end protected theorem commute.geom_sum₂_succ_eq {α : Type u} [ring α] {x y : α} (h : commute x y) {n : ℕ} : geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) := begin simp_rw [geom_sum₂, mul_sum, sum_range_succ_comm, nat.add_succ_sub_one, add_zero, nat.sub_self, pow_zero, mul_one, add_right_inj, ←mul_assoc, (h.symm.pow_right _).eq, mul_assoc, ←pow_succ], refine sum_congr rfl (λ i hi, _), suffices : n - 1 - i + 1 = n - i, { rw this }, cases n, { exact absurd (list.mem_range.mp hi) i.not_lt_zero }, { rw [nat.sub_add_eq_add_sub (nat.le_pred_of_lt (list.mem_range.mp hi)), nat.sub_add_cancel (nat.succ_le_iff.mpr n.succ_pos)] }, end theorem geom_sum₂_succ_eq {α : Type u} [comm_ring α] (x y : α) {n : ℕ} : geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) := (commute.all x y).geom_sum₂_succ_eq theorem mul_geom_sum₂_Ico [comm_ring α] (x y : α) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := (commute.all x y).mul_geom_sum₂_Ico hmn protected theorem commute.geom_sum₂_Ico_mul [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) * (x - y) = x ^ n - y ^ (n - m) * x ^ m := begin rw ← op_inj_iff, simp only [op_sub, op_mul, op_pow, op_sum], have : ∑ k in Ico m n, op y ^ (n - 1 - k) * op x ^ k = ∑ k in Ico m n, op x ^ k * op y ^ (n - 1 - k), { refine sum_congr rfl (λ k k_in, _), apply commute.pow_pow (commute.op h.symm) }, rw this, exact (commute.op h).mul_geom_sum₂_Ico hmn end theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (x - 1) = x^n - x^m := by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul, geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right] theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (1 - x) = x^m - x^n := by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul, geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left] protected theorem commute.geom_sum₂_Ico [division_ring α] {x y : α} (h : commute x y) (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h.geom_sum₂_Ico_mul hmn, mul_div_cancel _ this] theorem geom_sum₂_Ico [field α] {x y : α} (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := (commute.all x y).geom_sum₂_Ico hxy hmn theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ n - x ^ m) / (x - 1) := by simp only [sum_Ico_eq_sub _ hmn, (geom_sum_def _ _).symm, geom_sum_eq hx, div_sub_div_same, sub_sub_sub_cancel_right] theorem geom_sum_Ico' [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ m - x ^ n) / (1 - x) := by { simp only [geom_sum_Ico hx hmn], convert neg_div_neg_eq (x^m - x^n) (1-x); abel } lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (geom_sum x⁻¹ n) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x := nat.rec_on n (by simp) (λ n h, by rw [pow_succ, mul_inv_rev', ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc, inv_mul_cancel hx0]), begin rw [geom_sum_eq h₁, div_eq_iff_mul_eq h₂, ← mul_right_inj' h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃], simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm, add_left_comm], end variables {β : Type*} theorem ring_hom.map_geom_sum [semiring α] [semiring β] (x : α) (n : ℕ) (f : α →+* β) : f (geom_sum x n) = geom_sum (f x) n := by simp [geom_sum_def, f.map_sum] theorem ring_hom.map_geom_sum₂ [semiring α] [semiring β] (x y : α) (n : ℕ) (f : α →+* β) : f (geom_sum₂ x y n) = geom_sum₂ (f x) (f y) n := by simp [geom_sum₂_def, f.map_sum]
a3b56026669cfebaa1018601034cf55283a506a9
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.33.lean
1495773497e53d97ebf12c81ac8c6513d230791d
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
280
lean
import standard example (p q r : Prop) : p ∧ q ↔ q ∧ p := begin apply iff.intro, { intro H, match H with | and.intro H₁ H₂ := by apply and.intro; repeat assumption end }, { intro H, match H with | and.intro H₁ H₂ := by apply and.intro; repeat assumption end }, end
a7498eaa3c01bdf6993045bba4aef17407bde84e
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/io.lean
f5c52c5ec900f7ab528d7a1cbeb0283f9fdf6c13
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
8,804
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich -/ prelude import init.control.estate init.data.string.basic /-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld. Makes sure we never reorder `IO` operations. TODO: mark opaque -/ def IO.RealWorld : Type := Unit /- TODO(Leo): mark it as an opaque definition. Reason: prevent functions defined in other modules from accessing `IO.RealWorld`. We don't want action such as ``` def getWorld : IO (IO.RealWorld) := get ``` -/ def EIO (ε : Type) : Type → Type := EState ε IO.RealWorld instance (ε : Type) : Monad (EIO ε) := inferInstanceAs (Monad (EState ε IO.RealWorld)) instance (ε : Type) : MonadExcept ε (EIO ε) := inferInstanceAs (MonadExcept ε (EState ε IO.RealWorld)) instance {ε : Type} {α : Type} [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EState ε IO.RealWorld α)) /- In the future, we may want to give more concrete data like in https://doc.rust-lang.org/std/IO/enum.ErrorKind.html -/ def IO.Error := String instance : HasToString IO.Error := inferInstanceAs (HasToString String) instance : Inhabited IO.Error := inferInstanceAs (Inhabited String) def IO.userError (s : String) : IO.Error := s @[export lean.io_error_to_string_core] def IO.Error.toString : IO.Error → String := id abbrev IO : Type → Type := EIO IO.Error @[inline] unsafe def unsafeIO {α : Type} (fn : IO α) : Option α := fn.run' () @[extern 4 "lean_io_timeit"] constant timeit {α : Type} (msg : @& String) (fn : IO α) : IO α := default _ @[extern 4 "lean_io_allocprof"] constant allocprof {α : Type} (msg : @& String) (fn : IO α) : IO α := default _ /- Programs can execute IO actions during initialization that occurs before the `main` function is executed. The attribute `[init <action>]` specifies which IO action is executed to set the value of an opaque constant. The action `initializing` returns `true` iff it is invoked during initialization. -/ @[extern 1 "lean_io_initializing"] constant IO.initializing : IO Bool := default _ abbrev monadIO (m : Type → Type) := HasMonadLiftT IO m namespace IO def ofExcept {ε α : Type} [HasToString ε] (e : Except ε α) : IO α := match e with | Except.ok a => pure a | Except.error e => throw (IO.userError (toString e)) def lazyPure {α : Type} (fn : Unit → α) : IO α := pure (fn ()) inductive Fs.Mode | read | write | readWrite | append constant Fs.handle : Type := Unit namespace Prim open Fs @[specialize] partial def iterate {α β : Type} : α → (α → IO (Sum α β)) → IO β | a f := do v ← f a; match v with | Sum.inl a => iterate a f | Sum.inr b => pure b @[extern 2 "lean_io_prim_put_str"] constant putStr (s: @& String) : IO Unit := default _ @[extern 1 "lean_io_prim_get_line"] constant getLine : IO String := default _ @[extern 4 "lean_io_prim_handle_mk"] constant handle.mk (s : @& String) (m : Mode) (bin : Bool := false) : IO handle := default _ @[extern 2 "lean_io_prim_handle_is_eof"] constant handle.isEof (h : @& handle) : IO Bool := default _ @[extern 2 "lean_io_prim_handle_flush"] constant handle.flush (h : @& handle) : IO Unit := default _ @[extern 2 "lean_io_prim_handle_close"] constant handle.close (h : @& handle) : IO Unit := default _ -- TODO: replace `String` with byte buffer -- constant handle.read : handle → Nat → EIO String -- constant handle.write : handle → String → EIO Unit @[extern 2 "lean_io_prim_handle_get_line"] constant handle.getLine (h : @& handle) : IO String := default _ @[inline] def liftIO {m : Type → Type} {α : Type} [monadIO m] (x : IO α) : m α := monadLift x end Prim section variables {m : Type → Type} [Monad m] [monadIO m] private def putStr : String → m Unit := Prim.liftIO ∘ Prim.putStr def print {α} [HasToString α] (s : α) : m Unit := putStr ∘ toString $ s def println {α} [HasToString α] (s : α) : m Unit := print s *> putStr "\n" end namespace Fs variables {m : Type → Type} [Monad m] [monadIO m] def handle.mk (s : String) (Mode : Mode) (bin : Bool := false) : m handle := Prim.liftIO (Prim.handle.mk s Mode bin) def handle.isEof : handle → m Bool := Prim.liftIO ∘ Prim.handle.isEof def handle.flush : handle → m Unit := Prim.liftIO ∘ Prim.handle.flush def handle.close : handle → m Unit := Prim.liftIO ∘ Prim.handle.flush -- def handle.read (h : handle) (bytes : Nat) : m String := Prim.liftEIO (Prim.handle.read h bytes) -- def handle.write (h : handle) (s : String) : m Unit := Prim.liftEIO (Prim.handle.write h s) def handle.getLine : handle → m String := Prim.liftIO ∘ Prim.handle.getLine /- def getChar (h : handle) : m Char := do b ← h.read 1, if b.isEmpty then fail "getChar failed" else pure b.mkIterator.curr -/ -- def handle.putChar (h : handle) (c : Char) : m Unit := -- h.write (toString c) -- def handle.putStr (h : handle) (s : String) : m Unit := -- h.write s -- def handle.putStrLn (h : handle) (s : String) : m Unit := -- h.putStr s *> h.putStr "\n" def handle.readToEnd (h : handle) : m String := Prim.liftIO $ Prim.iterate "" $ fun r => do done ← h.isEof; if done then pure (Sum.inr r) -- stop else do -- HACK: use less efficient `getLine` while `read` is broken c ← h.getLine; pure $ Sum.inl (r ++ c) -- continue def readFile (fname : String) (bin := false) : m String := do h ← handle.mk fname Mode.read bin; r ← h.readToEnd; h.close; pure r -- def writeFile (fname : String) (data : String) (bin := false) : m Unit := -- do h ← handle.mk fname Mode.write bin, -- h.write data, -- h.close end Fs -- constant stdin : IO Fs.handle -- constant stderr : IO Fs.handle -- constant stdout : IO Fs.handle /- namespace Proc def child : Type := monadIOProcess.child ioCore def child.stdin : child → handle := monadIOProcess.stdin def child.stdout : child → handle := monadIOProcess.stdout def child.stderr : child → handle := monadIOProcess.stderr def spawn (p : IO.process.spawnArgs) : IO child := monadIOProcess.spawn ioCore p def wait (c : child) : IO Nat := monadIOProcess.wait c end Proc -/ /- References -/ constant RefPointed (α : Type) : PointedType := default _ def Ref (α : Type) : Type := (RefPointed α).type instance (α : Type) : Inhabited (Ref α) := ⟨(RefPointed α).val⟩ namespace Prim @[extern 3 cpp inline "lean::io_mk_ref(#2, #3)"] constant mkRef {α : Type} (a : α) : IO (Ref α) := default _ @[extern 3 cpp inline "lean::io_ref_get(#2, #3)"] constant Ref.get {α : Type} (r : @& Ref α) : IO α := default _ @[extern 4 cpp inline "lean::io_ref_set(#2, #3, #4)"] constant Ref.set {α : Type} (r : @& Ref α) (a : α) : IO Unit := default _ @[extern 4 cpp inline "lean::io_ref_swap(#2, #3, #4)"] constant Ref.swap {α : Type} (r : @& Ref α) (a : α) : IO α := default _ @[extern 3 cpp inline "lean::io_ref_reset(#2, #3)"] constant Ref.reset {α : Type} (r : @& Ref α) : IO Unit := default _ end Prim section variables {m : Type → Type} [Monad m] [monadIO m] @[inline] def mkRef {α : Type} (a : α) : m (Ref α) := Prim.liftIO (Prim.mkRef a) @[inline] def Ref.get {α : Type} (r : Ref α) : m α := Prim.liftIO (Prim.Ref.get r) @[inline] def Ref.set {α : Type} (r : Ref α) (a : α) : m Unit := Prim.liftIO (Prim.Ref.set r a) @[inline] def Ref.swap {α : Type} (r : Ref α) (a : α) : m α := Prim.liftIO (Prim.Ref.swap r a) @[inline] def Ref.reset {α : Type} (r : Ref α) : m Unit := Prim.liftIO (Prim.Ref.reset r) @[inline] def Ref.modify {α : Type} (r : Ref α) (f : α → α) : m Unit := do v ← r.get; r.reset; r.set (f v) end end IO /- /-- Run the external process specified by `args`. The process will run to completion with its output captured by a pipe, and read into `String` which is then returned. -/ def IO.cmd (args : IO.process.spawnArgs) : IO String := do child ← IO.Proc.spawn { stdout := IO.process.stdio.piped, ..args }, s ← IO.Fs.readToEnd child.stdout, IO.Fs.close child.stdout, exitv ← IO.Proc.wait child, if exitv ≠ 0 then IO.fail $ "process exited with status " ++ repr exitv else pure (), pure s -/ universe u /-- Typeclass used for presenting the output of an `#eval` command. -/ class HasEval (α : Type u) := (eval : α → IO Unit) instance HasRepr.HasEval {α : Type u} [HasRepr α] : HasEval α := ⟨fun a => IO.println (repr a)⟩ instance IO.HasEval {α : Type} [HasEval α] : HasEval (IO α) := ⟨fun x => do a ← x; HasEval.eval a⟩ -- special case: do not print `()` instance IOUnit.HasEval : HasEval (IO Unit) := ⟨fun x => x⟩
1f9354a2d399f209b30b8b072615ea6db8c1d84b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/omega/int/preterm.lean
5d793e5325c99bb5d34a9e573eb9087a0283e735
[ "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,862
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Linear integer arithmetic terms in pre-normalized form. -/ import tactic.omega.term namespace omega namespace int /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `-5` is reified to `cst -5`) and all other atomic terms are reified to `exp` (e.g., `-5 * (gcd 14 -7)` is reified to `exp -5 \`(gcd 14 -7)`). `exp` accepts a coefficient of type `int` as its first argument because multiplication by constant is allowed by the omega test. -/ meta inductive exprterm : Type | cst : int → exprterm | exp : int → expr → exprterm | add : exprterm → exprterm → exprterm /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ @[derive has_reflect, derive inhabited] inductive preterm : Type | cst : int → preterm | var : int → nat → preterm | add : preterm → preterm → preterm localized "notation (name := preterm.cst) `&` k := omega.int.preterm.cst k" in omega.int localized "infix (name := preterm.var) ` ** `:300 := omega.int.preterm.var" in omega.int localized "notation (name := preterm.add) t ` +* ` s := omega.int.preterm.add t s" in omega.int namespace preterm /-- Preterm evaluation -/ @[simp] def val (v : nat → int) : preterm → int | (& i) := i | (i ** n) := if i = 1 then v n else if i = -1 then -(v n) else (v n) * i | (t1 +* t2) := t1.val + t2.val /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index @[simp] def add_one (t : preterm) : preterm := t +* (&1) def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" end preterm open_locale list.func -- get notation for list.func.set /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term | (& i) := ⟨i, []⟩ | (i ** n) := ⟨0, [] {n ↦ i}⟩ | (t1 +* t2) := term.add (canonize t1) (canonize t2) @[simp] lemma val_canonize {v : nat → int} : ∀ {t : preterm}, (canonize t).val v = t.val v | (& i) := by simp only [preterm.val, add_zero, term.val, canonize, coeffs.val_nil] | (i ** n) := begin simp only [coeffs.val_set, canonize, preterm.val, zero_add, term.val], split_ifs with h1 h2, { simp only [one_mul, h1] }, { simp only [neg_mul, one_mul, h2] }, { rw mul_comm } end | (t +* s) := by simp only [canonize, val_canonize, term.val_add, preterm.val] end int end omega
9c5bd99d68193b47ab2460046cd43af44f8dce12
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/linarith/preprocessing.lean
970feebccff78814d78dcbf822cdd335c9d99b0f
[ "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
12,399
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.linarith.datatypes import tactic.zify import tactic.cancel_denoms /-! # Linarith preprocessing This file contains methods used to preprocess inputs to `linarith`. In particular, `linarith` works over comparisons of the form `t R 0`, where `R ∈ {<,≤,=}`. It assumes that expressions in `t` have integer coefficients and that the type of `t` has well-behaved subtraction. ## Implementation details A `global_preprocessor` is a function `list expr → tactic(list expr)`. Users can add custom preprocessing steps by adding them to the `linarith_config` object. `linarith.default_preprocessors` is the main list, and generally none of these should be skipped unless you know what you're doing. -/ open native tactic expr namespace linarith /-! ### Preprocessing -/ open tactic set_option eqn_compiler.max_steps 50000 /-- If `prf` is a proof of `¬ e`, where `e` is a comparison, `rem_neg prf e` flips the comparison in `e` and returns a proof. For example, if `prf : ¬ a < b`, ``rem_neg prf `(a < b)`` returns a proof of `a ≥ b`. -/ meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := mk_app ``lt_of_not_ge [prf] | `(_ < _) := mk_app ``le_of_not_gt [prf] | `(_ > _) := mk_app ``le_of_not_gt [prf] | `(_ ≥ _) := mk_app ``lt_of_not_ge [prf] | e := failed private meta def rearr_comp_aux : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := mk_app ``neg_nonpos_of_nonneg [prf] | prf `(%%a > 0) := mk_app `neg_neg_of_pos [prf] | prf `(0 ≥ %%a) := to_expr ``(id_rhs (%%a ≤ 0) %%prf) | prf `(0 > %%a) := to_expr ``(id_rhs (%%a < 0) %%prf) | prf `(0 = %%a) := mk_app `eq.symm [prf] | prf `(0 ≤ %%a) := mk_app ``neg_nonpos_of_nonneg [prf] | prf `(0 < %%a) := mk_app `neg_neg_of_pos [prf] | prf `(%%a ≤ %%b) := mk_app ``sub_nonpos_of_le [prf] | prf `(%%a < %%b) := mk_app `sub_neg_of_lt [prf] | prf `(%%a = %%b) := mk_app `sub_eq_zero_of_eq [prf] | prf `(%%a > %%b) := mk_app `sub_neg_of_lt [prf] | prf `(%%a ≥ %%b) := mk_app ``sub_nonpos_of_le [prf] | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp_aux nprf tp | prf a := trace a >> fail "couldn't rearrange comp" /-- `rearr_comp e` takes a proof `e` of an equality, inequality, or negation thereof, and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≤, <}`. -/ meta def rearr_comp (e : expr) : tactic expr := infer_type e >>= rearr_comp_aux e /-- If `e` is of the form `((n : ℕ) : ℤ)`, `is_nat_int_coe e` returns `n : ℕ`. -/ meta def is_nat_int_coe : expr → option expr | `(@coe ℕ ℤ %%_ %%n) := some n | _ := none /-- If `e : ℕ`, returns a proof of `0 ≤ (e : ℤ)`. -/ meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] /-- `get_nat_comps e` returns a list of all subexpressions of `e` of the form `((t : ℕ) : ℤ)`. -/ meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end /-- If `pf` is a proof of a strict inequality `(a : ℤ) < b`, `mk_non_strict_int_pf_of_strict_int_pf pf` returns a proof of `a + 1 ≤ b`, and similarly if `pf` proves a negated weak inequality. -/ meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr := do tp ← infer_type pf, match tp with | `(%%a < %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf) | `(%%a > %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf) | `(¬ %%a ≤ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf)) | `(¬ %%a ≥ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end /-- `is_nat_prop tp` is true iff `tp` is an inequality or equality between natural numbers or the negation thereof. -/ meta def is_nat_prop : expr → bool | `(@eq ℕ %%_ _) := tt | `(@has_le.le ℕ %%_ _ _) := tt | `(@has_lt.lt ℕ %%_ _ _) := tt | `(@ge ℕ %%_ _ _) := tt | `(@gt ℕ %%_ _ _) := tt | `(¬ %%p) := is_nat_prop p | _ := ff /-- `is_strict_int_prop tp` is true iff `tp` is a strict inequality between integers or the negation of a weak inequality between integers. -/ meta def is_strict_int_prop : expr → bool | `(@has_lt.lt ℤ %%_ _ _) := tt | `(@gt ℤ %%_ _ _) := tt | `(¬ @has_le.le ℤ %%_ _ _) := tt | `(¬ @ge ℤ %%_ _ _) := tt | _ := ff private meta def filter_comparisons_aux : expr → bool | `(¬ %%p) := p.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge] | tp := tp.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge, `eq] /-- Removes any expressions that are not proofs of inequalities, equalities, or negations thereof. -/ meta def filter_comparisons : preprocessor := { name := "filter terms that are not proofs of comparisons", transform := λ h, (do tp ← infer_type h, is_prop tp >>= guardb, guardb (filter_comparisons_aux tp), return [h]) <|> return [] } /-- Replaces proofs of negations of comparisons with proofs of the reversed comparisons. For example, a proof of `¬ a < b` will become a proof of `a ≥ b`. -/ meta def remove_negations : preprocessor := { name := "replace negations of comparisons", transform := λ h, do tp ← infer_type h, match tp with | `(¬ %%p) := singleton <$> rem_neg h p | _ := return [h] end } /-- If `h` is an equality or inequality between natural numbers, `nat_to_int` lifts this inequality to the integers. It also adds the facts that the integers involved are nonnegative. To avoid adding the same nonnegativity facts many times, it is a global preprocessor. -/ meta def nat_to_int : global_preprocessor := { name := "move nats to ints", transform := λ l, -- we lock the tactic state here because a `simplify` call inside of -- `zify_proof` corrupts the tactic state when run under `io.run_tactic`. do l ← lock_tactic_state $ l.mmap $ λ h, infer_type h >>= guardb ∘ is_nat_prop >> zify_proof [] h <|> return h, nonnegs ← l.mfoldl (λ (es : expr_set) h, do (a, b) ← infer_type h >>= get_rel_sides, return $ (es.insert_list (get_nat_comps a)).insert_list (get_nat_comps b)) mk_rb_set, (++) l <$> nonnegs.to_list.mmap mk_coe_nat_nonneg_prf } /-- `strengthen_strict_int h` turns a proof `h` of a strict integer inequality `t1 < t2` into a proof of `t1 ≤ t2 + 1`. -/ meta def strengthen_strict_int : preprocessor := { name := "strengthen strict inequalities over int", transform := λ h, do tp ← infer_type h, guardb (is_strict_int_prop tp) >> singleton <$> mk_non_strict_int_pf_of_strict_int_pf h <|> return [h] } /-- `mk_comp_with_zero h` takes a proof `h` of an equality, inequality, or negation thereof, and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≤, <}`. -/ meta def make_comp_with_zero : preprocessor := { name := "make comparisons with zero", transform := λ e, singleton <$> rearr_comp e <|> return [] } /-- `normalize_denominators_in_lhs h lhs` assumes that `h` is a proof of `lhs R 0`. It creates a proof of `lhs' R 0`, where all numeric division in `lhs` has been cancelled. -/ meta def normalize_denominators_in_lhs (h lhs : expr) : tactic expr := do (v, lhs') ← cancel_factors.derive lhs, if v = 1 then return h else do (ih, h'') ← mk_single_comp_zero_pf v h, (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' /-- `cancel_denoms pf` assumes `pf` is a proof of `t R 0`. If `t` contains the division symbol `/`, it tries to scale `t` to cancel out division by numerals. -/ meta def cancel_denoms : preprocessor := { name := "cancel denominators", transform := λ pf, (do some (_, lhs) ← parse_into_comp_and_expr <$> infer_type pf, guardb $ lhs.contains_constant (= `has_div.div), singleton <$> normalize_denominators_in_lhs pf lhs) <|> return [pf] } /-- `find_squares m e` collects all terms of the form `a ^ 2` and `a * a` that appear in `e` and adds them to the set `m`. A pair `(a, tt)` is added to `m` when `a^2` appears in `e`, and `(a, ff)` is added to `m` when `a*a` appears in `e`. -/ meta def find_squares : rb_set (expr × bool) → expr → tactic (rb_set (expr × bool)) | s `(%%a ^ 2) := do s ← find_squares s a, return (s.insert (a, tt)) | s e@`(%%e1 * %%e2) := if e1 = e2 then do s ← find_squares s e1, return (s.insert (e1, ff)) else e.mfoldl find_squares s | s e := e.mfoldl find_squares s /-- `nlinarith_extras` is the preprocessor corresponding to the `nlinarith` tactic. * For every term `t` such that `t^2` or `t*t` appears in the input, adds a proof of `t^2 ≥ 0` or `t*t ≥ 0`. * For every pair of comparisons `t1 R1 0` and `t2 R2 0`, adds a proof of `t1*t2 R 0`. This preprocessor is typically run last, after all inputs have been canonized. -/ meta def nlinarith_extras : global_preprocessor := { name := "nonlinear arithmetic extras", transform := λ ls, do s ← ls.mfoldr (λ h s', infer_type h >>= find_squares s') mk_rb_set, new_es ← s.mfold ([] : list expr) $ λ ⟨e, is_sq⟩ new_es, ((do p ← mk_app (if is_sq then ``sq_nonneg else ``mul_self_nonneg) [e], return $ p::new_es) <|> return new_es), new_es ← make_comp_with_zero.globalize.transform new_es, linarith_trace "nlinarith preprocessing found squares", linarith_trace s, linarith_trace_proofs "so we added proofs" new_es, with_comps ← (new_es ++ ls).mmap (λ e, do tp ← infer_type e, return $ (parse_into_comp_and_expr tp).elim (ineq.lt, e) (λ ⟨ine, _⟩, (ine, e))), products ← with_comps.mmap_upper_triangle $ λ ⟨posa, a⟩ ⟨posb, b⟩, some <$> match posa, posb with | ineq.eq, _ := mk_app ``zero_mul_eq [a, b] | _, ineq.eq := mk_app ``mul_zero_eq [a, b] | ineq.lt, ineq.lt := mk_app ``mul_pos_of_neg_of_neg [a, b] | ineq.lt, ineq.le := do a ← mk_app ``le_of_lt [a], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] | ineq.le, ineq.lt := do b ← mk_app ``le_of_lt [b], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] | ineq.le, ineq.le := mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] end <|> return none, products ← make_comp_with_zero.globalize.transform products.reduce_option, return $ new_es ++ ls ++ products } /-- `remove_ne_aux` case splits on any proof `h : a ≠ b` in the input, turning it into `a < b ∨ a > b`. This produces `2^n` branches when there are `n` such hypotheses in the input. -/ meta def remove_ne_aux : list expr → tactic (list branch) := λ hs, (do e ← hs.mfind (λ e : expr, do e ← infer_type e, guard $ e.is_ne.is_some), [(_, ng1), (_, ng2)] ← to_expr ``(or.elim (lt_or_gt_of_ne %%e)) >>= apply, let do_goal : expr → tactic (list branch) := λ g, do set_goals [g], h ← intro1, ls ← remove_ne_aux $ hs.remove_all [e], return $ ls.map (λ b : branch, (b.1, h::b.2)) in (++) <$> do_goal ng1 <*> do_goal ng2) <|> do g ← get_goal, return [(g, hs)] /-- `remove_ne` case splits on any proof `h : a ≠ b` in the input, turning it into `a < b ∨ a > b`, by calling `linarith.remove_ne_aux`. This produces `2^n` branches when there are `n` such hypotheses in the input. -/ meta def remove_ne : global_branching_preprocessor := { name := "remove_ne", transform := remove_ne_aux } /-- The default list of preprocessors, in the order they should typically run. -/ meta def default_preprocessors : list global_branching_preprocessor := [filter_comparisons, remove_negations, nat_to_int, strengthen_strict_int, make_comp_with_zero, cancel_denoms] /-- `preprocess pps l` takes a list `l` of proofs of propositions. It maps each preprocessor `pp ∈ pps` over this list. The preprocessors are run sequentially: each recieves the output of the previous one. Note that a preprocessor may produce multiple or no expressions from each input expression, so the size of the list may change. -/ meta def preprocess (pps : list global_branching_preprocessor) (l : list expr) : tactic (list branch) := do g ← get_goal, pps.mfoldl (λ ls pp, list.join <$> (ls.mmap $ λ b, set_goals [b.1] >> pp.process b.2)) [(g, l)] end linarith
1a2158d832152614a7b86d2afd7bac2270466a87
618003631150032a5676f229d13a079ac875ff77
/src/order/filter/bases.lean
af2b2ef2ae2f564e15a8fd29502f1858be95a99a
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
28,582
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.basic import data.set.countable /-! # Filter bases A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`, the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p` (ie. `s '' set_of p`) defines a filter basis `h.filter_basis`. If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop` and `s : ι → set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and `l = h.filter_basis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. This file also introduces more restricted classes of bases, involving monotonicity or countability. In particular, for `l : filter α`, `l.is_countably_generated` means there is a countable set of sets which generates `s`. This is reformulated in term of bases, and consequences are derived. ## Main statements * `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `basis_sets` : all sets of a filter form a basis; * `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`, `has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ principal t`, `l.prod l'`, `l.prod l`, `l.map f`, `l.comap f` respectively; * `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate `tendsto f l l'` in terms of bases. * `is_countably_generated_iff_exists_antimono_basis` : proves a filter is countably generated if and only if it admis a basis parametrized by a decreasing sequence of sets indexed by `ℕ`. * `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous". ## Implementation notes As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases: * `has_basis l s`, `s : set (set α)`; * `has_basis l s`, `s : ι → set α`; * `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`. We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis of this form. The other two can be emulated using `s = id` or `p = λ _, true`. With this approach sometimes one needs to `simp` the statement provided by the `has_basis` machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help with the case `p = λ _, true`. -/ open set filter variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} {ι' : Type*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure filter_basis (α : Type*) := (sets : set (set α)) (nonempty : sets.nonempty) (inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩ -- For illustration purposes, the filter basis defining (at_top : filter ℕ) instance : inhabited (filter_basis ℕ) := ⟨{ sets := range Ici, nonempty := ⟨Ici 0, mem_range_self 0⟩, inter_sets := begin rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, refine ⟨Ici (max n m), mem_range_self _, _⟩, rintros p p_in, split ; rw mem_Ici at *, exact le_of_max_le_left p_in, exact le_of_max_le_right p_in, end }⟩ /-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/ protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop := (nonempty : ∃ i, p i) (inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j) namespace filter namespace is_basis /-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/ protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α := { sets := s '' set_of p, nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, mem_image_of_mem s hi⟩, inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩, rcases h.inter hi hj with ⟨k, hk, hk'⟩, exact ⟨_, mem_image_of_mem s hk, hk'⟩ } } variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s) lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U := iff.rfl end is_basis end filter namespace filter_basis /-- The filter associated to a filter basis. -/ protected def filter (B : filter_basis α) : filter α := { sets := {s | ∃ t ∈ B, t ⊆ s}, univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩, sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩, inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩, let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in ⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ } lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := iff.rfl lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:= λ U_in, ⟨U, U_in, subset.refl _⟩ lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, principal s := begin ext U, rw [mem_filter_iff, mem_infi], { simp }, { rintros ⟨U, U_in⟩ ⟨V, V_in⟩, rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩, use [W, W_in], finish }, cases B.nonempty with U U_in, exact ⟨⟨U, U_in⟩⟩, end protected lemma generate (B : filter_basis α) : generate B.sets = B.filter := begin apply le_antisymm, { intros U U_in, rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩, exact generate_sets.superset (generate_sets.basic V_in) h }, { rw sets_iff_generate, apply mem_filter_of_mem } end end filter_basis namespace filter namespace is_basis variables {p : ι → Prop} {s : ι → set α} /-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/ protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter protected lemma mem_filter_iff (h : is_basis p s) {U : set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := begin erw [h.filter_basis.mem_filter_iff], simp only [mem_filter_basis_iff h, exists_prop], split, { rintros ⟨_, ⟨i, pi, rfl⟩, h⟩, tauto }, { tauto } end lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} := by erw h.filter_basis.generate ; refl end is_basis /-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) section same_type variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} {p' : ι' → Prop} {s' : ι' → set α} {i' : ι'} lemma has_basis_generate (s : set (set α)) : (generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) := ⟨begin intro U, rw mem_generate_iff, apply exists_congr, tauto end⟩ /-- The smallest filter basis containing a given collection of sets. -/ def filter_basis.of_sets (s : set (set α)) : filter_basis α := { sets := sInter '' { t | finite t ∧ t ⊆ s}, nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩, inter_sets := begin rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩, exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨finite_union fina finb, union_subset suba subb⟩, by rw sInter_union⟩, end } /-- Definition of `has_basis` unfolded with implicit set argument. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl.mem_iff' t protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s := ⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩ lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl.mem_iff).2 ⟨i, hi, ht⟩ lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi $ subset.refl _ lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s := { nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, hi⟩, inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) } lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l := by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] } lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.is_basis.filter_eq_generate, h.filter_eq] lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) := by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s := by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff lemma has_basis.forall_nonempty_iff_ne_bot (hl : l.has_basis p s) : (∀ {i}, p i → (s i).nonempty) ↔ l ≠ ⊥ := ⟨λ H, forall_sets_nonempty_iff_ne_bot.1 $ λ s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in (H hi).mono his, λ H i hi, nonempty_of_mem_sets H (hl.mem_of_mem hi)⟩ lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := ⟨λ t, exists_sets_subset_iff.symm⟩ lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := ⟨λ t, by simpa only [exists_prop, true_and] using @mem_at_top_sets α _ _ t⟩ lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨λ h i' hi', h $ hl'.mem_of_mem hi', λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_sets_of_superset (h _ hi') hs⟩ theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] lemma has_basis.inf (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := ⟨begin intro t, simp only [mem_inf_sets, exists_prop, hl.mem_iff, hl'.mem_iff], split, { rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, H⟩, use [(i, i'), ⟨hi, hi'⟩, subset.trans (inter_subset_inter ht ht') H] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, use [s i, i, hi, subset.refl _, s' i', i', hi', subset.refl _, H] } end⟩ lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ principal s').has_basis p (λ i, s i ∩ s') := ⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq, mem_inter_iff, and_imp]⟩ lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), principal (s i) := eq_binfi_of_mem_sets_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal_sets] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, principal (s i) := by simpa only [infi_true] using h.eq_binfi @[nolint ge_or_gt] -- see Note [nolint_ge] lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) (ne : nonempty ι) : (⨅ i, principal (s i)).has_basis (λ _, true) s := ⟨begin refine λ t, (mem_infi (h.mono_comp _ _) ne t).trans $ by simp only [exists_prop, true_and, mem_principal_sets], exact λ _ _, principal_mono.2 end⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, principal (s i)).has_basis (λ i, i ∈ S) s := ⟨begin refine λ t, (mem_binfi _ ne).trans $ by simp only [mem_principal_sets], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end⟩ lemma has_basis.map (f : α → β) (hl : l.has_basis p s) : (l.map f).has_basis p (λ i, f '' (s i)) := ⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩ lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) : (l.comap f).has_basis p (λ i, f ⁻¹' (s i)) := ⟨begin intro t, simp only [mem_comap_sets, exists_prop, hl.mem_iff], split, { rintros ⟨t', ⟨i, hi, ht'⟩, H⟩, exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ } end⟩ lemma has_basis.prod_self (hl : l.has_basis p s) : (l.prod l).has_basis p (λ i, (s i).prod (s i)) := ⟨begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem_sets ht₁ ht₂) with ⟨i, hi, ht⟩, exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ } end⟩ lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) := ⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩, λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩ lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨λ H i hi, H (s i) $ hl.mem_of_mem hi, λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩ variables [preorder ι] (l p s) /-- `is_antimono_basis p s` means the image of `s` bounded by `p` is a filter basis such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure is_antimono_basis extends is_basis p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) /-- We say that a filter `l` has a antimono basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure has_antimono_basis [preorder ι] (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) end same_type section two_types variables {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) : tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl } lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := by simp only [tendsto, hlb.ge_iff, mem_map, filter.eventually] lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := by simp [hlb.tendsto_right_iff, hla.eventually_iff] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := hla.tendsto_left_iff.1 H lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) : ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := hlb.tendsto_right_iff.1 H lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := (hla.tendsto_iff hlb).1 H lemma has_basis.prod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la.prod lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := (hla.comap prod.fst).inf (hlb.comap prod.snd) lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := begin rw hl.to_has_basis.tendsto_right_iff, intros i hi, rw eventually_at_top, exact ⟨i, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩, end end two_types /-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/ def is_countably_generated (f : filter α) : Prop := ∃ s : set (set α), countable s ∧ f = generate s /-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/ structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop := (countable : countable $ set_of p) /-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set defined by `p` is countable. -/ structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (countable : countable $ set_of p) /-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure countable_filter_basis (α : Type*) extends filter_basis α := (countable : countable sets) -- For illustration purposes, the countable filter basis defining (at_top : filter ℕ) instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) := ⟨{ countable := countable_range (λ n, Ici n), ..(default $ filter_basis ℕ),}⟩ lemma antimono_seq_of_seq (s : ℕ → set α) : ∃ t : ℕ → set α, (∀ i j, i ≤ j → t j ⊆ t i) ∧ (⨅ i, principal $ s i) = ⨅ i, principal (t i) := begin use λ n, ⋂ m ≤ n, s m, split, { intros i j hij a, simp, intros h i' hi'i, apply h, transitivity; assumption }, apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, apply Inter_mem_sets (finite_le_nat _), intros j hji, rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl }, end lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B) (Bne : B.nonempty) (f : ι → α) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin rw countable_iff_exists_surjective_to_subtype Bne at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_refl _ }, { intros a, rcases gsurj a with i, apply infi_le_of_le i _, subst h, apply le_refl _ } end lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin cases B.eq_empty_or_nonempty with hB Bnonempty, { rw [hB, infi_emptyset], use λ n, i₀, simp [h] }, { exact countable_binfi_eq_infi_seq Bcbl Bnonempty f } end lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) : ∃ (x : ℕ → set α), (⨅ t ∈ B, principal t) = ⨅ i, principal (x i) := countable_binfi_eq_infi_seq' Bcbl principal principal_univ namespace is_countably_generated /-- A set generating a countably generated filter. -/ def generating_set {f : filter α} (h : is_countably_generated f) := classical.some h lemma countable_generating_set {f : filter α} (h : is_countably_generated f) : countable h.generating_set := (classical.some_spec h).1 lemma eq_generate {f : filter α} (h : is_countably_generated f) : f = generate h.generating_set := (classical.some_spec h).2 /-- A countable filter basis for a countably generated filter. -/ def countable_filter_basis {l : filter α} (h : is_countably_generated l) : countable_filter_basis α := { countable := (countable_set_of_finite_subset h.countable_generating_set).image _, ..filter_basis.of_sets (h.generating_set) } lemma filter_basis_filter {l : filter α} (h : is_countably_generated l) : h.countable_filter_basis.to_filter_basis.filter = l := begin conv_rhs { rw h.eq_generate }, apply of_sets_filter_eq_generate, end lemma has_countable_basis {l : filter α} (h : is_countably_generated l) : l.has_countable_basis (λ t, finite t ∧ t ⊆ h.generating_set) (λ t, ⋂₀ t) := ⟨by convert has_basis_generate _ ; exact h.eq_generate, countable_set_of_finite_subset h.countable_generating_set⟩ lemma exists_countable_infi_principal {f : filter α} (h : f.is_countably_generated) : ∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, principal t := begin let B := h.countable_filter_basis, use [B.sets, B.countable], rw ← h.filter_basis_filter, rw B.to_filter_basis.eq_infi_principal, rw infi_subtype'' end lemma exists_seq {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, f = ⨅ i, principal (x i) := begin rcases cblb.exists_countable_infi_principal with ⟨B, Bcbl, rfl⟩, exact countable_binfi_principal_eq_seq_infi Bcbl, end lemma exists_antimono_seq {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ f = ⨅ i, principal (x i) := begin rcases cblb.exists_seq with ⟨x', hx'⟩, let x := λ n, ⋂ m ≤ n, x' m, use x, split, { intros i j hij a, simp [x], intros h i' hi'i, apply h, transitivity; assumption }, subst hx', apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, apply Inter_mem_sets (finite_le_nat _), intros j hji, rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp [x], intro h, apply h, refl }, end lemma has_antimono_basis {f : filter α} (h : f.is_countably_generated) : ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := begin rcases h.exists_antimono_seq with ⟨x, x_dec, rfl⟩, use x, constructor, apply has_basis_infi_principal, apply directed_of_mono, apply x_dec, use 0, simpa using x_dec, exact monotone_const end end is_countably_generated lemma is_countably_generated_seq (x : ℕ → set α) : is_countably_generated (⨅ i, principal $ x i) := begin rcases antimono_seq_of_seq x with ⟨y, am, h⟩, rw h, use [range y, countable_range _], rw (has_basis_infi_principal _ _).eq_generate, { simp [range] }, { apply directed_of_mono, apply am }, { use 0 }, end lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, principal $ x i) : f.is_countably_generated := let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) : is_countably_generated (⨅ (s ∈ B), principal s) := is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h) lemma is_countably_generated_iff_exists_antimono_basis {f : filter α} : is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := begin split, { intro h, exact h.has_antimono_basis }, { rintros ⟨x, h⟩, rw h.to_has_basis.eq_infi, exact is_countably_generated_seq x }, end namespace is_countably_generated lemma exists_antimono_seq' {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) := let ⟨x, hx⟩ := is_countably_generated_iff_exists_antimono_basis.mp cblb in ⟨x, λ i j, hx.decreasing trivial trivial, λ s, by simp [hx.to_has_basis.mem_iff]⟩ protected lemma comap {l : filter β} (h : l.is_countably_generated) (f : α → β) : (comap f l).is_countably_generated := begin rcases h.exists_seq with ⟨x, hx⟩, apply is_countably_generated_of_seq, use λ i, f ⁻¹' x i, calc comap f l = comap f (⨅ i, principal (x i)) : by rw hx ... = (⨅ i, comap f $ principal $ x i) : comap_infi ... = (⨅ i, principal $ f ⁻¹' x i) : by simp_rw comap_principal, end /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_seq with ⟨g, gmon, gbasis⟩, have gbasis : ∀ A, A ∈ k ↔ ∃ i, g i ⊆ A, { intro A, subst gbasis, rw mem_infi, { simp only [set.mem_Union, iff_self, filter.mem_principal_sets] }, { exact directed_of_mono _ (λ i j h, principal_mono.mpr $ gmon _ _ h) }, { apply_instance } }, classical, contrapose, simp only [not_forall, not_imp, not_exists, subset_def, @tendsto_def _ _ f, gbasis], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { simp only [tendsto_at_top', gbasis], rintros A ⟨i, hgiA⟩, use i, refine (λ j hj, hgiA $ gmon _ _ hj _), simp only [h] }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 end is_countably_generated -- TODO : prove this for a encodable type lemma is_countably_generated_at_top_finset_nat : (at_top : filter $ finset ℕ).is_countably_generated := begin apply is_countably_generated_of_seq, use λ N, Ici (finset.range N), apply eq_infi_of_mem_sets_iff_exists_mem, assume s, rw mem_at_top_sets, refine ⟨_, λ ⟨N, hN⟩, ⟨finset.range N, hN⟩⟩, rintros ⟨t, ht⟩, rcases mem_at_top_sets.1 (tendsto_finset_range (mem_at_top t)) with ⟨N, hN⟩, simp only [preimage, mem_set_of_eq] at hN, exact ⟨N, mem_principal_sets.2 $ λ t' ht', ht t' $ le_trans (hN _ $ le_refl N) ht'⟩ end end filter
c244caf5d26ef83b3deedfd4054bd0e40843ca69
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/subring.lean
8b691300b165051fb532d72bd72db492d313665c
[ "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
30,862
lean
/- Copyright (c) 2020 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors : Ashvni Narayanan -/ import deprecated.subring import group_theory.subgroup import ring_theory.subsemiring /-! # Subrings Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type whose terms correspond to subrings of `R`. This is the preferred way to talk about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`) are not in this file, and they will ultimately be deprecated. We prove that subrings are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subring R`, sending a subset of `R` to the subring it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)` `(A : subring R) (B : subring S) (s : set R)` * `subring R` : the type of subrings of a ring `R`. * `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings. * `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set. * `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M` form a `galois_insertion`. * `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f` * `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`. * `prod A B : subring (R × S)` : the product of subrings * `f.range : subring B` : the range of the ring homomorphism `f`. * `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`, the subring of `R` where `f x = g x` ## Implementation notes A subring is implemented as a subsemiring which is also an additive subgroup. The initial PR was as a submonoid which is also an additive subgroup. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subring's underlying set. ## Tags subring, subrings -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T] set_option old_structure_cmd true /-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R /-- Reinterpret a `subring` as a `subsemiring`. -/ add_decl_doc subring.to_subsemiring /-- Reinterpret a `subring` as an `add_subgroup`. -/ add_decl_doc subring.to_add_subgroup namespace subring /-- The underlying submonoid of a subring. -/ def to_submonoid (s : subring R) : submonoid R := { carrier := s.carrier, ..s.to_subsemiring.to_submonoid } instance : has_coe (subring R) (set R) := ⟨subring.carrier⟩ instance : has_coe_to_sort (subring R) := ⟨Type*, λ S, S.carrier⟩ instance : has_mem R (subring R) := ⟨λ m S, m ∈ (S:set R)⟩ /-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R) (hm : ↑sm = s) (ha : ↑sa = s) : subring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem, neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) {x : R} : x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha).to_submonoid = sm := submonoid.ext' hm.symm @[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa =s) : (subring.mk' s sm sa hm ha).to_add_subgroup = sa := add_subgroup.ext' ha.symm end subring /-- Construct a `subring` from a set satisfying `is_subring`. -/ def set.to_subring (S : set R) [is_subring S] : subring R := { carrier := S, one_mem' := is_submonoid.one_mem, mul_mem' := λ a b, is_submonoid.mul_mem, zero_mem' := is_add_submonoid.zero_mem, add_mem' := λ a b, is_add_submonoid.add_mem, neg_mem' := λ a, is_add_subgroup.neg_mem } protected lemma subring.exists {s : subring R} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.exists protected lemma subring.forall {s : subring R} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.forall /-- A `subsemiring` containing -1 is a `subring`. -/ def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R := { neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, } ..s.to_submonoid, ..s.to_add_submonoid } namespace subring variables (s : subring R) /-- Two subrings are equal if the underlying subsets are equal. -/ theorem ext' ⦃s t : subring R⦄ (h : (s : set R) = t) : s = t := by { cases s, cases t, congr' } /-- Two subrings are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {s t : subring R} : s = t ↔ (s : set R) = t := ⟨λ h, h ▸ rfl, λ h, ext' h⟩ /-- Two subrings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h /-- A subring contains the ring's 1. -/ theorem one_mem : (1 : R) ∈ s := s.one_mem' /-- A subring contains the ring's 0. -/ theorem zero_mem : (0 : R) ∈ s := s.zero_mem' /-- A subring is closed under multiplication. -/ theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem' /-- A subring is closed under addition. -/ theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem' /-- A subring is closed under negation. -/ theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem' /-- A subring is closed under subtraction -/ theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s := by { rw sub_eq_add_neg, exact s.add_mem hx (s.neg_mem hy) } /-- Product of a list of elements in a subring is in the subring. -/ lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := s.to_submonoid.list_prod_mem /-- Sum of a list of elements in a subring is in the subring. -/ lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := s.to_add_subgroup.list_sum_mem /-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/ lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := s.to_submonoid.multiset_prod_mem m /-- Sum of a multiset of elements in an `subring` of a `ring` is in the `subring`. -/ lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := s.to_add_subgroup.multiset_sum_mem m /-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the subring. -/ lemma prod_mem {R : Type*} [comm_ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := s.to_submonoid.prod_mem h /-- Sum of elements in a `subring` of a `ring` indexed by a `finset` is in the `subring`. -/ lemma sum_mem {R : Type*} [ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := s.to_add_subgroup.sum_mem h lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n lemma gsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) : n •ℤ x ∈ s := s.to_add_subgroup.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : R) ∈ s := by simp only [← gsmul_one, gsmul_mem, one_mem] /-- A subring of a ring inherits a ring structure -/ instance to_ring : ring s := { right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, .. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl @[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 := ⟨λ h, subtype.ext (trans h s.coe_zero.symm), λ h, h.symm ▸ s.coe_zero⟩ /-- A subring of a `comm_ring` is a `comm_ring`. -/ instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s} /-- The natural ring hom from a subring of ring `R` to `R`. -/ def subtype (s : subring R) : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl /-! # Partial order -/ instance : partial_order (subring R) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, .. partial_order.lift (coe : subring R → set R) ext' } lemma le_def {s t : subring R} : s ≤ t ↔ ∀ ⦃x : R⦄, x ∈ s → x ∈ t := iff.rfl @[simp, norm_cast] lemma coe_subset_coe {s t : subring R} : (s : set R) ⊆ t ↔ s ≤ t := iff.rfl @[simp, norm_cast] lemma coe_ssubset_coe {s t : subring R} : (s : set R) ⊂ t ↔ s < t := iff.rfl @[simp, norm_cast] lemma mem_coe {S : subring R} {m : R} : m ∈ (S : set R) ↔ m ∈ S := iff.rfl @[simp, norm_cast] lemma coe_coe (s : subring R) : ↥(s : set R) = s := rfl @[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} : x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl /-! # top -/ /-- The subring `R` of the ring `R`. -/ instance : has_top (subring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl /-! # comap -/ /-- The preimage of a subring along a ring homomorphism is a subring. -/ def comap {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) : subring R := { carrier := f ⁻¹' s.carrier, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_subgroup.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-! # map -/ /-- The image of a subring along a ring homomorphism is a subring. -/ def map {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring R) : subring S := { carrier := f '' s.carrier, .. s.to_submonoid.map (f : R →* S), .. s.to_add_subgroup.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := ext' $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap end subring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-! # range -/ /-- The range of a ring homomorphism, as a subring of the target. -/ def range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : subring S := (⊤ : subring R).map f @[simp] lemma coe_range : (f.range : set S) = set.range f := set.image_univ @[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y := by simp [range] lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range := mem_range.mpr ⟨x, rfl⟩ lemma map_range : f.range.map g = (g.comp f).range := (⊤ : subring R).map_map g f -- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } lemma surjective_onto_range : function.surjective (f.cod_restrict' f.range f.mem_range_self) := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩ end ring_hom namespace subring variables {cR : Type u} [comm_ring cR] /-- A subring of a commutative ring is a commutative ring. -/ def subset_comm_ring (S : subring cR) : comm_ring S := {mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring S} /-- A subring of an integral domain is an integral domain. -/ instance subring.domain {D : Type*} [integral_domain D] (S : subring D) : integral_domain S := { exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.1 zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨x, hx⟩ ⟨y, hy⟩, by { simp only [subtype.ext_iff_val, subtype.coe_mk], exact eq_zero_or_eq_zero_of_mul_eq_zero }, .. S.subset_comm_ring, } /-! # bot -/ instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩ instance : inhabited (subring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) := ring_hom.coe_range (int.cast_ring_hom R) lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x := ring_hom.mem_range /-! # inf -/ /-- The inf of two subrings is their intersection. -/ instance : has_inf (subring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩ @[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subring R) := ⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t ) (⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subring R)) : ((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] lemma Inf_to_submonoid (s : set (subring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_subgroup (s : set (subring R)) : (Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _ /-- Subrings of a ring form a complete lattice. -/ instance : complete_lattice (subring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from coe_subset_coe) is_glb_binfi)} /-! # subring closure of a subset -/ /-- The `subring` generated by a set. -/ def closure (s : set R) : subring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S := mem_Inf /-- The subring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx /-- A subring `t` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ (x : R), p x → p (-x)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) := ⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx ) (add_subgroup.zero_mem _) (add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) ) (λ x y hx hy, add_subgroup.add_mem _ hx hy ) (λ x hx, add_subgroup.neg_mem _ hx ) ( λ x y hx hy, add_subgroup.closure_induction hy (λ q hq, add_subgroup.closure_induction hx ( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) ) ( begin rw zero_mul q, apply add_subgroup.zero_mem _, end ) ( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end ) ( λ x hx, begin have f : -x * q = -(x*q) := by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) ) ( begin rw mul_zero x, apply add_subgroup.zero_mem _, end ) ( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end ) ( λ z hz, begin have f : x * -z = -(x*z) := by simp, rw f, apply add_subgroup.neg_mem _ hz, end ) ), λ h, add_subgroup.closure_induction h ( λ x hx, submonoid.closure_induction hx ( λ x hx, subset_closure hx ) ( one_mem _ ) ( λ x y hx hy, mul_mem _ hx hy ) ) ( zero_mem _ ) (λ x y hx hy, add_mem _ hx hy) ( λ x hx, neg_mem _ hx ) ⟩ theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) : (∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) := add_subgroup.closure_induction (mem_closure_iff.1 h) (λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h]; clear_aux_decl; tauto!⟩) ⟨[], by simp⟩ (λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t), by simp [hl2, hm2]⟩) (λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2 ⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp) (by simp [list.map_cons, add_comm] {contextual := tt})⟩) variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subring `S` equals `S`. -/ lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subring.gi R).gc.l_Sup lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s × t` as a subring of `R × S`. -/ def prod (s : subring R) (t : subring S) : subring (R × S) := { carrier := (s : set R).prod t, .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup} @[norm_cast] lemma coe_prod (s : subring R) (t : subring S) : (s.prod t : set (R × S)) = (s : set R).prod (t : set S) := rfl lemma mem_prod {s : subring R} {t : subring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subring R) : s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subring S) : (⊤ : subring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subrings is isomorphic to their product as rings. -/ def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } /-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings. Note that this fails without the directedness assumption (the union of two subrings is typically not a subring) -/ lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩, let U : subring R := subring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) : ((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subring namespace ring_hom variables [ring T] {s : subring R} open subring /-- Restriction of a ring homomorphism to a subring of the domain. -/ def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype @[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. -/ def range_restrict (f : R →+* S) : R →+* f.range := f.cod_restrict' f.range $ λ x, ⟨x, subring.mem_top x, rfl⟩ @[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl lemma range_top_iff_surjective {f : R →+* S} : f.range = (⊤ : subring S) ↔ function.surjective f := subring.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.range = (⊤ : subring S) := range_top_iff_surjective.2 hf /-- The subring of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subring of R -/ def eq_locus (f g : R →+* S) : subring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/ lemma eq_on_set_closure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from closure_le.2 h lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subring generated by a set equals the subring generated by the image of the set. -/ lemma map_closure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subring open ring_hom /-- The ring homomorphism associated to an inclusion of subrings. -/ def inclusion {S T : subring R} (h : S ≤ T) : S →* T := S.subtype.cod_restrict' _ (λ x, h x.2) @[simp] lemma range_subtype (s : subring R) : s.subtype.range = s := ext' $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨mem_coe.2 $ one_mem ⊥, hp.2⟩) end subring namespace ring_equiv variables {s t : subring R} /-- Makes the identity isomorphism from a proof two subrings of a multiplicative monoid are equal. -/ def subring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ subring.ext'_iff.1 h } end ring_equiv namespace subring variables {s : set R} local attribute [reducible] closure @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx end subring lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) : (k : R) * g ∈ G := by { convert add_subgroup.gsmul_mem G h k, simp }
a757b1cb69efd78470ea54f9ce303ce63d0dabbd
bdb33f8b7ea65f7705fc342a178508e2722eb851
/analysis/topology/continuity.lean
ffea2905d7f590d276b32bf327d481e5bdde5663
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
36,711
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 Continuous functions. Parts of the formalization is based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import analysis.topology.topological_space noncomputable theory open set filter lattice local attribute [instance] classical.prop_decidable universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type y} {ι : Sort x} section variables [topological_space α] [topological_space β] [topological_space γ] /-- A function between topological spaces is continuous if the preimage of every open set is open. -/ def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s) lemma continuous_id : continuous (id : α → α) := assume s h, h lemma continuous.comp {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g): continuous (g ∘ f) := assume s h, hf _ (hg s h) lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (nhds x) (nhds (f x)) | s := show s ∈ (nhds (f x)).sets → s ∈ (map f (nhds x)).sets, by simp [nhds_sets]; exact assume t t_subset t_open fx_in_t, ⟨f ⁻¹' t, preimage_mono t_subset, hf t t_open, fx_in_t⟩ lemma continuous_iff_tendsto {f : α → β} : continuous f ↔ (∀x, tendsto f (nhds x) (nhds (f x))) := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (nhds x) (nhds (f x)), assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ (nhds (f a)).sets, by simp [nhds_sets]; exact assume a ha, ⟨s, subset.refl s, hs, ha⟩, show is_open (f ⁻¹' s), by simp [is_open_iff_nhds]; exact assume a ha, hf a (this a ha)⟩ lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_tendsto.mpr $ assume a, tendsto_const_nhds lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, hf (-s) hs, assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)} (hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λa, @ite (p a) (h a) β (f a) (g a)) := continuous_iff_is_closed.mpr $ assume s hs, have (λa, ite (p a) (f a) (g a)) ⁻¹' s = (closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s), from set.ext $ assume a, classical.by_cases (assume : a ∈ frontier {a | p a}, have hac : a ∈ closure {a | p a}, from this.left, have hai : a ∈ closure {a | ¬ p a}, from have a ∈ - interior {a | p a}, from this.right, by rwa [←closure_compl] at this, by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt}) (assume hf : a ∈ - frontier {a | p a}, classical.by_cases (assume : p a, have hc : a ∈ closure {a | p a}, from subset_closure this, have hnc : a ∉ closure {a | ¬ p a}, by show a ∉ closure (- {a | p a}); rw [closure_compl]; simpa [frontier, hc] using hf, by simp [this, hc, hnc]) (assume : ¬ p a, have hc : a ∈ closure {a | ¬ p a}, from subset_closure this, have hnc : a ∉ closure {a | p a}, begin have hc : a ∈ closure (- {a | p a}), from hc, simp [closure_compl] at hc, simpa [frontier, hc] using hf end, by simp [this, hc, hnc])), by rw [this]; exact is_closed_union (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs) (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs) lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := have ∀ (a : α), nhds a ⊓ principal s ≠ ⊥ → nhds (f a) ⊓ principal (f '' s) ≠ ⊥, from assume a ha, have h₁ : ¬ map f (nhds a ⊓ principal s) = ⊥, by rwa[map_eq_bot_iff], have h₂ : map f (nhds a ⊓ principal s) ≤ nhds (f a) ⊓ principal (f '' s), from le_inf (le_trans (map_mono inf_le_left) $ by rw [continuous_iff_tendsto] at h; exact h a) (le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _), neq_bot_of_le_neq_bot h₁ h₂, by simp [image_subset_iff, closure_eq_nhds]; assumption lemma compact_image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) : compact (f '' s) := compact_of_finite_subcover $ assume c hco hcs, have hdo : ∀t∈c, is_open (f ⁻¹' t), from assume t' ht, hf _ $ hco _ ht, have hds : s ⊆ ⋃i∈c, f ⁻¹' i, by simpa [subset_def, -mem_image] using hcs, let ⟨d', hcd', hfd', hd'⟩ := compact_elim_finite_subcover_image hs hdo hds in ⟨d', hcd', hfd', by simpa [subset_def, -mem_image, image_subset_iff] using hd'⟩ end section constructions local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variable {f : α → β} lemma continuous_iff_induced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ induced f t₂ ≤ t₁ := ⟨assume hc s ⟨t, ht, s_eq⟩, s_eq.symm ▸ hc t ht, assume hle s h, hle _ ⟨_, h, rfl⟩⟩ lemma continuous_iff_le_coinduced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₂ ≤ coinduced f t₁ := iff.rfl theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := assume s hs, generate_open.rec_on hs h is_open_univ (assume s t _ _, is_open_inter) (assume t _ h, by rw [preimage_sUnion]; exact (is_open_Union $ assume s, is_open_Union $ assume hs, h s hs)) lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := assume s h, ⟨_, h, rfl⟩ lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := assume s ⟨t, ht, s_eq⟩, s_eq.symm ▸ h t ht lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := assume s h, h lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := assume s hs, h s hs lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₁ ≤ t₂) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := assume s h, h₁ _ (h₂ s h) lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₃ ≤ t₂) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := assume s h, h₂ s (h₁ s h) lemma continuous_inf_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊓ t₂) t₃ f := assume s h, ⟨h₁ s h, h₂ s h⟩ lemma continuous_inf_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊓ t₃) f := continuous_le_rng inf_le_left lemma continuous_inf_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊓ t₃) f := continuous_le_rng inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Inf t₁) t₂ f := assume s hs t ht, h t ht s hs lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Inf t₂) f := assume s hs, hf s $ hs t h₁ lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (infi t₁) t₂ f := continuous_Inf_dom $ assume t ⟨i, (t_eq : t = t₁ i)⟩, t_eq.symm ▸ h i lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_Inf_rng ⟨i, rfl⟩ h lemma continuous_top {t : tspace β} : cont ⊤ t f := assume s h, trivial lemma continuous_bot {t : tspace α} : cont t ⊥ f := continuous_Inf_rng (mem_univ $ coinduced f t) continuous_coinduced_rng lemma continuous_sup_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊔ t₃) f := continuous_Inf_rng (show t₂ ≤ coinduced f t₁ ∧ t₃ ≤ coinduced f t₁, from ⟨h₁, h₂⟩) continuous_coinduced_rng lemma continuous_sup_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊔ t₂) t₃ f := continuous_le_dom le_sup_left lemma continuous_sup_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊔ t₂) t₃ f := continuous_le_dom le_sup_right end constructions section embedding lemma induced_mono {t₁ t₂ : topological_space α} {f : β → α} (h : t₁ ≤ t₂) : t₁.induced f ≤ t₂.induced f := continuous_iff_induced_le.mp $ show @continuous β α (@topological_space.induced β α f t₂) t₁ (id ∘ f), begin apply continuous.comp, exact continuous_induced_dom, exact assume s hs, h _ hs end lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h.symm ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tβ : topological_space β] [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁.symm ▸ h₂.symm ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma induced_sup (t₁ : topological_space β) (t₂ : topological_space β) {f : α → β} : (t₁ ⊔ t₂).induced f = t₁.induced f ⊔ t₂.induced f := le_antisymm (continuous_iff_induced_le.mp $ continuous_sup_rng (continuous_sup_dom_left continuous_induced_dom) (continuous_sup_dom_right continuous_induced_dom)) (sup_le (induced_mono le_sup_left) (induced_mono le_sup_right)) /-- A function between topological spaces is an embedding if it is injective, and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/ def embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.injective f ∧ tα = tβ.induced f variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma embedding_id : embedding (@id α) := ⟨assume a₁ a₂ h, h, induced_id.symm⟩ lemma embedding_compose {f : α → β} {g : β → γ} (hf : embedding f) (hg : embedding g) : embedding (g ∘ f) := ⟨assume a₁ a₂ h, hf.left $ hg.left h, by rw [hf.right, hg.right, induced_compose]⟩ lemma embedding_prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := ⟨assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.left h₁, hg.left h₂⟩, by rw [prod.topological_space, prod.topological_space, hf.right, hg.right, induced_compose, induced_compose, induced_sup, induced_compose, induced_compose]⟩ lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : embedding (g ∘ f)) : embedding f := ⟨assume a₁ a₂ h, hgf.left $ by simp [h, (∘)], le_antisymm (by rw [hgf.right, ← continuous_iff_induced_le]; apply continuous_induced_dom.comp hg) (by rwa ← continuous_iff_induced_le)⟩ lemma embedding_open {f : α → β} {s : set α} (hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.right] at hs; exact hs in have is_open (t ∩ range f), from is_open_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma embedding_is_closed {f : α → β} {s : set α} (hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.right, is_closed_induced_iff] at hs; exact hs in have is_closed (t ∩ range f), from is_closed_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] end embedding section sierpinski variables [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from h _ is_open_singleton_true, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ end sierpinski section induced open topological_space variables [t : topological_space β] {f : α → β} theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma nhds_induced_eq_vmap {a : α} : @nhds α (induced f t) a = vmap f (nhds (f a)) := le_antisymm (assume s ⟨s', hs', (h_s : f ⁻¹' s' ⊆ s)⟩, let ⟨t', hsub, ht', hin⟩ := mem_nhds_sets_iff.1 hs' in (@nhds α (induced f t) a).upwards_sets begin simp [mem_nhds_sets_iff], exact ⟨preimage f t', preimage_mono hsub, is_open_induced ht', hin⟩ end h_s) (le_infi $ assume s, le_infi $ assume ⟨as, s', is_open_s', s_eq⟩, begin simp [vmap, mem_nhds_sets_iff, s_eq], exact ⟨s', ⟨s', subset.refl _, is_open_s', by rwa [s_eq] at as⟩, subset.refl _⟩ end) lemma map_nhds_induced_eq {a : α} (h : image f univ ∈ (nhds (f a)).sets) : map f (@nhds α (induced f t) a) = nhds (f a) := le_antisymm (@continuous.tendsto α β (induced f t) _ _ continuous_induced_dom a) (assume s, assume hs : f ⁻¹' s ∈ (@nhds α (induced f t) a).sets, let ⟨t', t_subset, is_open_t, a_in_t⟩ := mem_nhds_sets_iff.mp h in let ⟨s', s'_subset, ⟨s'', is_open_s'', s'_eq⟩, a_in_s'⟩ := (@mem_nhds_sets_iff _ (induced f t) _ _).mp hs in by subst s'_eq; exact (mem_nhds_sets_iff.mpr $ ⟨t' ∩ s'', assume x ⟨h₁, h₂⟩, match x, h₂, t_subset h₁ with | x, h₂, ⟨y, _, y_eq⟩ := begin subst y_eq, exact s'_subset h₂ end end, is_open_inter is_open_t is_open_s'', ⟨a_in_t, a_in_s'⟩⟩)) lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} (hf : ∀x y, f x = f y → x = y) : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := have vmap f (nhds (f a) ⊓ principal (f '' s)) ≠ ⊥ ↔ nhds (f a) ⊓ principal (f '' s) ≠ ⊥, from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ vmap_bot, assume h, forall_sets_neq_empty_iff_neq_bot.mp $ assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩, have f '' s ∈ (nhds (f a) ⊓ principal (f '' s)).sets, from mem_inf_sets_of_right $ by simp [subset.refl], have s₂ ∩ f '' s ∈ (nhds (f a) ⊓ principal (f '' s)).sets, from inter_mem_sets hs₂ this, let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := inhabited_of_mem_sets h this in ne_empty_of_mem $ hs $ by rwa [←ha₂] at hb₁⟩, calc a ∈ @closure α (topological_space.induced f t) s ↔ (@nhds α (topological_space.induced f t) a) ⊓ principal s ≠ ⊥ : by rw [closure_eq_nhds]; refl ... ↔ vmap f (nhds (f a)) ⊓ principal (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced_eq_vmap, preimage_image_eq _ hf] ... ↔ vmap f (nhds (f a) ⊓ principal (f '' s)) ≠ ⊥ : by rw [vmap_inf, ←vmap_principal] ... ↔ _ : by rwa [closure_eq_nhds] end induced section prod open topological_space variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_fst : continuous (@prod.fst α β) := continuous_sup_dom_left continuous_induced_dom lemma continuous_snd : continuous (@prod.snd α β) := continuous_sup_dom_right continuous_induced_dom lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) := continuous_sup_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : nhds (a, b) = filter.prod (nhds a) (nhds b) := by rw [filter.prod, prod.topological_space, nhds_sup, nhds_induced_eq_vmap, nhds_induced_eq_vmap] lemma prod_generate_from_generate_from_eq {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (sup_le (induced_le_iff_le_coinduced.mpr $ generate_from_le $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (induced_le_iff_le_coinduced.mpr $ generate_from_le $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) (generate_from_le $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) lemma prod_eq_generate_from [tα : topological_space α] [tβ : topological_space β] : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (sup_le (assume s ⟨t, ht, s_eq⟩, have set.prod t univ = s, by simp [s_eq, preimage, set.prod], this ▸ (generate_open.basic _ ⟨t, univ, ht, is_open_univ, rfl⟩)) (assume s ⟨t, ht, s_eq⟩, have set.prod univ t = s, by simp [s_eq, preimage, set.prod], this ▸ (generate_open.basic _ ⟨univ, t, is_open_univ, ht, rfl⟩))) (generate_from_le $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (nhds a) (nhds b) ⊓ principal (set.prod s t) = filter.prod (nhds a ⊓ principal s) (nhds b ⊓ principal t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_neq_bot lemma is_closed_prod [topological_space α] [topological_space β] {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed] lemma is_closed_diagonal [topological_space α] [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_neq_bot $ assume : nhds a₁ ⊓ nhds a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.upwards_sets, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end lemma is_closed_eq [topological_space α] [t2_space α] [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ end prod section sum variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_inl : continuous (@sum.inl α β) := continuous_inf_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@sum.inr α β) := continuous_inf_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_inf_dom hf hg end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding.tendsto_nhds_iff {f : α → β} {g : β → γ} {a : filter α} {b : β} (hg : embedding g) : tendsto f a (nhds b) ↔ tendsto (g ∘ f) a (nhds (g b)) := by rw [tendsto, tendsto, hg.right, nhds_induced_eq_vmap, ← map_le_iff_le_vmap, map_map] lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) : continuous f ↔ continuous (g ∘ f) := by simp [continuous_iff_tendsto, @embedding.tendsto_nhds_iff α β γ _ _ _ f g _ _ hg] lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id lemma embedding_subtype_val : embedding (@subtype.val α p) := ⟨assume a₁ a₂, subtype.eq, rfl⟩ lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ (nhds a).sets) : map (@subtype.val α p) (nhds ⟨a, ha⟩) = nhds a := map_nhds_induced_eq (by simp [subtype_val_image, h]) lemma nhds_subtype_eq_vmap {a : α} {h : p a} : nhds (⟨a, h⟩ : subtype p) = vmap subtype.val (nhds a) := nhds_induced_eq_vmap lemma continuous_subtype_nhds_cover {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ (nhds x).sets) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_tendsto.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ (nhds x).sets)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (nhds x) = map f (map subtype.val (nhds x')) : congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x.val) (nhds x') : rfl ... ≤ nhds (f x) : continuous_iff_tendsto.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {f : α → β} (c : γ → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_val (by simp [subtype_val_range]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : γ), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simp [and.comm, and.left_comm], simpa [(∘)], end, by rwa [this] lemma closure_subtype {p : α → Prop} {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) := closure_induced $ assume x y, subtype.eq end subtype section pi lemma nhds_pi {ι : Type u} {α : ι → Type v} [t : ∀i, topological_space (α i)] {a : Πi, α i} : nhds a = (⨅i, vmap (λx, x i) (nhds (a i))) := calc nhds a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, α i, x i) (t i)) a) : nhds_supr ... = (⨅i, vmap (λx, x i) (nhds (a i))) : by simp [nhds_induced_eq_vmap] /-- Tychonoff's theorem -/ lemma compact_pi_infinite {ι : Type v} {α : ι → Type u} [∀i:ι, topological_space (α i)] {s : Πi:ι, set (α i)} : (∀i, compact (s i)) → compact {x : Πi:ι, α i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (α i) := λi, map (λx:Πi:ι, α i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ nhds a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, α i, x i) ⁻¹' s i ∈ f.sets, from f.upwards_sets hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_vmap.mp $ (ha i).right⟩ end end pi -- TODO: use embeddings from above! structure dense_embedding [topological_space α] [topological_space β] (e : α → β) : Prop := (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (induced : ∀a, vmap e (nhds (e a)) = nhds a) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (H : ∀ (a:α) s ∈ (nhds a).sets, ∃t ∈ (nhds (e a)).sets, ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := ⟨dense, inj, λ a, le_antisymm (by simpa [le_def] using H a) (tendsto_iff_vmap.1 $ c.tendsto _)⟩ namespace dense_embedding variables [topological_space α] [topological_space β] variables {e : α → β} (de : dense_embedding e) protected lemma embedding (de : dense_embedding e) : embedding e := ⟨de.inj, eq_of_nhds_eq_nhds begin intro a, rw [← de.induced a, nhds_induced_eq_vmap] end⟩ protected lemma tendsto (de : dense_embedding e) {a : α} : tendsto e (nhds a) (nhds (e a)) := by rw [←de.induced a]; exact tendsto_vmap protected lemma continuous (de : dense_embedding e) {a : α} : continuous e := continuous_iff_tendsto.2 $ λ a, de.tendsto lemma inj_iff (de : dense_embedding e) {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma closure_range : closure (range e) = univ := let h := de.dense in set.ext $ assume x, ⟨assume _, trivial, assume _, @h x⟩ protected lemma nhds_inf_neq_bot (de : dense_embedding e) {b : β} : nhds b ⊓ principal (range e) ≠ ⊥ := begin have h := de.dense, simp [closure_eq_nhds] at h, exact h _ end lemma vmap_nhds_neq_bot (de : dense_embedding e) {b : β} : vmap e (nhds b) ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, (hs : e ⁻¹' t ⊆ s)⟩, have t ∩ range e ∈ (nhds b ⊓ principal (range e)).sets, from inter_mem_inf_sets ht (subset.refl _), let ⟨_, ⟨hx₁, y, rfl⟩⟩ := inhabited_of_mem_sets de.nhds_inf_neq_bot this in subset_ne_empty hs $ ne_empty_of_mem hx₁ variables [topological_space γ] [inhabited γ] [regular_space γ] /-- If `e : α → β` is a dense embedding, then any function `α → γ` extends to a function `β → γ`. -/ def ext (de : dense_embedding e) (f : α → γ) : β → γ := lim ∘ map f ∘ vmap e ∘ nhds lemma ext_eq {b : β} {c : γ} {f : α → γ} (hf : map f (vmap e (nhds b)) ≤ nhds c) : de.ext f b = c := lim_eq begin simp; exact vmap_nhds_neq_bot de end hf lemma ext_e_eq {a : α} {f : α → γ} (de : dense_embedding e) (hf : map f (nhds a) ≤ nhds (f a)) : de.ext f (e a) = f a := de.ext_eq begin rw de.induced; exact hf end lemma tendsto_ext {b : β} {f : α → γ} (de : dense_embedding e) (hf : {b | ∃c, tendsto f (vmap e $ nhds b) (nhds c)} ∈ (nhds b).sets) : tendsto (de.ext f) (nhds b) (nhds (de.ext f b)) := let φ := {b | tendsto f (vmap e $ nhds b) (nhds $ de.ext f b)} in have hφ : φ ∈ (nhds b).sets, from (nhds b).upwards_sets hf $ assume b ⟨c, hc⟩, show tendsto f (vmap e (nhds b)) (nhds (de.ext f b)), from (de.ext_eq hc).symm ▸ hc, assume s hs, let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in let ⟨s', hs'₁, (hs'₂ : e ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in have h₁ : closure (f '' (e ⁻¹' s')) ⊆ s'', by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂, have h₂ : t ⊆ de.ext f ⁻¹' closure (f '' (e ⁻¹' t)), from assume b' hb', have nhds b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb', have map f (vmap e (nhds b')) ≤ nhds (de.ext f b') ⊓ principal (f '' (e ⁻¹' t)), from calc _ ≤ map f (vmap e (nhds b' ⊓ principal t)) : map_mono $ vmap_mono $ le_inf (le_refl _) this ... ≤ map f (vmap e (nhds b')) ⊓ map f (vmap e (principal t)) : le_inf (map_mono $ vmap_mono $ inf_le_left) (map_mono $ vmap_mono $ inf_le_right) ... ≤ map f (vmap e (nhds b')) ⊓ principal (f '' (e ⁻¹' t)) : by simp [le_refl] ... ≤ _ : inf_le_inf ((ht₁ hb').left) (le_refl _), show de.ext f b' ∈ closure (f '' (e ⁻¹' t)), begin rw [closure_eq_nhds], apply neq_bot_of_le_neq_bot _ this, simp, exact de.vmap_nhds_neq_bot end, (nhds b).upwards_sets (show t ∈ (nhds b).sets, from mem_nhds_sets ht₂ ht₃) (calc t ⊆ de.ext f ⁻¹' closure (f '' (e ⁻¹' t)) : h₂ ... ⊆ de.ext f ⁻¹' closure (f '' (e ⁻¹' s')) : preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _ ... ⊆ de.ext f ⁻¹' s'' : preimage_mono h₁ ... ⊆ de.ext f ⁻¹' s : preimage_mono hs''₂) lemma continuous_ext {f : α → γ} (de : dense_embedding e) (hf : ∀b, ∃c, tendsto f (vmap e (nhds b)) (nhds c)) : continuous (de.ext f) := continuous_iff_tendsto.mpr $ assume b, de.tendsto_ext $ univ_mem_sets' hf end dense_embedding namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- The product of two dense embeddings is a dense embedding -/ protected def prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { dense_embedding . dense := have closure (range (λ(p : α × γ), (e₁ p.1, e₂ p.2))) = set.prod (closure (range e₁)) (closure (range e₂)), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, begin rw [this], simp, constructor, apply de₁.dense, apply de₂.dense end, inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, induced := assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_prod_eq, ←prod_vmap_vmap_eq, de₁.induced, de₂.induced] } def subtype_emb (p : α → Prop) {e : α → β} (de : dense_embedding e) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩ protected def subtype (p : α → Prop) {e : α → β} (de : dense_embedding e) : dense_embedding (de.subtype_emb p) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype_val_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_vmap, vmap_vmap_comp, (∘), (de.induced x).symm] } end dense_embedding lemma is_closed_property [topological_space α] [topological_space β] {e : α → β} {p : β → Prop} (he : closure (range e) = univ) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : closure_eq_of_is_closed hp, assume b, this trivial lemma is_closed_property2 [topological_space α] [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he).closure_range hp $ assume a, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space α] [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he).closure_range hp $ assume ⟨a₁, a₂, a₃⟩, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h ... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
44075f698e4a420ef00d135cb0bdda640a8f20ef
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/SubExpr.lean
8dd256327b3c09c16fed2677fbc6b7577e703ac7
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
5,940
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Daniel Selsam, Wojciech Nawrocki, E.W.Ayers -/ import Lean.Meta.Basic import Lean.Data.Json import Std.Data.RBMap namespace Lean /-- A position of a subexpression in an expression. See docstring of `SubExpr` for more detail.-/ def SubExpr.Pos := Nat namespace SubExpr.Pos def maxChildren := 4 /-- The coordinate `3 = maxChildren - 1` is reserved to denote the type of the expression. -/ def typeCoord : Nat := maxChildren - 1 def asNat : Pos → Nat := id /-- The Pos representing the root subexpression. -/ def root : Pos := (1 : Nat) instance : Inhabited Pos := ⟨root⟩ def isRoot (p : Pos) : Bool := p.asNat < maxChildren /-- The coordinate deepest in the Pos. -/ def head (p : Pos) : Nat := if p.isRoot then panic! "already at top" else p.asNat % maxChildren def tail (p : Pos) : Pos := if p.isRoot then panic! "already at top" else (p.asNat - p.head) / maxChildren def push (p : Pos) (c : Nat) : Pos := if c >= maxChildren then panic! s!"invalid coordinate {c}" else p.asNat * maxChildren + c variable {α : Type} [Inhabited α] /-- Fold over the position starting at the root and heading to the leaf-/ partial def foldl (f : α → Nat → α) (a : α) (p : Pos) : α := if p.isRoot then a else f (foldl f a p.tail) p.head /-- Fold over the position starting at the leaf and heading to the root-/ partial def foldr (f : Nat → α → α) (p : Pos) (a : α) : α := if p.isRoot then a else foldr f p.tail (f p.head a) /-- monad-fold over the position starting at the root and heading to the leaf -/ partial def foldlM [Monad M] (f : α → Nat → M α) (a : α) (p : Pos) : M α := have : Inhabited (M α) := inferInstance if p.isRoot then pure a else do foldlM f a p.tail >>= (f · p.head) /-- monad-fold over the position starting at the leaf and finishing at the root. -/ partial def foldrM [Monad M] (f : Nat → α → M α) (p : Pos) (a : α) : M α := if p.isRoot then pure a else f p.head a >>= foldrM f p.tail def depth (p : Pos) := p.foldr (fun _ => Nat.succ) 0 /-- Returns true if `pred` is true for each coordinate in `p`.-/ def all (pred : Nat → Bool) (p : Pos) : Bool := OptionT.run (m := Id) (foldrM (fun n a => if pred n then pure a else failure) p ()) |>.isSome def append : Pos → Pos → Pos := foldl push /-- Creates a subexpression `Pos` from an array of 'coordinates'. Each coordinate is a number {0,1,2} expressing which child subexpression should be explored. The first coordinate in the array corresponds to the root of the expression tree. -/ def ofArray (ps : Array Nat) : Pos := ps.foldl push root /-- Decodes a subexpression `Pos` as a sequence of coordinates `cs : Array Nat`. See `Pos.fromArray` for details. `cs[0]` is the coordinate for the root expression. -/ def toArray (p : Pos) : Array Nat := foldl Array.push #[] p def pushBindingDomain (p : Pos) := p.push 0 def pushBindingBody (p : Pos) := p.push 1 def pushLetVarType (p : Pos) := p.push 0 def pushLetValue (p : Pos) := p.push 1 def pushLetBody (p : Pos) := p.push 2 def pushAppFn (p : Pos) := p.push 0 def pushAppArg (p : Pos) := p.push 1 def pushProj (p : Pos) := p.push 0 def pushNaryFn (numArgs : Nat) (p : Pos) : Pos := p.asNat * (maxChildren ^ numArgs) def pushNaryArg (numArgs argIdx : Nat) (p : Pos) : Pos := show Nat from p.asNat * (maxChildren ^ (numArgs - argIdx)) + 1 protected def toString (p : Pos) : String := p.toArray.toList |>.map toString |> String.intercalate "/" |> ("/" ++ ·) open Except in private def ofStringCoord : String → Except String Nat | "0" => ok 0 | "1" => ok 1 | "2" => ok 2 | "3" => ok 3 | c => error s!"Invalid coordinate {c}" open Except in protected def fromString? : String → Except String Pos | "/" => Except.ok Pos.root | s => match String.splitOn s "/" with | "" :: tail => Pos.ofArray <$> tail.toArray.mapM ofStringCoord | ss => error s!"malformed {ss}" instance : Ord Pos := show Ord Nat by infer_instance instance : DecidableEq Pos := show DecidableEq Nat by infer_instance instance : ToString Pos := ⟨Pos.toString⟩ -- Note: we can't send the bare Nat over the wire because Json will convert to float -- if the nat is too big and least significant bits will be lost. instance : ToJson Pos := ⟨toJson ∘ Pos.toString⟩ instance : FromJson Pos := ⟨fun j => fromJson? j >>= Pos.fromString?⟩ end SubExpr.Pos /-- An expression and the position of a subexpression within this expression. Subexpressions are encoded as the current subexpression `e` and a position `p : Pos` denoting `e`'s position with respect to the root expression. We use a simple encoding scheme for expression positions `Pos`: every `Expr` constructor has at most 3 direct expression children. Considering an expression's type to be one extra child as well, we can injectively map a path of `childIdxs` to a natural number by computing the value of the 4-ary representation `1 :: childIdxs`, since n-ary representations without leading zeros are unique. Note that `pos` is initialized to `1` (case `childIdxs == []`).-/ structure SubExpr where expr : Expr pos : SubExpr.Pos deriving Inhabited namespace SubExpr def mkRoot (e : Expr) : SubExpr := ⟨e, Pos.root⟩ /-- Returns true if the selected subexpression is the topmost one.-/ def isRoot (s : SubExpr) : Bool := s.pos.isRoot end SubExpr open SubExpr in /-- Same as `Expr.traverseApp` but also includes a `SubExpr.Pos` argument for tracking subexpression position. -/ def Expr.traverseAppWithPos {M} [Monad M] (visit : Pos → Expr → M Expr) (p : Pos) (e : Expr) : M Expr := match e with | Expr.app f a => e.updateApp! <$> traverseAppWithPos visit p.pushAppFn f <*> visit p.pushAppArg a | e => visit p e end Lean
57acb389c867f4d3249ec4f0d274af6baa2eba43
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/Do.lean
4bd17366abeb23e2326a49f303e3ce0aa4dc8504
[ "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
72,049
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.BindersUtil import Lean.Elab.PatternVar import Lean.Elab.Quotation.Util import Lean.Parser.Do -- HACK: avoid code explosion until heuristics are improved set_option compiler.reuse false namespace Lean.Elab.Term open Lean.Parser.Term open Meta open TSyntax.Compat private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == ``Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == ``Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Parser.Term.do || k == ``Parser.Term.doSeqIndent || k == ``Parser.Term.doSeqBracketed || k == ``Parser.Term.termReturn || k == ``Parser.Term.termUnless || k == ``Parser.Term.termTry || k == ``Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Parser.Term.letPatDecl then false else if k == ``Parser.Term.letEqnsDecl then true else if k == ``Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> letIdBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Parser.Term.fun || k == ``Parser.Term.matchAlts || k == ``Parser.Term.doLetRec || k == ``Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax → Bool | Syntax.node _ k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == ``Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr returnType : Expr expectedType : Expr private def mkUnknownMonadResult : MetaM ExtractMonadResult := do let u ← mkFreshLevelMVar let v ← mkFreshLevelMVar let m ← mkFreshExprMVar (← mkArrow (mkSort (mkLevelSucc u)) (mkSort (mkLevelSucc v))) let returnType ← mkFreshExprMVar (mkSort (mkLevelSucc u)) return { m, returnType, expectedType := mkApp m returnType } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do let some expectedType := expectedType? | mkUnknownMonadResult let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do let .app m returnType := type | return none try let bindInstType ← mkAppM ``Bind #[m] discard <| Meta.synthInstance bindInstType return some { m, returnType, expectedType } catch _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then mkUnknownMonadResult else match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => throwError "invalid `do` notation, expected type is not a monad application{indentExpr expectedType}\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad." namespace Do abbrev Var := Syntax -- TODO: should be `Ident` /-- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Var patterns : Syntax rhs : σ deriving Inhabited /-- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Var) (doElem : Syntax) (k : Code) | reassign (xs : Array Var) (doElem : Syntax) (k : Code) /-- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Var × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | break (ref : Syntax) | continue (ref : Syntax) | return (ref : Syntax) (val : Syntax) /-- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | match (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited def Code.getRef? : Code → Option Syntax | .decl _ doElem _ => doElem | .reassign _ doElem _ => doElem | .joinpoint .. => none | .seq a _ => a | .action a => a | .break ref => ref | .continue ref => ref | .return ref _ => ref | .ite ref .. => ref | .match ref .. => ref | .jmp ref .. => ref abbrev VarSet := RBMap Name Syntax Name.cmp /-- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : VarSet := {} -- set of variables updated by `code` private def varSetToArray (s : VarSet) : Array Var := s.fold (fun xs _ x => xs.push x) #[] private def varsToMessageData (vars : Array Var) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax let rec loop : Code → MessageData | .decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | .reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | .joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | .seq e k => m!"{e}\n{loop k}" | .action e => e | .ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | .jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | .break _ => m!"break {us}" | .continue _ => m!"continue {us}" | .return _ v => m!"return {v} {us}" | .match _ _ ds _ alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /-- Return true if the give code contains an exit point that satisfies `p` -/ partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec loop : Code → Bool | .decl _ _ k => loop k | .reassign _ _ k => loop k | .joinpoint _ _ b k => loop b || loop k | .seq _ k => loop k | .ite _ _ _ _ t e => loop t || loop e | .match _ _ _ _ alts => alts.any (loop ·.rhs) | .jmp .. => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun _ => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | .return .. => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | .action _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | .break _ => true | .continue _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | .break _ => true | .continue _ => true | .return _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensure_expected_type% "type mismatch, result value" $y) let k ← mkCont y return .decl #[y] doElem k /-- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Var) : MacroM Code := let rec loop : Code → MacroM Code | .decl xs stx k => return .decl xs stx (← loop k) | .reassign xs stx k => return .reassign xs stx (← loop k) | .joinpoint n ps b k => return .joinpoint n ps (← loop b) (← loop k) | .seq e k => return .seq e (← loop k) | .ite ref x? h c t e => return .ite ref x? h c (← loop t) (← loop e) | .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | .action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.push y return Code.jmp ref jp jmpArgs | c => return c loop code structure JPDecl where name : Name params : Array (Var × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Var × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← `(y) pure #[(y.raw, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def addFreshJP (ps : Array (Var × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : VarSet) (xs : Array Var) : VarSet := xs.foldl (fun rs x => rs.insert x.getId x) rs def eraseVars (rs : VarSet) (xs : Array Var) : VarSet := xs.foldl (·.erase ·.getId) rs def eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet := match x? with | none => rs | some x => rs.insert x.getId x /-- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := varSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp xs /-- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : VarSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := varSetToArray rs let args := xs.push val let yFresh ← withRef ref `(y) let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM <| mkJPBody yFresh let jp ← addFreshJP ps jpBody return Code.jmp ref jp args /-- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := match c with | .decl xs stx k => return .decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | .reassign xs stx k => return .reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | .joinpoint j ps b k => return .joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | .seq e k => return .seq e (← pullExitPointsAux rs k) | .ite ref x? o c t e => return .ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | .jmp .. => return c | .break ref => mkSimpleJmp ref rs (.break ref) | .continue ref => mkSimpleJmp ref rs (.continue ref) | .return ref val => mkJmp ref rs val (fun y => return .return ref y) | .action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => return .action (← ``(Pure.pure $yFresh))) /-- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] return attachJPs jpDecls c else return c partial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code := let rec update (c : Code) : TermElabM Code := do match c with | .joinpoint j ps b k => return .joinpoint j ps (← update b) (← update k) | .seq e k => return .seq e (← update k) | .match ref g ds t alts => if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | .ite ref none o c t e => return .ite ref none o c (← update t) (← update e) | .ite ref (some h) o cond t e => if ws.contains h.getId then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else return Code.ite ref (some h) o cond (← update t) (← update e) | .reassign xs stx k => return .reassign xs stx (← update k) | .decl xs stx k => do if xs.any fun x => ws.contains x.getId then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else return .decl xs stx (← update k) | c => return c update c /-- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : VarSet) : TermElabM CodeBlock := do if ws.any fun x _ => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : VarSet) : VarSet := s₁.fold (·.insert ·) s₂ /-- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /-- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /-- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x.getId then extendUpdatedVarsAux c.code ws else pure c.code pure { code := .reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := .seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := .action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := .return ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := .break ref } def mkContinue (ref : Syntax) : CodeBlock := { code := .continue ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := optIdent.getOptional? let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch return { code := .ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do return mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction return { c with code := .ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } return { code := .match ref genParam discrs optMotive alts, uvars := ws } /-- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Var) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "`do` element is unreachable" let (terminal, k) ← homogenize terminal k let xs := varSetToArray k.uvars let y ← match y? with | some y => pure y | none => `(y) let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM <| convertTerminalActionIntoJmp terminal.code jp xs return { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Var := letIdDecl[0] -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) := getPatternVars pattern <|> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) := getPatternsVars patterns <|> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Var := letEqnsDecl[0] def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do let arg := letDecl[0] if arg.getKind == ``Parser.Term.letIdDecl then return #[getLetIdDeclVar arg] else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Parser.Term.letEqnsDecl then return #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Var) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getHaveIdLhsVar (optIdent : Syntax) : TermElabM Var := if optIdent.isNone then `(this) else pure optIdent[0] def getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do -- doHave := leading_parser "have " >> Term.haveDecl -- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl let arg := doHave[1][0] if arg.getKind == ``Parser.Term.haveIdDecl then -- haveIdDecl := leading_parser atomic (haveIdLhs >> " := ") >> termParser -- haveIdLhs := optional (ident >> many (ppSpace >> letIdBinder)) >> optType return #[← getHaveIdLhsVar arg[0]] else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Parser.Term.haveEqnsDecl then -- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts return #[← getHaveIdLhsVar arg[0]] else throwError "unexpected kind of have declaration" def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars return allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Var := doIdDecl[0] -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do let decl := doLetArrow[2] if decl.getKind == ``Parser.Term.doIdDecl then return #[getDoIdDeclVar decl] else if decl.getKind == ``Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of `do` declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do let arg := doReassign[0] if arg.getKind == ``Parser.Term.letIdDecl then return #[getLetIdDeclVar arg] else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode <| doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /-- If the given syntax is a `doIf`, return an equivalent `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $_:doIfProp then $_ else $_) => pure none | `(doElem|if $cond:doIfCond then $t $[else if $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (cond, t) in Array.zip (conds.reverse.push cond) (ts.reverse.push t) do e ← if eIsSeq then pure e else `(doSeq|$e:doElem) e ← match cond with | `(doIfCond|let $pat := $d) => `(doElem| match $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if $cond:doIfProp then $t else $e) | _ => `(doElem| if $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /-- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : DoIfView := { ref := doIf optIdent := doIf[1][0] cond := doIf[1][1] thenBranch := doIf[3] elseBranch := doIf[5][1] } /-- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then return elems[0]! else elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple => ``(MProd.mk $elem $tuple) /-- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == ``Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(uvars[0]!):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $a:ident := $x.1; let $b:ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $a:ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /-! The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ /-- Helper method for annotating `term` with the raw syntax `ref`. We use this method to implement finer-grained term infos for `do`-blocks. We use `withRef term` to make sure the synthetic position for the `with_annotate_term` is equal to the one for `term`. This is important for producing error messages when there is a type mismatch. Consider the following example: ``` opaque f : IO Nat def g : IO String := do f ``` There is at type mismatch at `f`, but it is detected when elaborating the expanded term containing the `with_annotate_term .. f`. The current `getRef` when this `annotate` is invoked is not necessarily `f`. Actually, it is the whole `do`-block. By using `withRef` we ensure the synthetic position for the `with_annotate_term ..` is equal to `term`. Recall that synthetic positions are used when generating error messages. -/ def annotate [Monad m] [MonadRef m] [MonadQuotation m] (ref : Syntax) (term : Syntax) : m Syntax := withRef term <| `(with_annotate_term $ref $term) namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | .regular => true | _ => false structure Context where /-- Syntax to reference the monad associated with the do notation. -/ m : Syntax /-- Syntax to reference the result of the monadic computation performed by the do notation. -/ returnType : Syntax uvars : Array Var kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read mkTuple ctx.uvars def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | .forIn => ``(Pure.pure (ForInStep.done $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | .nestedBC => unreachable! | .nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | .nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => unreachable! | .forIn => ``(Pure.pure (ForInStep.yield $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | .nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | .nestedPR => unreachable! | .nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => unreachable! | .forIn => ``(Pure.pure (ForInStep.done $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | .nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | .nestedPR => unreachable! | .nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | .forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | .forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | .nestedBC => unreachable! | .nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | .nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | .nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == ``Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == ``Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == ``Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == ``Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] return mkNode ``Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == ``Parser.Term.doLetArrow then let arg := decl[2] if arg.getKind == ``Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType id arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of `do` declaration" else Macro.throwErrorAt decl "unexpected kind of `do` declaration" else if kind == ``Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] return mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of `do` declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do match reassign with | `(doElem| $x:ident := $rhs) => `(let $x:ident := ensure_type_of% $x $(quote "invalid reassignment, value") $rhs; $k) | `(doElem| $e:term := $rhs) => `(let $e:term := ensure_type_of% $e $(quote "invalid reassignment, value") $rhs; $k) | _ => -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of `do` reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(if $cond then $thenBranch else $elseBranch) else let h := optIdent[0] ``(if $h:ident : $cond then $thenBranch else $elseBranch) def mkJoinPoint (j : Name) (ps : Array (Syntax × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $id) else `(_) let ps := ps.map (·.1) /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm (c : Code) : M Syntax := do let term ← go c if let some ref := c.getRef? then annotate ref term else return term where go (c : Code) : M Syntax := do match c with | .return ref val => withRef ref <| returnToTerm val | .continue ref => withRef ref continueToTerm | .break ref => withRef ref breakToTerm | .action e => actionTerminalToTerm e | .joinpoint j ps b k => mkJoinPoint j ps (← toTerm b) (← toTerm k) | .jmp ref j args => return mkJmp ref j args | .decl _ stx k => declToTerm stx (← toTerm k) | .reassign _ stx k => reassignToTerm stx (← toTerm k) | .seq stx k => seqToTerm stx (← toTerm k) | .ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | .match ref genParam discrs optMotive alts => let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", mkNullNode #[alt.patterns], mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] return mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, optMotive, discrs, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax := toTerm code { m, returnType, kind, uvars } /-- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => .regular | false, true, false => .regular | false, false, true => .nestedBC | true, true, false => .nestedPR | true, false, true => .nestedSBC | false, true, true => .nestedSBC | true, true, true => .nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m returnType uvars (mkNestedKind a r bc) /-- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple uvars match a, r, bc with | true, false, false => if uvars.isEmpty then return toDoElems (← `(do $term:term)) else return toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then return toDoElems (← `(do let r ← $term:term; return r)) else return toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | .pure a u => $u:term := u; pure a | .return b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | .pureReturn a u => $u:term := u; pure a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | .pureReturn a u => $u:term := u; return a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | .pure a u => $u:term := u; pure a | .return a u => $u:term := u; return a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == ``doLetArrow || kind == ``doLet || kind == ``doLetElse) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax /-- Syntax representing the monad associated with the do notation. -/ m : Syntax /-- Syntax to reference the result of the monadic computation performed by the do notation. -/ returnType : Syntax mutableVars : VarSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM def withNewMutableVars {α} (newVars : Array Var) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Var) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "`{x.simpMacroScopes}` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intent to mutate but define `{x.simpMacroScopes}`, consider using `let {x.simpMacroScopes}` instead" let ctx ← read for x in xs do unless ctx.mutableVars.contains x.getId do throwInvalidReassignment x.getId def checkNotShadowingMutable (xs : Array Var) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable `{x.simpMacroScopes}` cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x.getId then withRef x <| throwInvalidShadowing x.getId def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Var term : Syntax def mkForInBody (_ : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := varSetToArray uvars let term ← liftMacroM <| ToTerm.run forInBody.code ctx.m ctx.returnType uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) return ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid `do` element, it must be inside `for`" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a `do` sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax | stx@(Syntax.node i k args) => if liftMethodDelimiter k then return stx else if k == ``Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1]! let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem : Syntax ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node i k args | stx => return stx def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do if !hasLiftMethod doElem then return ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] return (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == ``Parser.Term.doLetArrow || kind == ``Parser.Term.doLet || kind == ``Parser.Term.doLetRec || kind == ``Parser.Term.doHave || kind == ``Parser.Term.doReassign || kind == ``Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value `{kind}` in an assignment" /-- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : VarSet := let ws := tryCode.uvars let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /-- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /-- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let decl := doLetArrow[2] if decl.getKind == ``Parser.Term.doIdDecl then let y := decl[0] checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some _ => return mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == ``Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let%$doLetArrow discr ← $doElem; let%$doLetArrow mut $pattern:term := discr) else `(do let%$doLetArrow discr ← $doElem; let%$doLetArrow $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else let contSeq ← if isMutableLet doLetArrow then let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var) pure (vars ++ doElems.toArray) else pure doElems.toArray let contSeq := mkDoSeq contSeq let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let%$doLetArrow discr ← $doElem; match%$doLetArrow discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of `do` declaration" partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do -- "let " >> optional "mut " >> termParser >> " := " >> termParser >> checkColGt >> " | " >> doElemParser let pattern := doLetElse[2] let val := doLetElse[4] let elseSeq := mkSingletonDoSeq doLetElse[6] let contSeq ← if isMutableLet doLetElse then let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var) pure (vars ++ doElems.toArray) else pure doElems.toArray let contSeq := mkDoSeq contSeq let auxDo ← `(do let discr := $val; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) /-- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let decl := doReassignArrow[0] if decl.getKind == ``Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == ``Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of `do` reassignment" /-- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view := mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /-- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /-- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1]! unless doForDecl[0].isNone do throwErrorAt doForDecl[0] "the proof annotation here has not been implemented yet" let y := doForDecl[1] let ys := doForDecl[3] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do /- Recall that `@` (explicit) disables `coeAtOutParam`. We used `@` at `Stream` functions to make sure `resultIsOutParamSupport` is not used. -/ let toStreamApp ← withRef ys `(@toStream _ _ _ $ys) let auxDo ← `(do let mut s := $toStreamApp:term for $doForDecls:doForDecl,* do match @Stream.next? _ _ _ s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let h? := if doForDecls[0]![0].isNone then none else some doForDecls[0]![0][0] let x := doForDecls[0]![1] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0]![3] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let ctx ← read -- semantic no-op that replaces the `uvars`' position information (which all point inside the loop) -- with that of the respective mutable declarations outside the loop, which allows the language -- server to identify them as conceptually identical variables let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v let uvarsTuple ← liftMacroM do mkTuple uvars if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let optType ← `(Option $((← read).returnType)) let forInTerm ← if let some h := h? then annotate doFor (← `(for_in'% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x $h (r : MProd $optType _) => let r := r.2; $forInBody)) else annotate doFor (← `(for_in% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x (r : MProd $optType _) => let r := r.2; $forInBody)) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit) | some a => return ensure_expected_type% "type mismatch, `for`" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← if let some h := h? then annotate doFor (← `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody)) else annotate doFor (← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody)) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let optMotive := doMatch[2] let discrs := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let matchAlts ← matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (← liftMacroM <| expandMatchAlt matchAlt) let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1][0] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optMotive alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx : Syntax => do if catchStx.getKind == ``Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) return { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == ``Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) return { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of `catch`" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid `try`, it must have a `catch` or `finally`" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := varSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM <| ToTerm.mkNestedTerm codeBlock.code ctx.m ctx.returnType uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (init := term) fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then annotate doTry (← ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm))) else let type := «catch».optType[1] annotate doTry (← ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "`finally` currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "`finally` currently does `return`, `break`, nor `continue`" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m ctx.returnType {} ToTerm.Kind.regular annotate doTry (← ``(tryFinally $term $finallyTerm)) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "`do`-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← expandLiftMethod doElem if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let k := doElem.getKind if k == ``Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == ``Parser.Term.doHave then let vars ← getDoHaveVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == ``Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == ``Parser.Term.doLetElse then doLetElseToCode doElem doElems else if k == ``Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == ``Parser.Term.doIf then doIfToCode doElem doElems else if k == ``Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == ``Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == ``Parser.Term.doMatch then doMatchToCode doElem doElems else if k == ``Parser.Term.doTry then doTryToCode doElem doElems else if k == ``Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == ``Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == ``Parser.Term.doReturn then doReturnToCode doElem doElems else if k == ``Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == ``Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}" end def run (doStx : Syntax) (m : Syntax) (returnType : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m, returnType } end ToCodeBlock @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← Term.exprToSyntax bindInfo.m let returnType ← Term.exprToSyntax bindInfo.returnType let codeBlock ← ToCodeBlock.run stx m returnType let stxNew ← liftMacroM <| ToTerm.run codeBlock.code m returnType trace[Elab.do] stxNew withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem ``Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem ``Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem ``Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem ``Parser.Term.doReturn end Lean.Elab.Term
7e0e32c53f5b2794082e67330715f792b2b6d69f
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/empty.lean
5613cd35187d772a0c963ba65075319900ebacd4
[ "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
168
lean
-- open inhabited nonempty classical lemma v1 : Prop := epsilon (λ x : Prop, true) inductive Empty : Type noncomputable definition v2 : Empty := epsilon (λ x, true)
5232ed9d080d96c1dc59e5c1254d9f02efdf53f2
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/monoid_algebra.lean
717c4d50e0f7ca33171765ec14b373399b574d98
[ "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
55,863
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, Yury G. Kudryashov, Scott Morrison -/ import algebra.big_operators.finsupp import linear_algebra.finsupp import algebra.non_unital_alg_hom /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In fact the construction of the "monoid algebra" makes sense when `G` is not even a monoid, but merely a magma, i.e., when `G` carries a multiplication which is not required to satisfy any conditions at all. In this case the construction yields a not-necessarily-unital, not-necessarily-associative algebra but it is still adjoint to the forgetful functor from such algebras to magmas, and we prove this as `monoid_algebra.lift_magma`. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) /-! ### Multiplicative monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid, has_coe_to_fun]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k end namespace monoid_algebra variables {k G} section has_mul variables [semiring k] [has_mul G] /-- The product of `f g : monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], .. finsupp.add_comm_monoid } end has_mul section semigroup variables [semiring k] [semigroup G] instance : non_unital_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. monoid_algebra.non_unital_non_assoc_semiring} end semigroup section has_one variables [semiring k] [has_one G] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl end has_one section mul_one_class variables [semiring k] [mul_one_class G] instance : non_assoc_semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], ..monoid_algebra.non_unital_non_assoc_semiring } variables {R : Type*} [semiring R] /-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : G →* R`, returns the additive homomorphism from `monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : G →* R) : monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g a := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : G →* R) : lift_nc (f : k →+ R) g 1 = 1 := by simp [one_def] lemma lift_nc_mul (f : k →+* R) (g : G →* R) (a b : monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := begin conv_rhs { rw [← sum_single a, ← sum_single b] }, simp_rw [mul_def, (lift_nc _ g).map_finsupp_sum, lift_nc_single, finsupp.sum_mul, finsupp.mul_sum], refine finset.sum_congr rfl (λ y hy, finset.sum_congr rfl (λ x hx, _)), simp [mul_assoc, (h_comm hy).left_comm] end end mul_one_class /-! #### Semiring structure -/ section semiring variables [semiring k] [monoid G] instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. monoid_algebra.non_unital_semiring, .. monoid_algebra.non_assoc_semiring } variables {R : Type*} [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.semiring } instance [semiring k] [nontrivial k] [nonempty G]: nontrivial (monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_group (monoid_algebra k G) := finsupp.add_group instance [ring k] [monoid G] : ring (monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. monoid_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { mul_comm := mul_comm, .. monoid_algebra.ring} variables {R S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : has_scalar R (monoid_algebra k G) := finsupp.has_scalar instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (monoid_algebra k G) := finsupp.distrib_mul_action G k instance [semiring R] [semiring k] [module R k] : module R (monoid_algebra k G) := finsupp.module G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_scalar R k] [nonempty G] : has_faithful_scalar R (monoid_algebra k G) := finsupp.has_faithful_scalar instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_scalar R S] [is_scalar_tower R S k] : is_scalar_tower R S (monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (monoid_algebra k G) := finsupp.smul_comm_class G k instance comap_distrib_mul_action_self [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action_self end derived_instances section misc_theorems variables [semiring k] local attribute [reducible] monoid_algebra lemma mul_apply [has_mul G] (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal [has_mul G] (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _ _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end lemma support_mul [has_mul G] (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bUnion_mono $ assume a₁ _, subset.trans support_sum $ bUnion_mono $ assume a₂ _, support_single_subset @[simp] lemma single_mul_single [has_mul G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow [monoid G] {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := by { simp only [pow_zero], refl } | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_mul α] [has_mul α₂] {x y : monoid_algebra β α} (f : mul_hom α α₂) : (map_domain f (x * y : monoid_algebra β α) : monoid_algebra β α₂) = (map_domain f x * map_domain f y : monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_mul], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end variables (k G) /-- The embedding of a magma into its magma algebra. -/ @[simps] def of_magma [has_mul G] : mul_hom G (monoid_algebra k G) := { to_fun := λ a, single a 1, map_mul' := λ a b, by simp only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- The embedding of a unital magma into its magma algebra. -/ @[simps] def of [mul_one_class G] : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } end lemma of_injective [mul_one_class G] [nontrivial k] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma single_mul_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr' with g s, split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_one_mul_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] lemma lift_nc_smul [mul_one_class G] {R : Type*} [semiring R] (f : k →+* R) (g : G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := begin suffices : (lift_nc ↑f g).comp (smul_add_hom k (monoid_algebra k G) c) = (add_monoid_hom.mul_left (f c)).comp (lift_nc ↑f g), from add_monoid_hom.congr_fun this φ, ext a b, simp [mul_assoc] end end misc_theorems /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables {R : Type*} (k) [semiring R] [semiring k] [distrib_mul_action R k] [has_mul G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, simp only [mul_apply, finsupp.smul_sum, smul_ite, smul_mul_assoc, sum_smul_index', zero_mul, if_t_t, implies_true_iff, eq_self_iff_true, sum_zero, coe_smul, smul_eq_mul, pi.smul_apply, smul_zero], end⟩ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, simp only [mul_apply, finsupp.sum, finset.smul_sum, smul_ite, mul_smul_comm, sum_smul_index', implies_true_iff, eq_self_iff_true, coe_smul, ite_eq_right_iff, smul_eq_mul, pi.smul_apply, mul_zero, smul_zero], end⟩ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (monoid_algebra k G) R (monoid_algebra k G) := ⟨λ t a b, by { haveI := smul_comm_class.symm k R k, rw ← smul_comm, } ⟩ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (monoid_algebra k G) A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := non_unital_alg_hom.to_distrib_mul_action_hom_injective $ finsupp.distrib_mul_action_hom_ext' $ λ a, distrib_mul_action_hom.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (monoid_algebra k G) A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := non_unital_alg_hom_ext k $ mul_hom.congr_fun h /-- The functor `G ↦ monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : mul_hom G A ≃ non_unital_alg_hom k (monoid_algebra k G) A := { to_fun := λ f, { to_fun := λ a, a.sum (λ m t, t • f m), map_smul' := λ t' a, begin rw [finsupp.smul_sum, sum_smul_index'], { simp_rw smul_assoc, }, { intros m, exact zero_smul k (f m), }, end, map_mul' := λ a₁ a₂, begin let g : G → k → A := λ m t, t • f m, have h₁ : ∀ m, g m 0 = 0, { intros, exact zero_smul k (f m), }, have h₂ : ∀ m (t₁ t₂ : k), g m (t₁ + t₂) = g m t₁ + g m t₂, { intros, rw ← add_smul, }, simp_rw [finsupp.mul_sum, finsupp.sum_mul, smul_mul_smul, ← f.map_mul, mul_def, sum_comm a₂ a₁, sum_sum_index h₁ h₂, sum_single_index (h₁ _)], end, .. lift_add_hom (λ x, (smul_add_hom k A).flip (f x)) }, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), left_inv := λ f, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, right_inv := λ F, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra local attribute [reducible] monoid_algebra lemma single_one_comm [comm_semiring k] [mul_one_class G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } /-- `finsupp.single 1` as a `ring_hom` -/ @[simps] def single_one_ring_hom [semiring k] [monoid G] : k →+* monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, one_mul], ..finsupp.single_add_hom 1} /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : ∀ b, f (single 1 b) = g (single 1 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := ring_hom.coe_add_monoid_hom_injective $ add_hom_ext $ λ a b, by rw [← one_mul a, ← mul_one b, ← single_mul_single, f.coe_add_monoid_hom, g.coe_add_monoid_hom, f.map_mul, g.map_mul, h₁, h_of] /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : f.comp single_one_ring_hom = g.comp single_one_ring_hom) (h_of : (f : monoid_algebra k G →* R).comp (of k G) = (g : monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) /-- The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`. In particular this provides the instance `algebra k (monoid_algebra k G)`. -/ instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : algebra k (monoid_algebra A G) := { smul_def' := λ r a, by { ext, simp [single_one_mul_apply, algebra.smul_def'', pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_one_mul_apply, mul_single_one_apply, algebra.commutes], }, ..single_one_ring_hom.comp (algebra_map k A) } /-- `finsupp.single 1` as a `alg_hom` -/ @[simps] def single_one_alg_hom {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : A →ₐ[k] monoid_algebra A G := { commutes' := λ r, by { ext, simp, refl, }, ..single_one_ring_hom} @[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : ⇑(algebra_map k (monoid_algebra A G)) = single 1 ∘ (algebra_map k A) := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = algebra_map k (monoid_algebra k G) b * of k G a := by simp lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] (a : G) (b : k) : single a (algebra_map k A b) = algebra_map k (monoid_algebra A G) b * of A G a := by simp lemma induction_on [semiring k] [monoid G] {p : monoid_algebra k G → Prop} (f : monoid_algebra k G) (hM : ∀ g, p (of k G g)) (hadd : ∀ f g : monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G 1) (hM 1) }, { convert hsmul r (of k G g) (hM g), simp only [mul_one, smul_single', of_apply] }, end end algebra section lift variables {k G} [comm_semiring k] [monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := alg_hom.to_linear_map_injective $ finsupp.lhom_ext' $ λ a, linear_map.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : monoid_algebra k G →* A).comp (of k G) = (φ₂ : monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G), to_fun := λ F, lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, left_inv := λ f, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] }, right_inv := λ F, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] } } variables {k G A} lemma lift_apply' (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F a) := rfl lemma lift_apply (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F a) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) : (lift k G A).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* A) (x) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* A) (a b) : lift k G A F (single a b) = b • F a := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } end lift section local attribute [reducible] monoid_algebra variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) : V →ₗ[k] V := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, smul_algebra_smul_comm _ _ _ } @[simp] lemma group_smul.linear_map_apply [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [monoid G] [comm_semiring k] {V W : Type u₃} [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] [add_comm_monoid W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (f : V →ₗ[k] W) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, simp only [add_smul, f.map_add, w, add_left_inj, single_eq_algebra_map_mul_of, ← smul_smul], erw [algebra_map_smul (monoid_algebra k G) r, algebra_map_smul (monoid_algebra k G) r, f.map_smul, h g v, of_apply], all_goals { apply_instance } } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end section universe ui variable {ι : Type ui} local attribute [reducible] monoid_algebra lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] end section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] local attribute [reducible] monoid_algebra @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a b * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a b) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end section span variables [semiring k] [mul_one_class G] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_span_support (f : monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span section opposite open finsupp opposite variables [semiring k] /-- The opposite of an `monoid_algebra R I` equivalent as a ring to the `monoid_algebra Rᵒᵖ Iᵒᵖ` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [monoid G] : (monoid_algebra k G)ᵒᵖ ≃+* monoid_algebra kᵒᵖ Gᵒᵖ := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i₁ r₁ i₂ r₂ : 6, simp end, ..op_add_equiv.symm.trans $ (finsupp.map_range.add_equiv (op_add_equiv : k ≃+ kᵒᵖ)).trans $ finsupp.dom_congr equiv_to_opposite } @[simp] lemma op_ring_equiv_single [monoid G] (r : k) (x : G) : monoid_algebra.op_ring_equiv (op (single x r)) = single (op x) (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [monoid G] (r : kᵒᵖ) (x : Gᵒᵖ) : monoid_algebra.op_ring_equiv.symm (single x r) = op (single x.unop r.unop) := by simp end opposite end monoid_algebra /-! ### Additive monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid, has_coe_to_fun]] def add_monoid_algebra := G →₀ k end namespace add_monoid_algebra variables {k G} section has_mul variables [semiring k] [has_add G] /-- The product of `f g : add_monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], nsmul := λ n f, n • f, nsmul_zero' := by { intros, ext, simp [-nsmul_eq_mul, add_smul] }, nsmul_succ' := by { intros, ext, simp [-nsmul_eq_mul, nat.succ_eq_one_add, add_smul] }, .. finsupp.add_comm_monoid } end has_mul section has_one variables [semiring k] [has_zero G] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl end has_one section semigroup variables [semiring k] [add_semigroup G] instance : non_unital_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. add_monoid_algebra.non_unital_non_assoc_semiring } end semigroup section mul_one_class variables [semiring k] [add_zero_class G] instance : non_assoc_semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], .. add_monoid_algebra.non_unital_non_assoc_semiring } variables {R : Type*} [semiring R] /-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : multiplicative G →* R`, returns the additive homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `add_monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : multiplicative G →* R) : add_monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g $ multiplicative.of_add x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : multiplicative G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g (multiplicative.of_add a) := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : multiplicative G →* R) : lift_nc (f : k →+ R) g 1 = 1 := @monoid_algebra.lift_nc_one k (multiplicative G) _ _ _ _ f g lemma lift_nc_mul (f : k →+* R) (g : multiplicative G →* R) (a b : add_monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g $ multiplicative.of_add y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := @monoid_algebra.lift_nc_mul k (multiplicative G) _ _ _ _ f g a b @h_comm end mul_one_class /-! #### Semiring structure -/ section semiring instance {R : Type*} [monoid R] [semiring k] [distrib_mul_action R k] : has_scalar R (add_monoid_algebra k G) := finsupp.has_scalar variables [semiring k] [add_monoid G] instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. add_monoid_algebra.non_unital_semiring, .. add_monoid_algebra.non_assoc_semiring, } variables {R : Type*} [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : multiplicative G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { mul_comm := @mul_comm (monoid_algebra k $ multiplicative G) _, .. add_monoid_algebra.semiring } instance [semiring k] [nontrivial k] [nonempty G] : nontrivial (add_monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_group (add_monoid_algebra k G) := finsupp.add_group instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, sub := has_sub.sub, sub_eq_add_neg := finsupp.add_group.sub_eq_add_neg, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { mul_comm := mul_comm, .. add_monoid_algebra.ring} variables {R S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (add_monoid_algebra k G) := finsupp.distrib_mul_action G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_scalar R k] [nonempty G] : has_faithful_scalar R (add_monoid_algebra k G) := finsupp.has_faithful_scalar instance [semiring R] [semiring k] [module R k] : module R (add_monoid_algebra k G) := finsupp.module G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_scalar R S] [is_scalar_tower R S k] : is_scalar_tower R S (add_monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (add_monoid_algebra k G) := finsupp.smul_comm_class G k /-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)` because we've never discussed actions of additive groups. -/ end derived_instances section misc_theorems variables [semiring k] lemma mul_apply [has_add G] (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := @monoid_algebra.mul_apply k (multiplicative G) _ _ _ _ _ lemma mul_apply_antidiagonal [has_add G] (f g : add_monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 + p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := @monoid_algebra.mul_apply_antidiagonal k (multiplicative G) _ _ _ _ _ s @hs lemma support_mul [has_add G] (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ + a₂}) := @monoid_algebra.support_mul k (multiplicative G) _ _ _ _ lemma single_mul_single [has_add G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ * single a₂ b₂ : add_monoid_algebra k G) = single (a₁ + a₂) (b₁ * b₂) := @monoid_algebra.single_mul_single k (multiplicative G) _ _ _ _ _ _ -- This should be a `@[simp]` lemma, but the simp_nf linter times out if we add this. -- Probably the correct fix is to make a `[add_]monoid_algebra.single` with the correct type, -- instead of relying on `finsupp.single`. lemma single_pow [add_monoid G] {a : G} {b : k} : ∀ n : ℕ, ((single a b)^n : add_monoid_algebra k G) = single (n • a) (b ^ n) | 0 := by { simp only [pow_zero, zero_nsmul], refl } | (n+1) := by rw [pow_succ, pow_succ, single_pow n, single_mul_single, add_comm, add_nsmul, one_nsmul] /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_add α] [has_add α₂] {x y : add_monoid_algebra β α} (f : add_hom α α₂) : (map_domain f (x * y : add_monoid_algebra β α) : add_monoid_algebra β α₂) = (map_domain f x * map_domain f y : add_monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_add], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end section variables (k G) /-- The embedding of an additive magma into its additive magma algebra. -/ @[simps] def of_magma [has_add G] : mul_hom (multiplicative G) (add_monoid_algebra k G) := { to_fun := λ a, single a 1, map_mul' := λ a b, by simpa only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- Embedding of a magma with zero into its magma algebra. -/ def of [add_zero_class G] : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } /-- Embedding of a magma with zero `G`, into its magma algebra, having `G` as source. -/ def of' : G → add_monoid_algebra k G := λ a, single a 1 end @[simp] lemma of_apply [add_zero_class G] (a : multiplicative G) : of k G a = single a.to_add 1 := rfl @[simp] lemma of'_apply (a : G) : of' k G a = single a 1 := rfl lemma of'_eq_of [add_zero_class G] (a : G) : of' k G a = of k G a := rfl lemma of_injective [nontrivial k] [add_zero_class G] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := @monoid_algebra.mul_single_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma mul_single_zero_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f : add_monoid_algebra k G) y = r * f z := @monoid_algebra.single_mul_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma single_zero_mul_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f : add_monoid_algebra k G) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] lemma lift_nc_smul {R : Type*} [add_zero_class G] [semiring R] (f : k →+* R) (g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := @monoid_algebra.lift_nc_smul k (multiplicative G) _ _ _ _ f g c φ variables {k G} lemma induction_on [add_monoid G] {p : add_monoid_algebra k G → Prop} (f : add_monoid_algebra k G) (hM : ∀ g, p (of k G (multiplicative.of_add g))) (hadd : ∀ f g : add_monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G (multiplicative.of_add 0)) (hM 0) }, { convert hsmul r (of k G (multiplicative.of_add g)) (hM g), simp only [mul_one, to_add_of_add, smul_single', of_apply] }, end end misc_theorems section span variables [semiring k] /-- An element of `add_monoid_algebra R M` is in the submodule generated by its support. -/ lemma mem_span_support [add_zero_class G] (f : add_monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support, using unbundled inclusion. -/ lemma mem_span_support' (f : add_monoid_algebra k G) : f ∈ submodule.span k (of' k G '' (f.support : set G)) := by rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span end add_monoid_algebra /-! #### Conversions between `add_monoid_algebra` and `monoid_algebra` We have not defined `add_monoid_algebra k G = monoid_algebra k (multiplicative G)` because historically this caused problems; since the changes that have made `nsmul` definitional, this would be possible, but for now we just contruct the ring isomorphisms using `ring_equiv.refl _`. -/ /-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative` -/ protected def add_monoid_algebra.to_multiplicative [semiring k] [has_add G] : add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) := { to_fun := equiv_map_domain multiplicative.of_add, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [multiplicative.of_add], convert monoid_algebra.map_domain_mul (mul_hom.id (multiplicative G)), end, ..finsupp.dom_congr multiplicative.of_add } /-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/ protected def monoid_algebra.to_additive [semiring k] [has_mul G] : monoid_algebra k G ≃+* add_monoid_algebra k (additive G) := { to_fun := equiv_map_domain additive.of_mul, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [additive.of_mul], convert monoid_algebra.map_domain_mul (mul_hom.id G), end, ..finsupp.dom_congr additive.of_mul } namespace add_monoid_algebra variables {k G} /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables {R : Type*} (k) [semiring R] [semiring k] [distrib_mul_action R k] [has_add G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.is_scalar_tower_self k (multiplicative G) R _ _ _ _ _ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_self k (multiplicative G) R _ _ _ _ _ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (add_monoid_algebra k G) R (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_symm_self k (multiplicative G) R _ _ _ _ _ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `add_monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (add_monoid_algebra k G) A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (add_monoid_algebra k G) A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext' k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- The functor `G ↦ add_monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : mul_hom (multiplicative G) A ≃ non_unital_alg_hom k (add_monoid_algebra k G) A := { to_fun := λ f, { to_fun := λ a, sum a (λ m t, t • f (multiplicative.of_add m)), .. (monoid_algebra.lift_magma k f : _)}, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), .. (monoid_algebra.lift_magma k : mul_hom (multiplicative G) A ≃ non_unital_alg_hom k _ A) } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra variables {R : Type*} local attribute [reducible] add_monoid_algebra /-- `finsupp.single 0` as a `ring_hom` -/ @[simps] def single_zero_ring_hom [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, zero_add], ..finsupp.single_add_hom 0} /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₀ : ∀ b, f (single 0 b) = g (single 0 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := @monoid_algebra.ring_hom_ext k (multiplicative G) R _ _ _ _ _ h₀ h_of /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₁ : f.comp single_zero_ring_hom = g.comp single_zero_ring_hom) (h_of : (f : add_monoid_algebra k G →* R).comp (of k G) = (g : add_monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) section opposite open finsupp opposite variables [semiring k] /-- The opposite of an `add_monoid_algebra R I` is ring equivalent to the `add_monoid_algebra Rᵒᵖ I` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [add_comm_monoid G] : (add_monoid_algebra k G)ᵒᵖ ≃+* add_monoid_algebra kᵒᵖ G := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i r i' r' : 6, dsimp, simp only [map_range_single, single_mul_single, ←op_mul, add_comm] end, ..opposite.op_add_equiv.symm.trans (finsupp.map_range.add_equiv (opposite.op_add_equiv : k ≃+ kᵒᵖ))} @[simp] lemma op_ring_equiv_single [add_comm_monoid G] (r : k) (x : G) : add_monoid_algebra.op_ring_equiv (op (single x r)) = single x (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [add_comm_monoid G] (r : kᵒᵖ) (x : Gᵒᵖ) : add_monoid_algebra.op_ring_equiv.symm (single x r) = op (single x r.unop) := by simp end opposite /-- The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`. In particular this provides the instance `algebra k (add_monoid_algebra k G)`. -/ instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : algebra R (add_monoid_algebra k G) := { smul_def' := λ r a, by { ext, simp [single_zero_mul_apply, algebra.smul_def'', pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_zero_mul_apply, mul_single_zero_apply, algebra.commutes], }, ..single_zero_ring_hom.comp (algebra_map R k) } /-- `finsupp.single 0` as a `alg_hom` -/ @[simps] def single_zero_alg_hom [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : k →ₐ[R] add_monoid_algebra k G := { commutes' := λ r, by { ext, simp, refl, }, ..single_zero_ring_hom} @[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : (algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) = single 0 ∘ (algebra_map R k) := rfl end algebra section lift variables {k G} [comm_semiring k] [add_monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : multiplicative G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.alg_hom_ext k (multiplicative G) _ _ _ _ _ _ _ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : add_monoid_algebra k G →* A).comp (of k G) = (φ₂ : add_monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : add_monoid_algebra k G →* A).comp (of k G), to_fun := λ F, { to_fun := lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ F}, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ } variables {k G A} lemma lift_apply' (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F (multiplicative.of_add a)) := rfl lemma lift_apply (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F (multiplicative.of_add a)) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : multiplicative G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : add_monoid_algebra k G →ₐ[k] A) (x : multiplicative G) : (lift k G A).symm F x = F (single x.to_add 1) := rfl lemma lift_of (F : multiplicative G →* A) (x : multiplicative G) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : multiplicative G →* A) (a b) : lift k G A F (single a b) = b • F (multiplicative.of_add a) := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : add_monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : add_monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : add_monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } lemma alg_hom_ext_iff {φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A} : (∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ := ⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩ end lift section local attribute [reducible] add_monoid_algebra universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end end add_monoid_algebra variables {R : Type*} [comm_semiring R] (k G) /-- The algebra equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative`. -/ def add_monoid_algebra.to_multiplicative_alg_equiv [semiring k] [algebra R k] [add_monoid G] : add_monoid_algebra k G ≃ₐ[R] monoid_algebra k (multiplicative G) := { commutes' := λ r, by simp [add_monoid_algebra.to_multiplicative], ..add_monoid_algebra.to_multiplicative k G } /-- The algebra equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive`. -/ def monoid_algebra.to_additive_alg_equiv [semiring k] [algebra R k] [monoid G] : monoid_algebra k G ≃ₐ[R] add_monoid_algebra k (additive G) := { commutes' := λ r, by simp [monoid_algebra.to_additive], ..monoid_algebra.to_additive k G }
ab31612fa31947baae198a109e312e0807ad3879
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/group/ulift.lean
49170b7c835cc09a9c4a52aaf29a3324a5c41737
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
6,780
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.int.cast.defs import algebra.hom.equiv.basic import algebra.group_with_zero.inj_surj /-! # `ulift` instances for groups and monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines instances for group, monoid, semigroup and related structures on `ulift` types. (Recall `ulift α` is just a "copy" of a type `α` in a higher universe.) We use `tactic.pi_instance_derive_field`, even though it wasn't intended for this purpose, which seems to work fine. We also provide `ulift.mul_equiv : ulift R ≃* R` (and its additive analogue). -/ universes u v variables {α : Type u} {β : Type*} {x y : ulift.{v} α} namespace ulift @[to_additive] instance has_one [has_one α] : has_one (ulift α) := ⟨⟨1⟩⟩ @[simp, to_additive] lemma one_down [has_one α] : (1 : ulift α).down = 1 := rfl @[to_additive] instance has_mul [has_mul α] : has_mul (ulift α) := ⟨λ f g, ⟨f.down * g.down⟩⟩ @[simp, to_additive] lemma mul_down [has_mul α] : (x * y).down = x.down * y.down := rfl @[to_additive] instance has_div [has_div α] : has_div (ulift α) := ⟨λ f g, ⟨f.down / g.down⟩⟩ @[simp, to_additive] lemma div_down [has_div α] : (x / y).down = x.down / y.down := rfl @[to_additive] instance has_inv [has_inv α] : has_inv (ulift α) := ⟨λ f, ⟨f.down⁻¹⟩⟩ @[simp, to_additive] lemma inv_down [has_inv α] : x⁻¹.down = (x.down)⁻¹ := rfl @[to_additive] instance has_smul [has_smul α β] : has_smul α (ulift β) := ⟨λ n x, up (n • x.down)⟩ @[simp, to_additive] lemma smul_down [has_smul α β] (a : α) (b : ulift.{v} β) : (a • b).down = a • b.down := rfl @[to_additive has_smul, to_additive_reorder 1] instance has_pow [has_pow α β] : has_pow (ulift α) β := ⟨λ x n, up (x.down ^ n)⟩ @[simp, to_additive smul_down, to_additive_reorder 1] lemma pow_down [has_pow α β] (a : ulift.{v} α) (b : β) : (a ^ b).down = a.down ^ b := rfl /-- The multiplicative equivalence between `ulift α` and `α`. -/ @[to_additive "The additive equivalence between `ulift α` and `α`."] def _root_.mul_equiv.ulift [has_mul α] : ulift α ≃* α := { map_mul' := λ x y, rfl, .. equiv.ulift } @[to_additive] instance semigroup [semigroup α] : semigroup (ulift α) := mul_equiv.ulift.injective.semigroup _ $ λ x y, rfl @[to_additive] instance comm_semigroup [comm_semigroup α] : comm_semigroup (ulift α) := equiv.ulift.injective.comm_semigroup _ $ λ x y, rfl @[to_additive] instance mul_one_class [mul_one_class α] : mul_one_class (ulift α) := equiv.ulift.injective.mul_one_class _ rfl $ λ x y, rfl instance mul_zero_one_class [mul_zero_one_class α] : mul_zero_one_class (ulift α) := equiv.ulift.injective.mul_zero_one_class _ rfl rfl $ λ x y, rfl @[to_additive] instance monoid [monoid α] : monoid (ulift α) := equiv.ulift.injective.monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance add_monoid_with_one [add_monoid_with_one α] : add_monoid_with_one (ulift α) := { nat_cast := λ n, ⟨n⟩, nat_cast_zero := congr_arg ulift.up nat.cast_zero, nat_cast_succ := λ n, congr_arg ulift.up (nat.cast_succ _), .. ulift.has_one, .. ulift.add_monoid } @[simp] lemma nat_cast_down [add_monoid_with_one α] (n : ℕ) : (n : ulift α).down = n := rfl @[to_additive] instance comm_monoid [comm_monoid α] : comm_monoid (ulift α) := equiv.ulift.injective.comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance monoid_with_zero [monoid_with_zero α] : monoid_with_zero (ulift α) := equiv.ulift.injective.monoid_with_zero _ rfl rfl (λ _ _, rfl) (λ _ _, rfl) instance comm_monoid_with_zero [comm_monoid_with_zero α] : comm_monoid_with_zero (ulift α) := equiv.ulift.injective.comm_monoid_with_zero _ rfl rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive] instance div_inv_monoid [div_inv_monoid α] : div_inv_monoid (ulift α) := equiv.ulift.injective.div_inv_monoid _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[to_additive] instance group [group α] : group (ulift α) := equiv.ulift.injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance add_group_with_one [add_group_with_one α] : add_group_with_one (ulift α) := { int_cast := λ n, ⟨n⟩, int_cast_of_nat := λ n, congr_arg ulift.up (int.cast_of_nat _), int_cast_neg_succ_of_nat := λ n, congr_arg ulift.up (int.cast_neg_succ_of_nat _), .. ulift.add_monoid_with_one, .. ulift.add_group } @[simp] lemma int_cast_down [add_group_with_one α] (n : ℤ) : (n : ulift α).down = n := rfl @[to_additive] instance comm_group [comm_group α] : comm_group (ulift α) := equiv.ulift.injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance group_with_zero [group_with_zero α] : group_with_zero (ulift α) := equiv.ulift.injective.group_with_zero _ rfl rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance comm_group_with_zero [comm_group_with_zero α] : comm_group_with_zero (ulift α) := equiv.ulift.injective.comm_group_with_zero _ rfl rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [left_cancel_semigroup α] : left_cancel_semigroup (ulift α) := equiv.ulift.injective.left_cancel_semigroup _ (λ _ _, rfl) @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [right_cancel_semigroup α] : right_cancel_semigroup (ulift α) := equiv.ulift.injective.right_cancel_semigroup _ (λ _ _, rfl) @[to_additive add_left_cancel_monoid] instance left_cancel_monoid [left_cancel_monoid α] : left_cancel_monoid (ulift α) := equiv.ulift.injective.left_cancel_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_right_cancel_monoid] instance right_cancel_monoid [right_cancel_monoid α] : right_cancel_monoid (ulift α) := equiv.ulift.injective.right_cancel_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_cancel_monoid] instance cancel_monoid [cancel_monoid α] : cancel_monoid (ulift α) := equiv.ulift.injective.cancel_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_cancel_monoid] instance cancel_comm_monoid [cancel_comm_monoid α] : cancel_comm_monoid (ulift α) := equiv.ulift.injective.cancel_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance nontrivial [nontrivial α] : nontrivial (ulift α) := equiv.ulift.symm.injective.nontrivial -- TODO we don't do `ordered_cancel_comm_monoid` or `ordered_comm_group` -- We'd need to add instances for `ulift` in `order.basic`. end ulift
21f1a11954660e3518719d7056c3fafb36685ec2
e514e8b939af519a1d5e9b30a850769d058df4e9
/examples/rubiks_cube.lean
341a7d2e2e38332f22d15dbe65a4314b635e14dc
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
17,584
lean
import tactic.rewrite_search abbreviation C := ℕ variables X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 : C constant Rubik : C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C @[ematch] constant Rubik_1 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_3 X_5 X_8 X_2 X_7 X_1 X_4 X_6 X_33 X_34 X_35 X_12 X_13 X_14 X_15 X_16 X_9 X_10 X_11 X_20 X_21 X_22 X_23 X_24 X_17 X_18 X_19 X_28 X_29 X_30 X_31 X_32 X_25 X_26 X_27 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 @[ematch] constant Rubik_2 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_17 X_2 X_3 X_20 X_5 X_22 X_7 X_8 X_11 X_13 X_16 X_10 X_15 X_9 X_12 X_14 X_41 X_18 X_19 X_44 X_21 X_46 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_6 X_36 X_4 X_38 X_39 X_1 X_40 X_42 X_43 X_37 X_45 X_35 X_47 X_48 @[ematch] constant Rubik_3 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_25 X_28 X_30 X_9 X_10 X_8 X_12 X_7 X_14 X_15 X_6 X_19 X_21 X_24 X_18 X_23 X_17 X_20 X_22 X_43 X_26 X_27 X_42 X_29 X_41 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_11 X_13 X_16 X_44 X_45 X_46 X_47 X_48 @[ematch] constant Rubik_4 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_38 X_4 X_36 X_6 X_7 X_33 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_3 X_20 X_5 X_22 X_23 X_8 X_27 X_29 X_32 X_26 X_31 X_25 X_28 X_30 X_48 X_34 X_35 X_45 X_37 X_43 X_39 X_40 X_41 X_42 X_19 X_44 X_21 X_46 X_47 X_24 @[ematch] constant Rubik_5 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_14 X_12 X_9 X_4 X_5 X_6 X_7 X_8 X_46 X_10 X_11 X_47 X_13 X_48 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_1 X_28 X_2 X_30 X_31 X_3 X_35 X_37 X_40 X_34 X_39 X_33 X_36 X_38 X_41 X_42 X_43 X_44 X_45 X_32 X_29 X_27 @[ematch] constant Rubik_6 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_22 X_23 X_24 X_17 X_18 X_19 X_20 X_21 X_30 X_31 X_32 X_25 X_26 X_27 X_28 X_29 X_38 X_39 X_40 X_33 X_34 X_35 X_36 X_37 X_14 X_15 X_16 X_43 X_45 X_48 X_42 X_47 X_41 X_44 X_46 -- @[ematch] constant Rubik_7 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_6 X_4 X_1 X_7 X_2 X_8 X_5 X_3 X_17 X_18 X_19 X_12 X_13 X_14 X_15 X_16 X_25 X_26 X_27 X_20 X_21 X_22 X_23 X_24 X_33 X_34 X_35 X_28 X_29 X_30 X_31 X_32 X_9 X_10 X_11 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 -- @[ematch] constant Rubik_8 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_40 X_2 X_3 X_37 X_5 X_35 X_7 X_8 X_14 X_12 X_9 X_15 X_10 X_16 X_13 X_11 X_1 X_18 X_19 X_4 X_21 X_6 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_46 X_36 X_44 X_38 X_39 X_41 X_17 X_42 X_43 X_20 X_45 X_22 X_47 X_48 -- @[ematch] constant Rubik_9 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_16 X_13 X_11 X_9 X_10 X_41 X_12 X_42 X_14 X_15 X_43 X_22 X_20 X_17 X_23 X_18 X_24 X_21 X_19 X_6 X_26 X_27 X_7 X_29 X_8 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_30 X_28 X_25 X_44 X_45 X_46 X_47 X_48 -- @[ematch] constant Rubik_10 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_19 X_4 X_21 X_6 X_7 X_24 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_43 X_20 X_45 X_22 X_23 X_48 X_30 X_28 X_25 X_31 X_26 X_32 X_29 X_27 X_8 X_34 X_35 X_5 X_37 X_3 X_39 X_40 X_41 X_42 X_38 X_44 X_36 X_46 X_47 X_33 -- @[ematch] constant Rubik_11 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_27 X_29 X_32 X_4 X_5 X_6 X_7 X_8 X_3 X_10 X_11 X_2 X_13 X_1 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_48 X_28 X_47 X_30 X_31 X_46 X_38 X_36 X_33 X_39 X_34 X_40 X_37 X_35 X_41 X_42 X_43 X_44 X_45 X_9 X_12 X_14 -- @[ematch] constant Rubik_12 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_38 X_39 X_40 X_17 X_18 X_19 X_20 X_21 X_14 X_15 X_16 X_25 X_26 X_27 X_28 X_29 X_22 X_23 X_24 X_33 X_34 X_35 X_36 X_37 X_30 X_31 X_32 X_46 X_44 X_41 X_47 X_42 X_48 X_45 X_43 lemma Rubik_test_1 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 0 0 0 0 0 0 0 4 4 4 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5 5 := begin -- rewrite_search_using [`ematch], rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, sorry end -- lemma Rubik_test_2 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 0 0 1 0 1 0 0 4 4 4 5 1 5 1 1 5 1 1 2 2 2 2 2 2 2 2 3 0 3 3 0 3 3 0 4 4 4 4 4 5 5 5 5 5 3 3 3 := by rewrite_search_using [`ematch] {visualiser:=tt} -- lemma Rubik_test_3 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 0 1 0 4 3 3 4 1 1 0 1 0 2 2 2 2 2 0 2 0 5 3 3 3 3 4 3 4 5 5 4 5 4 4 5 4 5 1 0 1 5 2 1 2 1 5 3 := by rewrite_search_using [`ematch] -- lemma Rubik_test_4 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 1 4 2 4 2 3 4 0 0 0 1 1 5 5 5 1 2 1 5 0 3 2 3 0 0 0 3 3 5 5 5 3 4 3 5 0 1 4 1 4 1 2 4 2 4 3 2 := by rewrite_search_using [`ematch] -- lemma Rubik_test_5 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 0 0 2 5 2 5 5 3 3 3 1 1 1 1 1 0 2 4 5 4 5 2 4 3 3 1 3 1 3 3 1 2 4 5 2 0 2 4 0 4 0 0 4 0 4 5 5 := by rewrite_search_using [`ematch] -- lemma Rubik_test_6 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 3 3 3 1 4 1 0 5 2 0 0 5 1 2 1 1 4 4 3 5 3 5 2 2 2 3 4 2 0 1 5 4 0 0 0 2 4 5 5 1 4 1 0 4 2 5 3 3 := by rewrite_search_using [`ematch] -- lemma Rubik_test_7 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 4 0 0 2 0 1 3 4 3 1 0 3 0 5 4 0 4 2 3 4 3 3 1 1 5 1 1 5 3 5 2 2 2 2 0 4 0 5 5 3 2 4 4 5 5 2 1 1 := by rewrite_search_using [`ematch] -- lemma Rubik_test_8 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 1 5 3 4 3 0 4 0 4 4 2 1 2 1 1 0 2 1 0 0 0 3 5 0 0 1 3 1 3 5 2 4 4 3 5 5 5 3 5 2 2 4 2 4 3 5 1 := by rewrite_search_using [`ematch] -- lemma Rubik_test_9 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 5 2 5 2 1 2 4 3 1 0 3 0 0 3 5 4 0 0 4 0 4 4 2 3 1 1 1 3 1 5 4 5 4 5 2 5 5 3 2 1 1 0 0 2 3 4 3 := by rewrite_search_using [`ematch] -- lemma Rubik_test_10 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 1 2 2 5 4 0 0 4 3 3 4 3 4 2 2 5 4 3 4 5 3 2 0 4 4 0 1 3 3 2 2 1 0 1 0 1 5 5 1 5 5 2 0 1 0 3 1 := by rewrite_search_using [`ematch] -- lemma Rubik_test_20 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 0 5 1 5 3 5 3 2 4 5 5 5 0 4 2 4 2 4 4 1 1 3 1 0 3 1 2 2 4 2 3 4 1 5 0 1 5 4 2 0 0 0 0 3 3 3 2 := by rewrite_search_using [`ematch] -- lemma Rubik_test_30 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 3 4 0 4 3 2 5 1 1 4 4 0 3 2 1 0 5 1 4 3 0 5 4 4 3 1 5 1 5 1 3 0 0 2 4 5 2 2 2 2 1 3 3 2 5 0 0 := by rewrite_search_using [`ematch] -- lemma Rubik_test_40 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 4 5 4 1 0 5 3 4 0 2 1 3 0 1 4 3 3 2 4 5 0 2 3 5 2 2 1 2 4 2 5 1 5 3 3 0 4 3 1 1 0 5 4 5 2 0 1 := by rewrite_search_using [`ematch] -- lemma Rubik_test_50 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 0 1 4 4 3 5 0 5 1 4 1 0 3 3 0 0 3 2 2 1 2 5 5 3 0 0 2 1 1 2 3 4 3 4 5 0 5 5 5 1 2 2 4 3 4 4 2 := by rewrite_search_using [`ematch] -- lemma Rubik_test_60 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 4 5 1 3 5 5 1 0 5 5 3 4 4 1 3 4 2 4 2 0 2 3 4 1 3 2 5 0 3 0 2 4 2 1 3 2 3 1 0 0 0 5 2 0 1 4 1 5 := by rewrite_search_using [`ematch] -- lemma Rubik_test_70 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 3 1 5 4 5 4 0 1 4 3 4 2 1 5 2 2 1 3 5 0 1 2 5 4 3 4 1 2 3 2 3 5 5 4 0 0 2 3 5 0 3 4 1 1 2 0 0 := by rewrite_search_using [`ematch] -- lemma Rubik_test_80 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 0 2 0 1 0 4 1 2 3 3 4 3 5 1 5 4 5 5 4 2 4 2 0 2 2 3 5 5 1 2 1 0 1 3 3 1 0 4 4 1 3 4 5 0 3 0 2 := by rewrite_search_using [`ematch] -- lemma Rubik_test_90 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 3 1 3 2 4 4 3 2 0 3 4 4 1 5 0 5 1 2 0 0 3 2 0 5 1 4 1 5 1 5 3 5 4 5 2 5 0 2 2 2 0 4 3 1 0 3 4 := by rewrite_search_using [`ematch] -- lemma Rubik_test_100 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 2 3 2 1 3 5 1 1 3 4 1 0 2 1 1 0 1 4 3 4 2 0 0 5 0 5 0 3 2 5 5 4 5 4 4 4 2 3 3 5 2 1 2 4 0 5 3 := by rewrite_search_using [`ematch] -- lemma Rubik_test_200 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 3 3 1 1 1 1 2 0 0 2 2 3 4 3 5 0 4 1 5 5 3 5 1 5 2 2 1 3 4 2 4 5 2 3 0 5 1 0 0 4 4 0 4 0 3 4 5 := by rewrite_search_using [`ematch] -- lemma Rubik_test_300 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 1 3 4 3 4 1 0 1 3 1 2 4 0 4 3 0 5 3 5 2 5 1 5 4 2 5 5 0 4 3 2 4 4 0 3 0 5 2 2 2 0 1 0 5 3 1 1 := by rewrite_search_using [`ematch] -- lemma Rubik_test_400 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 4 5 4 0 3 0 0 4 1 0 5 5 5 1 0 2 3 4 3 3 2 0 1 1 1 1 4 4 2 2 5 4 0 3 5 2 3 1 3 1 2 5 5 3 2 2 4 := by rewrite_search_using [`ematch] -- lemma Rubik_test_500 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 2 3 2 0 1 3 5 5 0 2 2 1 2 5 0 0 4 1 0 1 4 1 5 4 3 0 4 2 3 4 4 2 3 1 5 1 0 0 5 3 5 4 3 5 3 4 1 := by rewrite_search_using [`ematch] -- lemma Rubik_test_600 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 4 4 4 3 0 1 5 5 1 0 5 0 2 0 3 2 2 1 3 3 5 0 4 4 2 2 0 2 5 5 2 1 3 1 5 3 4 4 0 1 3 5 3 4 1 2 1 0 := by rewrite_search_using [`ematch] -- lemma Rubik_test_700 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 0 3 4 4 5 2 4 2 3 2 1 1 5 4 0 1 3 0 5 2 2 4 1 3 1 5 5 3 4 0 2 4 3 3 5 0 0 1 1 1 0 0 5 2 4 2 3 := by rewrite_search_using [`ematch] -- lemma Rubik_test_800 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 1 5 3 0 5 3 5 2 4 1 0 5 3 1 0 4 5 3 4 5 1 1 0 2 1 2 2 3 3 3 4 1 5 1 0 2 3 0 5 4 2 2 4 2 4 4 0 := by rewrite_search_using [`ematch] -- lemma Rubik_test_900 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 0 5 0 4 1 1 0 2 2 4 2 1 4 2 2 5 5 2 0 4 5 2 3 3 5 4 1 0 0 3 5 3 3 1 4 3 2 5 1 1 5 4 1 4 0 3 3 := by rewrite_search_using [`ematch] -- lemma Rubik_test_1000 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 3 2 4 0 5 5 5 0 4 4 2 4 3 3 2 5 1 1 2 5 1 2 0 4 3 4 1 2 4 1 2 1 0 5 5 3 1 0 1 4 3 3 5 3 0 0 0 2 := by rewrite_search_using [`ematch]