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
508dac691d912ffc736827405340c6ab8d4ac617
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.9.lean
e5f01a9786208b7ad5bc1dfe6d5563ef0661fed0
[]
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
240
lean
/- page 103 -/ import standard import data.list open list definition append {A : Type} : list A → list A → list A | append nil l := l | append (h::t) l := h :: append t l example : append [1, 2, 3] [4, 5] = [1, 2, 3, 4, 5] := rfl
35ed83c2ea828b8c77b0799ea7254a137719d54f
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/measure_theory/function/special_functions.lean
ea59cf3c3a963b0fc4e83d4f6aec6c8afbcfb73d
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,460
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.special_functions.pow import analysis.special_functions.trigonometric.arctan import analysis.inner_product_space.calculus import measure_theory.constructions.borel_space /-! # Measurability of real and complex functions We show that most standard real and complex functions are measurable, notably `exp`, `cos`, `sin`, `cosh`, `sinh`, `log`, `pow`, `arcsin`, `arccos`, `arctan`, and scalar products. -/ noncomputable theory open_locale nnreal ennreal namespace real @[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable @[measurability] lemma measurable_log : measurable log := measurable_of_measurable_on_compl_singleton 0 $ continuous.measurable $ continuous_on_iff_continuous_restrict.1 continuous_on_log @[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable @[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable @[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable @[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable @[measurability] lemma measurable_arcsin : measurable arcsin := continuous_arcsin.measurable @[measurability] lemma measurable_arccos : measurable arccos := continuous_arccos.measurable @[measurability] lemma measurable_arctan : measurable arctan := continuous_arctan.measurable end real namespace complex @[measurability] lemma measurable_re : measurable re := continuous_re.measurable @[measurability] lemma measurable_im : measurable im := continuous_im.measurable @[measurability] lemma measurable_of_real : measurable (coe : ℝ → ℂ) := continuous_of_real.measurable @[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable @[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable @[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable @[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable @[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable @[measurability] lemma measurable_arg : measurable arg := have A : measurable (λ x : ℂ, real.arcsin (x.im / x.abs)), from real.measurable_arcsin.comp (measurable_im.div measurable_norm), have B : measurable (λ x : ℂ, real.arcsin ((-x).im / x.abs)), from real.measurable_arcsin.comp ((measurable_im.comp measurable_neg).div measurable_norm), measurable.ite (is_closed_le continuous_const continuous_re).measurable_set A $ measurable.ite (is_closed_le continuous_const continuous_im).measurable_set (B.add_const _) (B.sub_const _) @[measurability] lemma measurable_log : measurable log := (measurable_of_real.comp $ real.measurable_log.comp measurable_norm).add $ (measurable_of_real.comp measurable_arg).mul_const I end complex namespace is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [opens_measurable_space 𝕜] @[measurability] lemma measurable_re : measurable (re : 𝕜 → ℝ) := continuous_re.measurable @[measurability] lemma measurable_im : measurable (im : 𝕜 → ℝ) := continuous_im.measurable end is_R_or_C section real_composition open real variables {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) @[measurability] lemma measurable.exp : measurable (λ x, real.exp (f x)) := real.measurable_exp.comp hf @[measurability] lemma measurable.log : measurable (λ x, log (f x)) := measurable_log.comp hf @[measurability] lemma measurable.cos : measurable (λ x, real.cos (f x)) := real.measurable_cos.comp hf @[measurability] lemma measurable.sin : measurable (λ x, real.sin (f x)) := real.measurable_sin.comp hf @[measurability] lemma measurable.cosh : measurable (λ x, real.cosh (f x)) := real.measurable_cosh.comp hf @[measurability] lemma measurable.sinh : measurable (λ x, real.sinh (f x)) := real.measurable_sinh.comp hf @[measurability] lemma measurable.arctan : measurable (λ x, arctan (f x)) := measurable_arctan.comp hf @[measurability] lemma measurable.sqrt : measurable (λ x, sqrt (f x)) := continuous_sqrt.measurable.comp hf end real_composition section complex_composition open complex variables {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) @[measurability] lemma measurable.cexp : measurable (λ x, complex.exp (f x)) := complex.measurable_exp.comp hf @[measurability] lemma measurable.ccos : measurable (λ x, complex.cos (f x)) := complex.measurable_cos.comp hf @[measurability] lemma measurable.csin : measurable (λ x, complex.sin (f x)) := complex.measurable_sin.comp hf @[measurability] lemma measurable.ccosh : measurable (λ x, complex.cosh (f x)) := complex.measurable_cosh.comp hf @[measurability] lemma measurable.csinh : measurable (λ x, complex.sinh (f x)) := complex.measurable_sinh.comp hf @[measurability] lemma measurable.carg : measurable (λ x, arg (f x)) := measurable_arg.comp hf @[measurability] lemma measurable.clog : measurable (λ x, log (f x)) := measurable_log.comp hf end complex_composition section is_R_or_C_composition variables {α 𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space α] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → 𝕜} {μ : measure_theory.measure α} @[measurability] lemma measurable.re (hf : measurable f) : measurable (λ x, is_R_or_C.re (f x)) := is_R_or_C.measurable_re.comp hf @[measurability] lemma ae_measurable.re (hf : ae_measurable f μ) : ae_measurable (λ x, is_R_or_C.re (f x)) μ := is_R_or_C.measurable_re.comp_ae_measurable hf @[measurability] lemma measurable.im (hf : measurable f) : measurable (λ x, is_R_or_C.im (f x)) := is_R_or_C.measurable_im.comp hf @[measurability] lemma ae_measurable.im (hf : ae_measurable f μ) : ae_measurable (λ x, is_R_or_C.im (f x)) μ := is_R_or_C.measurable_im.comp_ae_measurable hf end is_R_or_C_composition section pow_instances instance complex.has_measurable_pow : has_measurable_pow ℂ ℂ := ⟨measurable.ite (measurable_fst (measurable_set_singleton 0)) (measurable.ite (measurable_snd (measurable_set_singleton 0)) measurable_one measurable_zero) (measurable_fst.clog.mul measurable_snd).cexp⟩ instance real.has_measurable_pow : has_measurable_pow ℝ ℝ := ⟨complex.measurable_re.comp $ ((complex.measurable_of_real.comp measurable_fst).pow (complex.measurable_of_real.comp measurable_snd))⟩ instance nnreal.has_measurable_pow : has_measurable_pow ℝ≥0 ℝ := ⟨(measurable_fst.coe_nnreal_real.pow measurable_snd).subtype_mk⟩ instance ennreal.has_measurable_pow : has_measurable_pow ℝ≥0∞ ℝ := begin refine ⟨ennreal.measurable_of_measurable_nnreal_prod _ _⟩, { simp_rw ennreal.coe_rpow_def, refine measurable.ite _ measurable_const (measurable_fst.pow measurable_snd).coe_nnreal_ennreal, exact measurable_set.inter (measurable_fst (measurable_set_singleton 0)) (measurable_snd measurable_set_Iio), }, { simp_rw ennreal.top_rpow_def, refine measurable.ite measurable_set_Ioi measurable_const _, exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const, }, end end pow_instances section variables {α : Type*} {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y @[measurability] lemma measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜] {f g : α → E} (hf : measurable f) (hg : measurable g) : measurable (λ t, ⟪f t, g t⟫) := continuous.measurable2 continuous_inner hf hg @[measurability] lemma ae_measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜] {μ : measure_theory.measure α} {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, ⟪f x, g x⟫) μ := begin refine ⟨λ x, ⟪hf.mk f x, hg.mk g x⟫, hf.measurable_mk.inner hg.measurable_mk, _⟩, refine hf.ae_eq_mk.mp (hg.ae_eq_mk.mono (λ x hxg hxf, _)), dsimp only, congr, { exact hxf, }, { exact hxg, }, end end
8f9133631271b633294f4da2bb67022b1e9c4cd0
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/time_expr_current_old_4-8.lean
bf9c69d8cf384cbf1fff1634cd43ec553c827473
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
19,835
lean
import .expr_base import ...phys.time.time namespace lang.time universes u variables (K : Type u) [field K] [inhabited K] {f : fm K TIME} {sp : spc K f} /- Duration -/ structure duration_var {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) extends var /- Time -/ structure time_var {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) extends var mutual inductive duration_expr, time_expr {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) with duration_expr : Type u | lit (v : duration sp) : duration_expr | var (v : duration_var sp) : duration_expr | add_dur_dur (d1 : duration_expr) (d2 : duration_expr) : duration_expr | neg_dur (d : duration_expr) : duration_expr | sub_dur_dur (d1 : duration_expr) (d2 : duration_expr) : duration_expr | sub_time_time (t1 : time_expr) (t2 : time_expr) : duration_expr | smul_dur (k : K) (d : duration_expr) : duration_expr with time_expr : Type u | lit (p : time sp) : time_expr | var (v : time_var sp) : time_expr | add_dur_time (d : duration_expr) (t : time_expr) : time_expr abbreviation duration_env {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) := duration_var sp → duration sp abbreviation duration_eval {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) := duration_env sp → duration_expr sp → duration sp abbreviation time_env {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) := time_var sp → time sp abbreviation time_eval {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) := time_env sp → time_expr sp → time sp structure time_frame_var (K : Type u) [field K] [inhabited K] extends var inductive time_frame_expr (K : Type u) [field K] [inhabited K] : Type u --{f : fm K T} | lit (f : fm K TIME) : time_frame_expr | var (v : time_frame_var K) : time_frame_expr /- I have varying opinions on what exactly the parameters to the derived constructor should be. -/ | derived {f : fm K TIME} {sp : spc K f} (o : time_expr sp) (b : duration_expr sp) : time_frame_expr structure time_space_var {K : Type u} [field K] [inhabited K] (f : fm K TIME) extends var inductive time_space_expr {K : Type u} [field K] [inhabited K] (f : fm K TIME) : Type (u+1) | lit (sp : spc K f) : time_space_expr | var (v : time_space_var f) : time_space_expr | mk (f : time_frame_expr K) : time_space_expr abbreviation time_frame_env (K : Type u) [field K] [inhabited K] := time_frame_var K → fm K TIME abbreviation time_frame_eval (K : Type u) [field K] [inhabited K] := time_frame_env K → time_frame_expr K → fm K TIME /-You need to indicate explicitly what type of frame you think the space has, because the environment needs a hint about the expected return type which does trivialize the point of the environment in a way, since parameterized spc types only have a single value per frame-/ abbreviation time_space_env {K : Type u} [field K] [inhabited K] (f : fm K TIME) := time_space_var f → spc K f abbreviation time_space_eval {K : Type u} [field K] [inhabited K] (f : fm K TIME) := time_space_env f → time_space_expr f → spc K f --not working -- lean doesn't play nice with notation and dependent types --notation `[`flit`]` := time_frame_expr.lit flit --notation `[`slit`]` := time_space_expr.lit slit --instance {K : Type u} [field K] [inhabited K] {f : fm K TIME} {sp : spc K f} : has_coe (time sp) (time_expr sp) := ⟨λt, time_expr.lit t⟩ --instance {K : Type u} [field K] [inhabited K] {f : fm K TIME} {sp : spc K f} : has_coe (duration sp) (duration_expr sp) := ⟨λt, duration_expr.lit t⟩ --instance {K : Type u} [field K] [inhabited K] : has_coe (fm K TIME) (time_frame_expr K) := ⟨λf, time_frame_expr.lit f⟩ --instance {K : Type u} [field K] [inhabited K] {f : fm K TIME} : has_coe (spc K f) (time_space_expr K) := ⟨λs, time_space_expr.lit s⟩ #check has_add class time_has_lit {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) := (cast : time sp → time_expr sp) notation `[`tlit`]` := time_has_lit.cast tlit instance time_lit {K : Type u} [field K] [inhabited K] {f : fm K TIME} {sp : spc K f} : time_has_lit sp := ⟨λt : time sp, time_expr.lit t⟩ class duration_has_lit {K : Type u} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) := (cast : duration sp → duration_expr sp) notation `[`tlit`]` := duration_has_lit.cast tlit instance duration_lit {K : Type u} [field K] [inhabited K] {f : fm K TIME} {sp : spc K f} : duration_has_lit sp := ⟨λt : duration sp, duration_expr.lit t⟩ class time_frame_has_lit (K : Type u) [field K] [inhabited K] := (cast : fm K TIME → time_frame_expr K) notation `[`flit`]` := time_frame_has_lit.cast flit instance time_frame_lit {K : Type u} [field K] [inhabited K] : time_frame_has_lit K := ⟨λf, time_frame_expr.lit f⟩ class time_space_has_lit {K : Type u} [field K] [inhabited K] (f : fm K TIME) := (cast : spc K f → time_space_expr f) notation `[`slit`]` := time_space_has_lit.cast slit instance time_space_lit {K : Type u} [field K] [inhabited K] {f : fm K TIME} : time_space_has_lit f := ⟨λs, time_space_expr.lit s⟩ /- Analogous methods provided at math layer -/ #check mk_frame def mk_time_frame_expr {f : fm K TIME} {sp : spc K f} (o : time_expr sp) (b : duration_expr sp) : time_frame_expr K := time_frame_expr.derived o b /- 4/7 WRITE THIS FUNCTION LATER. YOU NEED TO GET THE VALUE OUT OF THE f PARAMETER TO INCLUDE IT IN THE TYPE AND THEN USE IT IN THE CONSTRUCTOR -/ #check mk_space def mk_time_space_expr (K : Type u) [field K] [inhabited K] (f : time_frame_expr K) : time_space_expr K := time_space_expr.mk f def add_dur_expr_dur_expr (v1 v2 : duration_expr sp) : duration_expr sp := duration_expr.add_dur_dur v1 v2 def smul_dur_expr (k : K) (v : duration_expr sp) : duration_expr sp := duration_expr.smul_dur k v def neg_dur_expr (v : duration_expr sp) : duration_expr sp := duration_expr.neg_dur v def sub_dur_expr_dur_expr (v1 v2 : duration_expr sp) : duration_expr sp := -- v1-v2 duration_expr.sub_dur_dur v1 v2 -- See unframed file for template for proving vector_space instance has_add_dur_expr : has_add (duration_expr sp) := ⟨ add_dur_expr_dur_expr K ⟩ lemma add_assoc_dur_expr : ∀ a b c : duration_expr sp, a + b + c = a + (b + c) := sorry instance add_semigroup_dur_expr : add_semigroup (duration_expr sp) := ⟨ add_dur_expr_dur_expr K, add_assoc_dur_expr K⟩ def dur_expr_zero := duration_expr.lit (mk_duration sp 0) instance has_zero_dur_expr : has_zero (duration_expr sp) := ⟨dur_expr_zero K⟩ lemma zero_add_dur_expr : ∀ a : duration_expr sp, 0 + a = a := sorry lemma add_zero_dur_expr : ∀ a : duration_expr sp, a + 0 = a := sorry instance add_monoid_dur_expr : add_monoid (duration_expr sp) := ⟨ -- add_semigroup add_dur_expr_dur_expr K, add_assoc_dur_expr K, -- has_zero dur_expr_zero K, -- new structure @zero_add_dur_expr K _ _ f sp, add_zero_dur_expr K ⟩ instance has_neg_dur_expr : has_neg (duration_expr sp) := ⟨neg_dur_expr K⟩ instance has_sub_dur_expr : has_sub (duration_expr sp) := ⟨ sub_dur_expr_dur_expr K⟩ lemma sub_eq_add_neg_dur_expr : ∀ a b : duration_expr sp, a - b = a + -b := sorry instance sub_neg_monoid_dur_expr : sub_neg_monoid (duration_expr sp) := ⟨ add_dur_expr_dur_expr K, add_assoc_dur_expr K, dur_expr_zero K, zero_add_dur_expr K, add_zero_dur_expr K, -- add_monoid neg_dur_expr K, -- has_neg sub_dur_expr_dur_expr K, -- has_sub sub_eq_add_neg_dur_expr K, -- new ⟩ lemma add_left_neg_dur_expr : ∀ a : duration_expr sp, -a + a = 0 := sorry instance : add_group (duration_expr sp) := ⟨ -- sub_neg_monoid add_dur_expr_dur_expr K, add_assoc_dur_expr K, dur_expr_zero K, zero_add_dur_expr K, add_zero_dur_expr K, -- add_monoid neg_dur_expr K, -- has_neg sub_dur_expr_dur_expr K, -- has_sub sub_eq_add_neg_dur_expr K, -- new add_left_neg_dur_expr K, ⟩ lemma add_comm_dur_expr : ∀ a b : duration_expr sp, a + b = b + a := sorry instance add_comm_semigroup_dur_expr : add_comm_semigroup (duration_expr sp) := ⟨ -- add_semigroup add_dur_expr_dur_expr K, add_assoc_dur_expr K, add_comm_dur_expr K, ⟩ instance add_comm_monoid_dur_expr : add_comm_monoid (duration_expr sp) := ⟨ -- add_monoid -- add_semigroup add_dur_expr_dur_expr K, add_assoc_dur_expr K, -- has_zero dur_expr_zero K, -- new structure zero_add_dur_expr K, add_zero_dur_expr K, -- add_comm_semigroup (minus repeats) add_comm_dur_expr K, ⟩ instance has_scalar_dur_expr : has_scalar K (duration_expr sp) := ⟨ smul_dur_expr K, ⟩ lemma one_smul_dur_expr : ∀ b : duration_expr sp, (1 : K) • b = b := sorry lemma mul_smul_dur_expr : ∀ (x y : K) (b : duration_expr sp), (x * y) • b = x • y • b := sorry instance mul_action_dur_expr : mul_action K (duration_expr sp) := ⟨ one_smul_dur_expr K, mul_smul_dur_expr K, ⟩ lemma smul_add_dur_expr : ∀(r : K) (x y : duration_expr sp), r • (x + y) = r • x + r • y := sorry lemma smul_zero_dur_expr : ∀(r : K), r • (0 : duration_expr sp) = 0 := sorry instance distrib_mul_action_K_dur_exprKx : distrib_mul_action K (duration_expr sp) := ⟨ smul_add_dur_expr K, smul_zero_dur_expr K, ⟩ -- renaming vs template due to clash with name "s" for prevailing variable lemma add_smul_dur_expr : ∀ (a b : K) (x : duration_expr sp), (a + b) • x = a • x + b • x := sorry lemma zero_smul_dur_expr : ∀ (x : duration_expr sp), (0 : K) • x = 0 := sorry instance semimodule_K_durationK : semimodule K (duration_expr sp) := ⟨ add_smul_dur_expr K, zero_smul_dur_expr K⟩ instance add_comm_group_dur_expr : add_comm_group (duration_expr sp) := ⟨ -- add_group add_dur_expr_dur_expr K, add_assoc_dur_expr K, dur_expr_zero K, zero_add_dur_expr K, add_zero_dur_expr K, -- add_monoid neg_dur_expr K, -- has_neg sub_dur_expr_dur_expr K, -- has_sub sub_eq_add_neg_dur_expr K, add_left_neg_dur_expr K, -- commutativity add_comm_dur_expr K, ⟩ instance : vector_space K (duration_expr sp) := sorry /- ******************** *** Affine space *** ******************** -/ /- Affine operations -/ instance : has_add (duration_expr sp) := ⟨add_dur_expr_dur_expr K⟩ instance : has_zero (duration_expr sp) := ⟨dur_expr_zero K⟩ instance : has_neg (duration_expr sp) := ⟨neg_dur_expr K⟩ /- Lemmas needed to implement affine space API -/ def sub_time_expr_time_expr {f : fm K TIME} {sp : spc K f } (p1 p2 : time_expr sp) : duration_expr sp := duration_expr.sub_time_time p1 p2 def add_time_expr_dur_expr {f : fm K TIME} {sp : spc K f } (p : time_expr sp) (v : duration_expr sp) : time_expr sp := time_expr.add_dur_time v p def add_dur_expr_time_expr {f : fm K TIME} {sp : spc K f } (v : duration_expr sp) (p : time_expr sp) : time_expr sp := time_expr.add_dur_time v p def aff_dur_expr_group_action : duration_expr sp → time_expr sp → time_expr sp := add_dur_expr_time_expr K instance : has_vadd (duration_expr sp) (time_expr sp) := ⟨aff_dur_expr_group_action K⟩ lemma zero_dur_expr_vadd'_a1 : ∀ p : time_expr sp, (0 : duration_expr sp) +ᵥ p = p := sorry lemma dur_expr_add_assoc'_a1 : ∀ (g1 g2 : duration_expr sp) (p : time_expr sp), g1 +ᵥ (g2 +ᵥ p) = (g1 + g2) +ᵥ p := sorry instance dur_expr_add_action: add_action (duration_expr sp) (time_expr sp) := ⟨ aff_dur_expr_group_action K, zero_dur_expr_vadd'_a1 K, dur_expr_add_assoc'_a1 K⟩ def aff_time_expr_group_sub : time_expr sp → time_expr sp → duration_expr sp := sub_time_expr_time_expr K instance time_expr_has_vsub : has_vsub (duration_expr sp) (time_expr sp) := ⟨ aff_time_expr_group_sub K ⟩ instance : nonempty (time_expr sp) := ⟨time_expr.lit (mk_time sp 0)⟩ lemma time_expr_vsub_vadd_a1 : ∀ (p1 p2 : (time_expr sp)), (p1 -ᵥ p2) +ᵥ p2 = p1 := sorry lemma time_expr_vadd_vsub_a1 : ∀ (g : duration_expr sp) (p : time_expr sp), g +ᵥ p -ᵥ p = g := sorry instance aff_time_expr_torsor : add_torsor (duration_expr sp) (time_expr sp) := --affine space! ⟨ aff_dur_expr_group_action K, zero_dur_expr_vadd'_a1 K, -- add_action dur_expr_add_assoc'_a1 K, -- add_action aff_time_expr_group_sub K, -- has_vsub time_expr_vsub_vadd_a1 K, -- add_torsor time_expr_vadd_vsub_a1 K, -- add_torsor ⟩ /- + : d s -> d s -> d s • : K -> d s -> d s +ᵥ : d s -> t s -> t s -ᵥ : t s -> t s -> d s Here s is an affine coordinate space on TIME. Otherwise we've got time points and durations, within, but not across, spaces. -/ /- Transform -/ structure transform_var {K : Type u} [field K] [inhabited K] {f1 : fm K TIME} {f2 : fm K TIME} (sp1 : spc K f1) (sp2 : spc K f2) extends var /- inductive transform_expr {K : Type u} [field K] [inhabited K] --{f1 : fm K TIME} {f2 : fm K TIME} (sp1 : spc K f1) (sp2:=sp1 : spc K f2) -- (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2 := sp1) : Π {f1 : fm K TIME} (sp1 : spc K f1), Π {f2 : fm K TIME} (sp2 : spc K f2), Type u | lit {f1 : fm K TIME} (sp1 : spc K f1) {f2 : fm K TIME} (sp2 : spc K f2) (p : time_transform sp1 sp2) : transform_expr sp1 sp2 | var (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_var sp1.2 sp2.2) : transform_expr sp1 sp2 | apply_duration (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_expr sp1 sp2) (d : duration_expr sp1.2) : transform_expr sp1 sp2 | compose (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : time_transform sp1.2 sp2.2) (sp3 : Σf3 : fm K TIME, spc K f3) (v : time_transform sp1 sp2) : transform_expr sp1 sp3 -/ /- invalid occurrence of recursive arg#7 of 'lang.time.transform_expr.compose', the body of the functional type depends on it. All Messages (28) PROBLEM WITH TRANSFORM EXPRESSIONS -/ /- inductive transform_expr' {K : Type u} [field K] [inhabited K] --{f1 : fm K TIME} {f2 : fm K TIME} (sp1 : spc K f1) (sp2:=sp1 : spc K f2) -- (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2 := sp1) : Π {f1 : fm K TIME} (sp1 : spc K f1), Π {f2 : fm K TIME} (sp2 : spc K f2), Type u | lit {f1 : fm K TIME} (sp1 : spc K f1) {f2 : fm K TIME} (sp2 : spc K f2) (p : time_transform sp1 sp2) : transform_expr' sp1 sp2 | var (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_var sp1.2 sp2.2) : transform_expr' sp1.2 sp2.2 | apply_duration (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_expr' sp1.2 sp2.2) (d : duration_expr sp1.2) : transform_expr' sp1.2 sp2.2 | compose (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_expr' sp1.2 sp2.2) (sp3 : Σf3 : fm K TIME, spc K f3) (v : transform_expr' sp2.2 sp3.2) : transform_expr' sp1.2 sp3.2 -/ inductive transform_expr {K : Type u} [field K] [inhabited K] --{f1 : fm K TIME} {f2 : fm K TIME} (sp1 : spc K f1) (sp2:=sp1 : spc K f2) -- (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2 := sp1) : Π {f1 : fm K TIME} (sp1 : spc K f1), Π {f2 : fm K TIME} (sp2 : spc K f2), Type u | lit {f1 : fm K TIME} {sp1 : spc K f1} {f2 : fm K TIME} {sp2 : spc K f2} (p : time_transform sp1 sp2) : transform_expr sp1 sp2 | var {f1 : fm K TIME} {sp1 : spc K f1} {f2 : fm K TIME} {sp2 : spc K f2} (v : transform_var sp1 sp2) : transform_expr sp1 sp2 | apply_duration {f1 : fm K TIME} {sp1 : spc K f1} {f2 : fm K TIME} {sp2 : spc K f2} (v : transform_expr sp1 sp2) (d : duration_expr sp1) : transform_expr sp1 sp2 | compose_lit {f1 : fm K TIME} {sp1 : spc K f1} {f2 : fm K TIME} {sp2 : spc K f2} (v : time_transform sp1 sp2) {f3 : fm K TIME} {sp3 : spc K f3} (v : time_transform sp2 sp3) : transform_expr sp1 sp3 class time_transform_has_lit {K : Type u} [field K] [inhabited K] {f1 : fm K TIME} (sp1 : spc K f1) {f2 : fm K TIME} (sp2 : spc K f2) := (cast : time_transform sp1 sp2 → transform_expr sp1 sp2) notation `[`tlit`]` := time_transform_has_lit.cast tlit instance time_transform_lit {K : Type u} [field K] [inhabited K] {f1 : fm K TIME} {sp1 : spc K f1} {f2 : fm K TIME} {sp2 : spc K f2} : time_transform_has_lit sp1 sp2 := ⟨λt, transform_expr.lit t⟩ /- inductive transform_expr {K : Type u} [field K] [inhabited K] --{f1 : fm K TIME} {f2 : fm K TIME} (sp1 : spc K f1) (sp2:=sp1 : spc K f2) -- (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2 := sp1) : Σf1 : fm K TIME, spc K f1 → Σf2 : fm K TIME, spc K f2 → Type u | lit (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (p : time_transform sp1.1 sp1.2) : transform_expr --| var (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_var sp1.1 sp1.2) : transform_expr sp1 sp2 --| apply_duration (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_expr ) (d : duration_expr sp) : transform_expr sp1 sp2 --| compose (sp1 : Σf1 : fm K TIME, spc K f1) (sp2 : Σf2 : fm K TIME, spc K f2) (v : transform_expr sp1 sp2) -- (sp3 : Σf3 : fm K TIME, spc K f3) (v : transform_expr sp2 sp3) : transform_expr sp1 sp3 -/ abbreviation transform_env {K : Type u} [field K] [inhabited K] {f1 : fm K TIME} {f2 : fm K TIME} (sp1 : spc K f1) (sp2 : spc K f2) := transform_var sp1 sp2 → time_transform sp1 sp2 abbreviation transform_eval {K : Type u} [field K] [inhabited K] {f1 : fm K TIME} {f2 : fm K TIME} (sp1 : spc K f1) (sp2 : spc K f2) := transform_env sp1 sp2 → transform_expr sp1 sp2 → time_transform sp1 sp2 variables {f2 : fm K TIME} (sp2 : spc K f2) structure env {K : Type u} [field K] [inhabited K] -- {f : fm K TIME} (sp : spc K f) {f2 : fm K TIME} {sp2 : spc K f2} := := (duration : Π {f : fm K TIME}, Π (sp : spc K f), duration_env sp ) (time : Π {f : fm K TIME}, Π (sp : spc K f), time_env sp ) (transform : Π {f1 : fm K TIME}, Π (sp1 : spc K f1), Π {f2 : fm K TIME}, Π (sp2 : spc K f2), transform_env sp1 sp2) (frame : time_frame_env K) (space : Π (f : fm K TIME), time_space_env f) def env.init (K : Type u) [field K] [inhabited K] : env := ⟨ (λf: fm K TIME, λsp, λv, ⟨mk_vectr sp 1⟩), (λf: fm K TIME, λsp, λv, ⟨mk_point sp 0⟩), (λf: fm K TIME, λsp1, λf2, λsp2, (λv, sp1.time_tr sp2)), (λv, time_std_frame K), (λf, (λv, mk_space K f)) ⟩ structure eval {K : Type u} [field K] [inhabited K] := (duration : Π {f : fm K TIME}, Π (sp : spc K f), duration_eval sp ) (time : Π {f : fm K TIME}, Π (sp : spc K f), time_eval sp ) (transform : Π {f1 : fm K TIME}, Π (sp1 : spc K f1), Π {f2 : fm K TIME}, Π (sp2 : spc K f2), transform_eval sp1 sp2) (frame : time_frame_eval K) (space : Π (f : fm K TIME), time_space_eval f) def eval.init (K : Type u) [field K] [inhabited K] : eval := ⟨ (λf: fm K TIME, λsp, λenv_,λexpr_, ⟨mk_vectr sp 1⟩), (λf: fm K TIME, λsp, λenv_,λexpr_, ⟨mk_point sp 0⟩), (λf: fm K TIME, λsp1, λf2, λsp2, (λenv_,λexpr_, sp1.time_tr sp2 : transform_eval sp1 sp2)), (λenv_, λexpr_, time_std_frame K), (λf, λenv_, λexpr_, mk_space K f) ⟩ end lang.time
2a084c1ae548783424375e3eb0c0b0867398c075
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/nary_overload.lean
019f0800070e4b4a025426c29f832db2da8416c5
[ "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
575
lean
prelude constant {l} vec : Type l → Type l constant {l} lst : Type l → Type l constant vec.nil {A : Type} : vec A constant lst.nil {A : Type} : lst A constant vec.cons {A : Type} : A → vec A → vec A constant lst.cons {A : Type} : A → lst A → lst A notation `[` l:(foldr `, ` (h t, vec.cons h t) vec.nil `]`) := l notation `[` l:(foldr `, ` (h t, lst.cons h t) lst.nil `]`) := l constant A : Type variables a b c : A check [a, b, c] check ([a, b, c] : vec A) check ([a, b, c] : lst A) set_option pp.all true check ([a, b, c] : vec A) check ([a, b, c] : lst A)
13201287eb98b341e962f301b20231a0e107a01a
dde4c4e99f4467a499e1166ed3f2f730b1a9b4bc
/my_project/src/PPT_properties.lean
703b8cb4c5a5e1021fc5826b26eae95748bf7fe7
[]
no_license
lcenek21/PPT-Properties
46cece134dde50aa2ec137865efdd252a4d0ae8d
64aa68179bf8bacafac2c768929d2a959226266b
refs/heads/main
1,692,243,205,457
1,632,365,679,000
1,632,365,679,000
409,422,057
0
0
null
null
null
null
UTF-8
Lean
false
false
6,329
lean
import data.zmod.parity import number_theory.pythagorean_triples import number_theory.quadratic_reciprocity /- Authors: Lisa Cenek, Brittany Gelb -/ /- Several useful elementary properties of primitive pythagorean triples follow nicely from the classification theorem. We formalize some of those properties, starting with divisibility by 3 and 4. -/ open pythagorean_triple /- If x,y,z is a primitive pythagorean triple, then exactly one of x,y is 0 mod 4. -/ theorem pythagorean_triple_exactly_one_div_four {x y z : ℤ} (h : pythagorean_triple x y z) (h_coprime : int.gcd x y = 1): ((x % 4 = 0) ∧ (y % 4 ≠ 0)) ∨ ((x % 4 ≠ 0) ∧ (y % 4 = 0)) := begin have k : pythagorean_triple x y z ∧ int.gcd x y = 1, split, exact h, exact h_coprime, rw coprime_classification at k, cases k with m km, cases km with n kmn, cases kmn with k1 k2, cases k2 with k2 k3, cases k3 with k3 k4, cases k4 with k4 k5, { cases k1 with y_even x_even, { right, cases y_even with x_odd y_even, cases k4 with k4m k4n, have eq1 := int.mod_add_div m 2, rw k4m at eq1, rw zero_add at eq1, rw ← eq1 at y_even, rw ← mul_assoc 2 2 (m / 2) at y_even, have two_mul_two : (2 : ℤ ) * 2 = 4 := by norm_num, rw two_mul_two at y_even, norm_num, rw mul_assoc at y_even, have four_div_y := dvd.intro (m / 2 * n) (eq.symm y_even), refine ⟨_, four_div_y⟩, rw ← imp_false, intro j, have four_div_one := int.dvd_gcd j four_div_y, rw h_coprime at four_div_one, norm_num at four_div_one, }, { left, cases x_even with x_even y_odd, cases k4 with k4m k4n, have eq1 := int.mod_add_div m 2, rw k4m at eq1, rw zero_add at eq1, rw ← eq1 at x_even, rw ← mul_assoc 2 2 (m / 2) at x_even, have two_mul_two : (2 : ℤ ) * 2 = 4 := by norm_num, rw two_mul_two at x_even, norm_num, rw mul_assoc at x_even, have four_div_x := dvd.intro (m / 2 * n) (eq.symm x_even), refine ⟨four_div_x, _⟩, rw ← imp_false, intro j, have four_div_one := int.dvd_gcd four_div_x j, rw h_coprime at four_div_one, norm_num at four_div_one, } }, { cases k1 with y_even x_even, { right, cases y_even with x_odd y_even, cases k5 with k5m k5n, have eq1 := int.mod_add_div n 2, rw k5n at eq1, rw zero_add at eq1, rw mul_assoc at y_even, rw mul_comm m n at y_even, rw ← mul_assoc at y_even, rw ← eq1 at y_even, rw ← mul_assoc 2 2 (n / 2) at y_even, have two_mul_two : (2 : ℤ ) * 2 = 4 := by norm_num, rw two_mul_two at y_even, norm_num, rw mul_assoc at y_even, have four_div_y := dvd.intro (n / 2 * m) (eq.symm y_even), refine ⟨_, four_div_y⟩, rw ← imp_false, intro j, have four_div_one := int.dvd_gcd j four_div_y, rw h_coprime at four_div_one, norm_num at four_div_one, }, { left, cases x_even with x_even y_odd, cases k5 with k5m k5n, have eq1 := int.mod_add_div n 2, rw k5n at eq1, rw zero_add at eq1, rw mul_assoc at x_even, rw mul_comm m n at x_even, rw ← mul_assoc at x_even, rw ← eq1 at x_even, rw ← mul_assoc 2 2 (n / 2) at x_even, have two_mul_two : (2 : ℤ ) * 2 = 4 := by norm_num, rw two_mul_two at x_even, norm_num, rw mul_assoc at x_even, have four_div_x := dvd.intro (n / 2 * m) (eq.symm x_even), refine ⟨four_div_x, _⟩, rw ← imp_false, intro j, have four_div_one := int.dvd_gcd four_div_x j, rw h_coprime at four_div_one, norm_num at four_div_one, } } end /- Lemma to obtain possible values modulo 3. (Modeled from data.nat.parity) -/ lemma mod_three_eq_zero_or_one_or_two (n : ℤ) : n % 3 = 0 ∨ n % 3 = 1 ∨ n % 3 = 2 := have h : n % 3 < 3 := abs_of_nonneg (show 0 ≤ (3 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 3 := int.mod_nonneg _ dec_trivial, match (n % 3), h, h₁ with | (0 : ℕ) := λ _ _ , or.inl rfl | (1 : ℕ) := λ _ _ , or.inr (or.inl rfl) | (2 : ℕ) := λ _ _ , or.inr (or.inr rfl) | (k + 3 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- If x,y,z is a primitive pythagorean triple, then exactly one of x,y is 0 mod 3. -/ theorem pythagorean_triple_exactly_one_div_three {x y z : ℤ} (h : pythagorean_triple x y z) (h_coprime : int.gcd x y = 1): ((x % 3 = 0) ∧ (y % 3 ≠ 0)) ∨ ((x % 3 ≠ 0) ∧ (y % 3 = 0)) := begin by_contradiction H, rw push_neg.not_or_eq at H, cases H with h1 h2, rw push_neg.not_and_eq at h1, rw push_neg.not_and_eq at h2, rw push_neg.not_not_eq at h1, by_cases j : (x % 3 = 0), { have j' := h1 j, simp at h1 j j', have three_div_one := int.dvd_gcd j j', rw h_coprime at three_div_one, norm_num at three_div_one, }, { have j' := h2 j, have xlem := mod_three_eq_zero_or_one_or_two x, have ylem := mod_three_eq_zero_or_one_or_two y, have xlem' := or.resolve_left xlem j, have ylem' := or.resolve_left ylem j', have pyth_mod : (x * x + y * y) % 3 = (x * x + y * y) % 3 := by refl, have xyz : x * x + y * y = z * z := h, have pyth_mod' : (x*x + y*y) % 3 = (z*z) % 3 := by { calc (x*x + y*y) % 3 = (x*x + y*y) % 3 : by refl ...= (z*z) % 3 : by rw xyz, }, cases xlem' with x1 x2, { cases ylem' with y1 y2, { have x_sq := int.mul_mod x x 3, rw x1 at x_sq, have y_sq := int.mul_mod y y 3, rw y1 at y_sq, norm_num at x_sq, norm_num at y_sq, rw int.add_mod (x*x) (y*y) 3 at pyth_mod', rw x_sq at pyth_mod', rw y_sq at pyth_mod', norm_num at pyth_mod', haveI : fact (nat.prime 3) := by sorry, have two_not_zero : (2 : zmod 3) ≠ 0 := dec_trivial, have lem := zmod.euler_criterion 3 two_not_zero, { have two_not_euler_right : ¬ ((2 : zmod 3)^(3/2) = 1):= by dec_trivial, rw ← not_iff_not at lem, rw ← lem at two_not_euler_right, sorry, }, }, sorry, }, sorry, }, end
6fdf320936728c62c589de6e25483718ab7970e4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/category/Mon/limits.lean
5c85e6d4444eb8b2792d57eb1dd2dca34ee0b86e
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,642
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 algebra.group.pi import algebra.category.Mon.basic import group_theory.submonoid import category_theory.limits.types import category_theory.limits.creates /-! # The category of (commutative) (additive) monoids has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ noncomputable theory open category_theory open category_theory.limits universe u namespace Mon variables {J : Type u} [small_category J] @[to_additive] instance monoid_obj (F : J ⥤ Mon) (j) : monoid ((F ⋙ forget Mon).obj j) := by { change monoid (F.obj j), apply_instance } /-- The flat sections of a functor into `Mon` form a submonoid of all sections. -/ @[to_additive "The flat sections of a functor into `AddMon` form an additive submonoid of all sections."] def sections_submonoid (F : J ⥤ Mon) : submonoid (Π j, F.obj j) := { carrier := (F ⋙ forget Mon).sections, one_mem' := λ j j' f, by simp, mul_mem' := λ a b ah bh j j' f, begin simp only [forget_map_eq_coe, functor.comp_map, monoid_hom.map_mul, pi.mul_apply], dsimp [functor.sections] at ah bh, rw [ah f, bh f], end } @[to_additive] instance limit_monoid (F : J ⥤ Mon) : monoid (types.limit_cone (F ⋙ forget Mon.{u})).X := (sections_submonoid F).to_monoid /-- `limit.π (F ⋙ forget Mon) j` as a `monoid_hom`. -/ @[to_additive "`limit.π (F ⋙ forget AddMon) j` as an `add_monoid_hom`."] def limit_π_monoid_hom (F : J ⥤ Mon.{u}) (j) : (types.limit_cone (F ⋙ forget Mon)).X →* (F ⋙ forget Mon).obj j := { to_fun := (types.limit_cone (F ⋙ forget Mon)).π.app j, map_one' := rfl, map_mul' := λ x y, rfl } namespace has_limits -- The next two definitions are used in the construction of `has_limits Mon`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `Mon`. (Internal use only; use the limits API.) -/ @[to_additive "(Internal use only; use the limits API.)"] def limit_cone (F : J ⥤ Mon) : cone F := { X := Mon.of (types.limit_cone (F ⋙ forget _)).X, π := { app := limit_π_monoid_hom F, naturality' := λ j j' f, monoid_hom.coe_inj ((types.limit_cone (F ⋙ forget _)).π.naturality f) } } /-- Witness that the limit cone in `Mon` is a limit cone. (Internal use only; use the limits API.) -/ @[to_additive "(Internal use only; use the limits API.)"] def limit_cone_is_limit (F : J ⥤ Mon) : is_limit (limit_cone F) := begin refine is_limit.of_faithful (forget Mon) (types.limit_cone_is_limit _) (λ s, ⟨_, _, _⟩) (λ s, rfl); tidy, end end has_limits open has_limits /-- The category of monoids has all limits. -/ @[to_additive] instance has_limits : has_limits Mon := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } /-- The forgetful functor from monoids to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ @[to_additive] instance forget_preserves_limits : preserves_limits (forget Mon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (types.limit_cone_is_limit (F ⋙ forget _)) } } end Mon namespace CommMon variables {J : Type u} [small_category J] @[to_additive] instance comm_monoid_obj (F : J ⥤ CommMon) (j) : comm_monoid ((F ⋙ forget CommMon).obj j) := by { change comm_monoid (F.obj j), apply_instance } @[to_additive] instance limit_comm_monoid (F : J ⥤ CommMon) : comm_monoid (types.limit_cone (F ⋙ forget CommMon.{u})).X := @submonoid.to_comm_monoid (Π j, F.obj j) _ (Mon.sections_submonoid (F ⋙ forget₂ CommMon Mon.{u})) /-- We show that the forgetful functor `CommMon ⥤ Mon` creates limits. All we need to do is notice that the limit point has a `comm_monoid` instance available, and then reuse the existing limit. -/ @[to_additive] instance (F : J ⥤ CommMon) : creates_limit F (forget₂ CommMon Mon.{u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommMon.of (types.limit_cone (F ⋙ forget CommMon)).X, π := { app := Mon.limit_π_monoid_hom (F ⋙ forget₂ CommMon Mon), naturality' := (Mon.has_limits.limit_cone (F ⋙ forget₂ _ _)).π.naturality, } }, valid_lift := by apply is_limit.unique_up_to_iso (Mon.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ CommMon Mon.{u}) (Mon.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommMon`. (Generally, you'll just want to use `limit F`.) -/ @[to_additive "A choice of limit cone for a functor into `CommMon`. (Generally, you'll just want to use `limit F`.)"] def limit_cone (F : J ⥤ CommMon) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommMon Mon.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ @[to_additive "The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.)"] def limit_cone_is_limit (F : J ⥤ CommMon) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of commutative monoids has all limits. -/ @[to_additive] instance has_limits : has_limits CommMon := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommMon Mon) } } /-- The forgetful functor from commutative monoids to monoids preserves all limits. (That is, the underlying monoid could have been computed instead as limits in the category of monoids.) -/ @[to_additive AddCommMon.forget₂_AddMon_preserves_limits] instance forget₂_Mon_preserves_limits : preserves_limits (forget₂ CommMon Mon) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- The forgetful functor from commutative monoids to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ @[to_additive] instance forget_preserves_limits : preserves_limits (forget CommMon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommMon Mon) (forget Mon) } } end CommMon
affc1b4b15cd6dbe794fc9926c7cd32ddc85deef
4d3f29a7b2eff44af8fd0d3176232e039acb9ee3
/LAMR/Util/Propositional.lean
af8f497217f475c579a3814e866c8b0b8d854197
[]
no_license
marijnheule/lamr
5fc5d69d326ff92e321242cfd7f72e78d7f99d7e
28cc4114c7361059bb54f407fa312bf38b48728b
refs/heads/main
1,689,338,013,620
1,630,359,632,000
1,630,359,632,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
125
lean
import LAMR.Util.Propositional.Syntax import LAMR.Util.Propositional.Transformations import LAMR.Util.Propositional.SatSolver
7b2a854a36db8c2c6fdb8dc5f4b21b5ab5a0f26d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/597b.hlean
41c23257cbb3a2d544ee2100f1d7fc04bfd96b48
[ "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
99
hlean
-- open equiv constants (A B : Type₀) (f : A ≃ B) definition foo : A → B := f -- should fail
7753face157519a2e7789b2c2aaa7b93da776eac
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/vector_bundle/constructions.lean
0d5efe12a58326da12559196213099177350fc13
[ "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,479
lean
/- Copyright © 2022 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Sébastien Gouëzel, Heather Macbeth, Floris van Doorn -/ import topology.fiber_bundle.constructions import topology.vector_bundle.basic /-! # Standard constructions on vector bundles This file contains several standard constructions on vector bundles: * `bundle.trivial.vector_bundle 𝕜 B F`: the trivial vector bundle with scalar field `𝕜` and model fibre `F` over the base `B` * `vector_bundle.prod`: for vector bundles `E₁` and `E₂` with scalar field `𝕜` over a common base, a vector bundle structure on their direct sum `E₁ ×ᵇ E₂` (the notation stands for `λ x, E₁ x × E₂ x`). * `vector_bundle.pullback`: for a vector bundle `E` over `B`, a vector bundle structure on its pullback `f *ᵖ E` by a map `f : B' → B` (the notation is a type synonym for `E ∘ f`). ## Tags Vector bundle, direct sum, pullback -/ noncomputable theory open bundle set fiber_bundle open_locale classical bundle /-! ### The trivial vector bundle -/ namespace bundle.trivial variables (𝕜 : Type*) (B : Type*) (F : Type*) [nontrivially_normed_field 𝕜] [normed_add_comm_group F] [normed_space 𝕜 F] [topological_space B] instance trivialization.is_linear : (trivialization B F).is_linear 𝕜 := { linear := λ x hx, ⟨λ y z, rfl, λ c y, rfl⟩ } variables {𝕜} lemma trivialization.coord_changeL (b : B) : (trivialization B F).coord_changeL 𝕜 (trivialization B F) b = continuous_linear_equiv.refl 𝕜 F := begin ext v, rw [trivialization.coord_changeL_apply'], exacts [rfl, ⟨mem_univ _, mem_univ _⟩] end variables (𝕜) instance vector_bundle : vector_bundle 𝕜 F (bundle.trivial B F) := { trivialization_linear' := begin introsI e he, rw eq_trivialization B F e, apply_instance end, continuous_on_coord_change' := begin introsI e e' he he', unfreezingI { obtain rfl := eq_trivialization B F e }, unfreezingI { obtain rfl := eq_trivialization B F e' }, simp_rw trivialization.coord_changeL, exact continuous_const.continuous_on end } end bundle.trivial /-! ### Direct sum of two vector bundles -/ section variables (𝕜 : Type*) {B : Type*} [nontrivially_normed_field 𝕜] [topological_space B] (F₁ : Type*) [normed_add_comm_group F₁] [normed_space 𝕜 F₁] (E₁ : B → Type*) [topological_space (total_space E₁)] (F₂ : Type*) [normed_add_comm_group F₂] [normed_space 𝕜 F₂] (E₂ : B → Type*) [topological_space (total_space E₂)] namespace trivialization variables {F₁ E₁ F₂ E₂} [Π x, add_comm_monoid (E₁ x)] [Π x, module 𝕜 (E₁ x)] [Π x, add_comm_monoid (E₂ x)] [Π x, module 𝕜 (E₂ x)] (e₁ : trivialization F₁ (π E₁)) (e₂ : trivialization F₂ (π E₂)) instance prod.is_linear [e₁.is_linear 𝕜] [e₂.is_linear 𝕜] : (e₁.prod e₂).is_linear 𝕜 := { linear := λ x ⟨h₁, h₂⟩, (((e₁.linear 𝕜 h₁).mk' _).prod_map ((e₂.linear 𝕜 h₂).mk' _)).is_linear } variables {e₁ e₂} [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)] [fiber_bundle F₁ E₁] [fiber_bundle F₂ E₂] lemma prod_apply [e₁.is_linear 𝕜] [e₂.is_linear 𝕜] {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) (v₁ : E₁ x) (v₂ : E₂ x) : prod e₁ e₂ ⟨x, (v₁, v₂)⟩ = ⟨x, e₁.continuous_linear_equiv_at 𝕜 x hx₁ v₁, e₂.continuous_linear_equiv_at 𝕜 x hx₂ v₂⟩ := rfl end trivialization open trivialization variables [Π x, add_comm_monoid (E₁ x)] [Π x, module 𝕜 (E₁ x)] [Π x, add_comm_monoid (E₂ x)] [Π x, module 𝕜 (E₂ x)] [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)] [fiber_bundle F₁ E₁] [fiber_bundle F₂ E₂] /-- The product of two vector bundles is a vector bundle. -/ instance vector_bundle.prod [vector_bundle 𝕜 F₁ E₁] [vector_bundle 𝕜 F₂ E₂] : vector_bundle 𝕜 (F₁ × F₂) (E₁ ×ᵇ E₂) := { trivialization_linear' := begin rintros _ ⟨e₁, e₂, he₁, he₂, rfl⟩, resetI, apply_instance end, continuous_on_coord_change' := begin rintros _ _ ⟨e₁, e₂, he₁, he₂, rfl⟩ ⟨e₁', e₂', he₁', he₂', rfl⟩, resetI, refine (((continuous_on_coord_change 𝕜 e₁ e₁').mono _).prod_mapL 𝕜 ((continuous_on_coord_change 𝕜 e₂ e₂').mono _)).congr _; dsimp only [base_set_prod] with mfld_simps, { mfld_set_tac }, { mfld_set_tac }, { rintro b hb, rw [continuous_linear_map.ext_iff], rintro ⟨v₁, v₂⟩, show (e₁.prod e₂).coord_changeL 𝕜 (e₁'.prod e₂') b (v₁, v₂) = (e₁.coord_changeL 𝕜 e₁' b v₁, e₂.coord_changeL 𝕜 e₂' b v₂), rw [e₁.coord_changeL_apply e₁', e₂.coord_changeL_apply e₂', (e₁.prod e₂).coord_changeL_apply'], exacts [rfl, hb, ⟨hb.1.2, hb.2.2⟩, ⟨hb.1.1, hb.2.1⟩] } end } variables {𝕜 F₁ E₁ F₂ E₂} @[simp] lemma trivialization.continuous_linear_equiv_at_prod {e₁ : trivialization F₁ (π E₁)} {e₂ : trivialization F₂ (π E₂)} [e₁.is_linear 𝕜] [e₂.is_linear 𝕜] {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) : (e₁.prod e₂).continuous_linear_equiv_at 𝕜 x ⟨hx₁, hx₂⟩ = (e₁.continuous_linear_equiv_at 𝕜 x hx₁).prod (e₂.continuous_linear_equiv_at 𝕜 x hx₂) := begin ext1, funext v, obtain ⟨v₁, v₂⟩ := v, rw [(e₁.prod e₂).continuous_linear_equiv_at_apply 𝕜, trivialization.prod], exact (congr_arg prod.snd (prod_apply 𝕜 hx₁ hx₂ v₁ v₂) : _) end end /-! ### Pullbacks of vector bundles -/ section variables (R 𝕜 : Type*) {B : Type*} (F : Type*) (E : B → Type*) {B' : Type*} (f : B' → B) instance [∀ (x : B), add_comm_monoid (E x)] : ∀ (x : B'), add_comm_monoid ((f *ᵖ E) x) := by delta_instance bundle.pullback instance [semiring R] [∀ (x : B), add_comm_monoid (E x)] [∀ x, module R (E x)] : ∀ (x : B'), module R ((f *ᵖ E) x) := by delta_instance bundle.pullback variables {E F} [topological_space B'] [topological_space (total_space E)] [nontrivially_normed_field 𝕜] [normed_add_comm_group F] [normed_space 𝕜 F] [topological_space B] [∀ x, add_comm_monoid (E x)] [∀ x, module 𝕜 (E x)] {K : Type*} [continuous_map_class K B' B] instance trivialization.pullback_linear (e : trivialization F (π E)) [e.is_linear 𝕜] (f : K) : (@trivialization.pullback _ _ _ B' _ _ _ _ _ _ _ e f).is_linear 𝕜 := { linear := λ x h, e.linear 𝕜 h } instance vector_bundle.pullback [∀ x, topological_space (E x)] [fiber_bundle F E] [vector_bundle 𝕜 F E] (f : K) : vector_bundle 𝕜 F ((f : B' → B) *ᵖ E) := { trivialization_linear' := begin rintro _ ⟨e, he, rfl⟩, resetI, apply_instance, end, continuous_on_coord_change' := begin rintro _ _ ⟨e, he, rfl⟩ ⟨e', he', rfl⟩, resetI, refine ((continuous_on_coord_change 𝕜 e e').comp (map_continuous f).continuous_on (λ b hb, hb)).congr _, rintro b (hb : f b ∈ e.base_set ∩ e'.base_set), ext v, show ((e.pullback f).coord_changeL 𝕜 (e'.pullback f) b) v = (e.coord_changeL 𝕜 e' (f b)) v, rw [e.coord_changeL_apply e' hb, (e.pullback f).coord_changeL_apply' _], exacts [rfl, hb] end } end
60d7c6c47529414b0d5a21ae106a84673d53d474
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/set_integral_auto.lean
dbdcf4345c1220e9665a3cc4c23d124ff74ee972
[]
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
55,555
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.measure_theory.bochner_integration import Mathlib.analysis.normed_space.indicator_function import Mathlib.PostPort universes u_1 u_2 u_3 u_5 u_4 namespace Mathlib /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We also define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that `∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation `∫ a in s, f a` is `measure_theory.integral (s.indicator f)` ## TODO The file ends with over a hundred lines of commented out code. This is the old contents of this file using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be migrated to the new definition. -/ theorem piecewise_ae_eq_restrict {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure_theory.measure α} {s : set α} {f : α → β} {g : α → β} (hs : is_measurable s) : filter.eventually_eq (measure_theory.measure.ae (measure_theory.measure.restrict μ s)) (set.piecewise s f g) f := sorry theorem piecewise_ae_eq_restrict_compl {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure_theory.measure α} {s : set α} {f : α → β} {g : α → β} (hs : is_measurable s) : filter.eventually_eq (measure_theory.measure.ae (measure_theory.measure.restrict μ (sᶜ))) (set.piecewise s f g) g := sorry theorem indicator_ae_eq_restrict {α : Type u_1} {β : Type u_2} [measurable_space α] [HasZero β] {μ : measure_theory.measure α} {s : set α} {f : α → β} (hs : is_measurable s) : filter.eventually_eq (measure_theory.measure.ae (measure_theory.measure.restrict μ s)) (set.indicator s f) f := piecewise_ae_eq_restrict hs theorem indicator_ae_eq_restrict_compl {α : Type u_1} {β : Type u_2} [measurable_space α] [HasZero β] {μ : measure_theory.measure α} {s : set α} {f : α → β} (hs : is_measurable s) : filter.eventually_eq (measure_theory.measure.ae (measure_theory.measure.restrict μ (sᶜ))) (set.indicator s f) 0 := piecewise_ae_eq_restrict_compl hs /-- A function `f` is measurable at filter `l` w.r.t. a measure `μ` if it is ae-measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def measurable_at_filter {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : α → β) (l : filter α) (μ : autoParam (measure_theory.measure α) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.measure_theory.volume_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "measure_theory") "volume_tac") [])) := ∃ (s : set α), ∃ (H : s ∈ l), ae_measurable f @[simp] theorem measurable_at_bot {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {μ : measure_theory.measure α} {f : α → β} : measurable_at_filter f ⊥ := sorry protected theorem measurable_at_filter.eventually {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {l : filter α} {f : α → β} {μ : measure_theory.measure α} (h : measurable_at_filter f l) : filter.eventually (fun (s : set α) => ae_measurable f) (filter.lift' l set.powerset) := iff.mpr (filter.eventually_lift'_powerset' fun (s t : set α) => ae_measurable.mono_set) h protected theorem measurable_at_filter.filter_mono {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {l : filter α} {l' : filter α} {f : α → β} {μ : measure_theory.measure α} (h : measurable_at_filter f l) (h' : l' ≤ l) : measurable_at_filter f l' := sorry protected theorem ae_measurable.measurable_at_filter {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {l : filter α} {f : α → β} {μ : measure_theory.measure α} (h : ae_measurable f) : measurable_at_filter f l := Exists.intro set.univ (Exists.intro filter.univ_mem_sets (eq.mpr (id (Eq._oldrec (Eq.refl (ae_measurable f)) measure_theory.measure.restrict_univ)) h)) theorem ae_measurable.measurable_at_filter_of_mem {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {l : filter α} {f : α → β} {μ : measure_theory.measure α} {s : set α} (h : ae_measurable f) (hl : s ∈ l) : measurable_at_filter f l := Exists.intro s (Exists.intro hl h) protected theorem measurable.measurable_at_filter {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {l : filter α} {f : α → β} {μ : measure_theory.measure α} (h : measurable f) : measurable_at_filter f l := ae_measurable.measurable_at_filter (measurable.ae_measurable h) namespace measure_theory theorem has_finite_integral_restrict_of_bounded {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] {f : α → E} {s : set α} {μ : measure α} {C : ℝ} (hs : coe_fn μ s < ⊤) (hf : filter.eventually (fun (x : α) => norm (f x) ≤ C) (measure.ae (measure.restrict μ s))) : has_finite_integral f := has_finite_integral_of_bounded hf /-- A function is `integrable_on` a set `s` if it is a measurable function and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] (f : α → E) (s : set α) (μ : autoParam (measure α) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.measure_theory.volume_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "measure_theory") "volume_tac") [])) := integrable f theorem integrable_on.integrable {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} (h : integrable_on f s) : integrable f := h @[simp] theorem integrable_on_empty {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} : integrable_on f ∅ := sorry @[simp] theorem integrable_on_univ {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} : integrable_on f set.univ ↔ integrable f := eq.mpr (id (Eq._oldrec (Eq.refl (integrable_on f set.univ ↔ integrable f)) (integrable_on.equations._eqn_1 f set.univ))) (eq.mpr (id (Eq._oldrec (Eq.refl (integrable f ↔ integrable f)) measure.restrict_univ)) (iff.refl (integrable f))) theorem integrable_on_zero {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {s : set α} {μ : measure α} : integrable_on (fun (_x : α) => 0) s := integrable_zero α E (measure.restrict μ s) theorem integrable_on_const {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {s : set α} {μ : measure α} {C : E} : integrable_on (fun (_x : α) => C) s ↔ C = 0 ∨ coe_fn μ s < ⊤ := sorry theorem integrable_on.mono {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} {ν : measure α} (h : integrable_on f t) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s := integrable.mono_measure h (measure.restrict_mono hs hμ) theorem integrable_on.mono_set {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} (h : integrable_on f t) (hst : s ⊆ t) : integrable_on f s := integrable_on.mono h hst (le_refl μ) theorem integrable_on.mono_measure {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} {ν : measure α} (h : integrable_on f s) (hμ : μ ≤ ν) : integrable_on f s := integrable_on.mono h (set.subset.refl s) hμ theorem integrable_on.mono_set_ae {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} (h : integrable_on f t) (hst : filter.eventually_le (measure.ae μ) s t) : integrable_on f s := integrable.mono_measure (integrable_on.integrable h) (restrict_mono_ae hst) theorem integrable.integrable_on {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} (h : integrable f) : integrable_on f s := integrable.mono_measure h measure.restrict_le_self theorem integrable.integrable_on' {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} (h : integrable f) : integrable_on f s := h theorem integrable_on.left_of_union {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} (h : integrable_on f (s ∪ t)) : integrable_on f s := integrable_on.mono_set h (set.subset_union_left s t) theorem integrable_on.right_of_union {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} (h : integrable_on f (s ∪ t)) : integrable_on f t := integrable_on.mono_set h (set.subset_union_right s t) theorem integrable_on.union {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} (hs : integrable_on f s) (ht : integrable_on f t) : integrable_on f (s ∪ t) := integrable.mono_measure (integrable.add_measure hs ht) (measure.restrict_union_le s t) @[simp] theorem integrable_on_union {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} : integrable_on f (s ∪ t) ↔ integrable_on f s ∧ integrable_on f t := sorry @[simp] theorem integrable_on_finite_union {α : Type u_1} {β : Type u_2} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {s : set β} (hs : set.finite s) {t : β → set α} : integrable_on f (set.Union fun (i : β) => set.Union fun (H : i ∈ s) => t i) ↔ ∀ (i : β), i ∈ s → integrable_on f (t i) := sorry @[simp] theorem integrable_on_finset_union {α : Type u_1} {β : Type u_2} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {s : finset β} {t : β → set α} : integrable_on f (set.Union fun (i : β) => set.Union fun (H : i ∈ s) => t i) ↔ ∀ (i : β), i ∈ s → integrable_on f (t i) := integrable_on_finite_union (finset.finite_to_set s) theorem integrable_on.add_measure {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} {ν : measure α} (hμ : integrable_on f s) (hν : integrable_on f s) : integrable_on f s := id (eq.mpr (id (Eq._oldrec (Eq.refl (integrable f)) (measure.restrict_add μ ν s))) (integrable.add_measure (integrable_on.integrable hμ) hν)) @[simp] theorem integrable_on_add_measure {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} {ν : measure α} : integrable_on f s ↔ integrable_on f s ∧ integrable_on f s := sorry theorem ae_measurable_indicator_iff {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} (hs : is_measurable s) : ae_measurable f ↔ ae_measurable (set.indicator s f) := sorry theorem integrable_indicator_iff {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} (hs : is_measurable s) : integrable (set.indicator s f) ↔ integrable_on f s := sorry theorem integrable_on.indicator {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} (h : integrable_on f s) (hs : is_measurable s) : integrable (set.indicator s f) := iff.mpr (integrable_indicator_iff hs) h /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] (f : α → E) (l : filter α) (μ : autoParam (measure α) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.measure_theory.volume_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "measure_theory") "volume_tac") [])) := ∃ (s : set α), ∃ (H : s ∈ l), integrable_on f s protected theorem integrable_at_filter.eventually {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} (h : integrable_at_filter f l) : filter.eventually (fun (s : set α) => integrable_on f s) (filter.lift' l set.powerset) := sorry theorem integrable_at_filter.filter_mono {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} {l' : filter α} (hl : l ≤ l') (hl' : integrable_at_filter f l') : integrable_at_filter f l := sorry theorem integrable_at_filter.inf_of_left {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} {l' : filter α} (hl : integrable_at_filter f l) : integrable_at_filter f (l ⊓ l') := integrable_at_filter.filter_mono inf_le_left hl theorem integrable_at_filter.inf_of_right {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} {l' : filter α} (hl : integrable_at_filter f l) : integrable_at_filter f (l' ⊓ l) := integrable_at_filter.filter_mono inf_le_right hl @[simp] theorem integrable_at_filter.inf_ae_iff {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} : integrable_at_filter f (l ⊓ measure.ae μ) ↔ integrable_at_filter f l := sorry theorem integrable_at_filter.of_inf_ae {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} : integrable_at_filter f (l ⊓ measure.ae μ) → integrable_at_filter f l := iff.mp integrable_at_filter.inf_ae_iff /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ theorem measure.finite_at_filter.integrable_at_filter {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} [filter.is_measurably_generated l] (hfm : measurable_at_filter f l) (hμ : measure.finite_at_filter μ l) (hf : filter.is_bounded_under LessEq l (norm ∘ f)) : integrable_at_filter f l := sorry theorem measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} [filter.is_measurably_generated l] (hfm : measurable_at_filter f l) (hμ : measure.finite_at_filter μ l) {b : E} (hf : filter.tendsto f (l ⊓ measure.ae μ) (nhds b)) : integrable_at_filter f l := integrable_at_filter.of_inf_ae (measure.finite_at_filter.integrable_at_filter (measurable_at_filter.filter_mono hfm inf_le_left) (measure.finite_at_filter.inf_of_left hμ) (filter.tendsto.is_bounded_under_le (filter.tendsto.norm hf))) theorem Mathlib.filter.tendsto.integrable_at_filter_ae {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} [filter.is_measurably_generated l] (hfm : measurable_at_filter f l) (hμ : measure.finite_at_filter μ l) {b : E} (hf : filter.tendsto f (l ⊓ measure.ae μ) (nhds b)) : integrable_at_filter f l := measure.finite_at_filter.integrable_at_filter_of_tendsto_ae theorem measure.finite_at_filter.integrable_at_filter_of_tendsto {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} [filter.is_measurably_generated l] (hfm : measurable_at_filter f l) (hμ : measure.finite_at_filter μ l) {b : E} (hf : filter.tendsto f l (nhds b)) : integrable_at_filter f l := measure.finite_at_filter.integrable_at_filter hfm hμ (filter.tendsto.is_bounded_under_le (filter.tendsto.norm hf)) theorem Mathlib.filter.tendsto.integrable_at_filter {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} {l : filter α} [filter.is_measurably_generated l] (hfm : measurable_at_filter f l) (hμ : measure.finite_at_filter μ l) {b : E} (hf : filter.tendsto f l (nhds b)) : integrable_at_filter f l := measure.finite_at_filter.integrable_at_filter_of_tendsto theorem integrable_add {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [opens_measurable_space E] {f : α → E} {g : α → E} (h : set.univ ⊆ f ⁻¹' singleton 0 ∪ g ⁻¹' singleton 0) (hf : measurable f) (hg : measurable g) : integrable (f + g) ↔ integrable f ∧ integrable g := sorry /-- To prove something for an arbitrary integrable function in a second countable Borel normed group, it suffices to show that * the property holds for (multiples of) characteristic functions; * is closed under addition; * the set of functions in the `L¹` space for which the property holds is closed. * the property is closed under the almost-everywhere equal relation. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`). -/ theorem integrable.induction {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] (P : (α → E) → Prop) (h_ind : ∀ (c : E) {s : set α}, is_measurable s → coe_fn μ s < ⊤ → P (set.indicator s fun (_x : α) => c)) (h_sum : ∀ {f g : α → E}, set.univ ⊆ f ⁻¹' singleton 0 ∪ g ⁻¹' singleton 0 → integrable f → integrable g → P f → P g → P (f + g)) (h_closed : is_closed (set_of fun (f : l1 α E μ) => P ⇑f)) (h_ae : ∀ {f g : α → E}, filter.eventually_eq (measure.ae μ) f g → integrable f → P f → P g) {f : α → E} (hf : integrable f) : P f := sorry theorem set_integral_congr_ae {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {g : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] (hs : is_measurable s) (h : filter.eventually (fun (x : α) => x ∈ s → f x = g x) (measure.ae μ)) : (integral (measure.restrict μ s) fun (x : α) => f x) = integral (measure.restrict μ s) fun (x : α) => g x := integral_congr_ae (iff.mpr (ae_restrict_iff' hs) h) theorem set_integral_congr {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {g : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] (hs : is_measurable s) (h : set.eq_on f g s) : (integral (measure.restrict μ s) fun (x : α) => f x) = integral (measure.restrict μ s) fun (x : α) => g x := set_integral_congr_ae hs (filter.eventually_of_forall h) theorem integral_union {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {t : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] (hst : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) (hfs : integrable_on f s) (hft : integrable_on f t) : (integral (measure.restrict μ (s ∪ t)) fun (x : α) => f x) = (integral (measure.restrict μ s) fun (x : α) => f x) + integral (measure.restrict μ t) fun (x : α) => f x := sorry theorem integral_empty {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] : (integral (measure.restrict μ ∅) fun (x : α) => f x) = 0 := eq.mpr (id (Eq._oldrec (Eq.refl ((integral (measure.restrict μ ∅) fun (x : α) => f x) = 0)) measure.restrict_empty)) (eq.mpr (id (Eq._oldrec (Eq.refl ((integral 0 fun (x : α) => f x) = 0)) (integral_zero_measure fun (x : α) => f x))) (Eq.refl 0)) theorem integral_univ {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] : (integral (measure.restrict μ set.univ) fun (x : α) => f x) = integral μ fun (x : α) => f x := sorry theorem integral_add_compl {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] (hs : is_measurable s) (hfi : integrable f) : ((integral (measure.restrict μ s) fun (x : α) => f x) + integral (measure.restrict μ (sᶜ)) fun (x : α) => f x) = integral μ fun (x : α) => f x := sorry /-- For a function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ theorem integral_indicator {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] (hs : is_measurable s) : (integral μ fun (x : α) => set.indicator s f x) = integral (measure.restrict μ s) fun (x : α) => f x := sorry theorem set_integral_const {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] (c : E) : (integral (measure.restrict μ s) fun (x : α) => c) = ennreal.to_real (coe_fn μ s) • c := sorry @[simp] theorem integral_indicator_const {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] (e : E) {s : set α} (s_meas : is_measurable s) : (integral μ fun (a : α) => set.indicator s (fun (x : α) => e) a) = ennreal.to_real (coe_fn μ s) • e := sorry theorem set_integral_map {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] {β : Type u_2} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : is_measurable s) (hf : ae_measurable f) (hg : measurable g) : (integral (measure.restrict (coe_fn (measure.map g) μ) s) fun (y : β) => f y) = integral (measure.restrict μ (g ⁻¹' s)) fun (x : α) => f (g x) := sorry theorem norm_set_integral_le_of_norm_le_const_ae {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] {C : ℝ} (hs : coe_fn μ s < ⊤) (hC : filter.eventually (fun (x : α) => norm (f x) ≤ C) (measure.ae (measure.restrict μ s))) : norm (integral (measure.restrict μ s) fun (x : α) => f x) ≤ C * ennreal.to_real (coe_fn μ s) := sorry theorem norm_set_integral_le_of_norm_le_const_ae' {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] {C : ℝ} (hs : coe_fn μ s < ⊤) (hC : filter.eventually (fun (x : α) => x ∈ s → norm (f x) ≤ C) (measure.ae μ)) (hfm : ae_measurable f) : norm (integral (measure.restrict μ s) fun (x : α) => f x) ≤ C * ennreal.to_real (coe_fn μ s) := sorry theorem norm_set_integral_le_of_norm_le_const_ae'' {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] {C : ℝ} (hs : coe_fn μ s < ⊤) (hsm : is_measurable s) (hC : filter.eventually (fun (x : α) => x ∈ s → norm (f x) ≤ C) (measure.ae μ)) : norm (integral (measure.restrict μ s) fun (x : α) => f x) ≤ C * ennreal.to_real (coe_fn μ s) := sorry theorem norm_set_integral_le_of_norm_le_const {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] {C : ℝ} (hs : coe_fn μ s < ⊤) (hC : ∀ (x : α), x ∈ s → norm (f x) ≤ C) (hfm : ae_measurable f) : norm (integral (measure.restrict μ s) fun (x : α) => f x) ≤ C * ennreal.to_real (coe_fn μ s) := norm_set_integral_le_of_norm_le_const_ae' hs (filter.eventually_of_forall hC) hfm theorem norm_set_integral_le_of_norm_le_const' {α : Type u_1} {E : Type u_3} [measurable_space α] [normed_group E] [measurable_space E] {f : α → E} {s : set α} {μ : measure α} [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] {C : ℝ} (hs : coe_fn μ s < ⊤) (hsm : is_measurable s) (hC : ∀ (x : α), x ∈ s → norm (f x) ≤ C) : norm (integral (measure.restrict μ s) fun (x : α) => f x) ≤ C * ennreal.to_real (coe_fn μ s) := norm_set_integral_le_of_norm_le_const_ae'' hs hsm (filter.eventually_of_forall hC) theorem set_integral_eq_zero_iff_of_nonneg_ae {α : Type u_1} [measurable_space α] {s : set α} {μ : measure α} {f : α → ℝ} (hf : filter.eventually_le (measure.ae (measure.restrict μ s)) 0 f) (hfi : integrable_on f s) : (integral (measure.restrict μ s) fun (x : α) => f x) = 0 ↔ filter.eventually_eq (measure.ae (measure.restrict μ s)) f 0 := integral_eq_zero_iff_of_nonneg_ae hf hfi theorem set_integral_pos_iff_support_of_nonneg_ae {α : Type u_1} [measurable_space α] {s : set α} {μ : measure α} {f : α → ℝ} (hf : filter.eventually_le (measure.ae (measure.restrict μ s)) 0 f) (hfi : integrable_on f s) : (0 < integral (measure.restrict μ s) fun (x : α) => f x) ↔ 0 < coe_fn μ (function.support f ∩ s) := sorry end measure_theory /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.lift' powerset` along `li`. Since `μ (s i)` is an `ennreal` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ theorem filter.tendsto.integral_sub_linear_is_o_ae {α : Type u_1} {E : Type u_3} [measurable_space α] {ι : Type u_5} [measurable_space E] [normed_group E] [normed_space ℝ E] [topological_space.second_countable_topology E] [complete_space E] [borel_space E] {μ : measure_theory.measure α} {l : filter α} [filter.is_measurably_generated l] {f : α → E} {b : E} (h : filter.tendsto f (l ⊓ measure_theory.measure.ae μ) (nhds b)) (hfm : measurable_at_filter f l) (hμ : measure_theory.measure.finite_at_filter μ l) {s : ι → set α} {li : filter ι} (hs : filter.tendsto s li (filter.lift' l set.powerset)) (m : optParam (ι → ℝ) fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) (hsμ : autoParam (filter.eventually_eq li (fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) m) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.refl") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "refl") [])) : asymptotics.is_o (fun (i : ι) => (measure_theory.integral (measure_theory.measure.restrict μ (s i)) fun (x : α) => f x) - m i • b) m li := sorry /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a` within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ennreal` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ theorem continuous_within_at.integral_sub_linear_is_o_ae {α : Type u_1} {E : Type u_3} [measurable_space α] {ι : Type u_5} [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [topological_space.second_countable_topology E] [complete_space E] [borel_space E] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (ha : continuous_within_at f t a) (ht : is_measurable t) (hfm : measurable_at_filter f (nhds_within a t)) {s : ι → set α} {li : filter ι} (hs : filter.tendsto s li (filter.lift' (nhds_within a t) set.powerset)) (m : optParam (ι → ℝ) fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) (hsμ : autoParam (filter.eventually_eq li (fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) m) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.refl") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "refl") [])) : asymptotics.is_o (fun (i : ι) => (measure_theory.integral (measure_theory.measure.restrict μ (s i)) fun (x : α) => f x) - m i • f a) m li := filter.tendsto.integral_sub_linear_is_o_ae (filter.tendsto.mono_left ha inf_le_left) hfm (measure_theory.measure.finite_at_nhds_within μ a t) hs m /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).lift' powerset` along `li. Since `μ (s i)` is an `ennreal` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ theorem continuous_at.integral_sub_linear_is_o_ae {α : Type u_1} {E : Type u_3} [measurable_space α] {ι : Type u_5} [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [topological_space.second_countable_topology E] [complete_space E] [borel_space E] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : measurable_at_filter f (nhds a)) {s : ι → set α} {li : filter ι} (hs : filter.tendsto s li (filter.lift' (nhds a) set.powerset)) (m : optParam (ι → ℝ) fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) (hsμ : autoParam (filter.eventually_eq li (fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) m) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.refl") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "refl") [])) : asymptotics.is_o (fun (i : ι) => (measure_theory.integral (measure_theory.measure.restrict μ (s i)) fun (x : α) => f x) - m i • f a) m li := filter.tendsto.integral_sub_linear_is_o_ae (filter.tendsto.mono_left ha inf_le_left) hfm (measure_theory.measure.finite_at_nhds μ a) hs m /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ theorem is_compact.integrable_on_of_nhds_within {α : Type u_1} {E : Type u_3} [measurable_space α] [measurable_space E] [normed_group E] [topological_space α] {μ : measure_theory.measure α} {s : set α} (hs : is_compact s) {f : α → E} (hf : ∀ (x : α), x ∈ s → measure_theory.integrable_at_filter f (nhds_within x s)) : measure_theory.integrable_on f s := sorry /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ theorem continuous_on.ae_measurable {α : Type u_1} {E : Type u_3} [measurable_space α] [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [borel_space E] {f : α → E} {s : set α} {μ : measure_theory.measure α} (hf : continuous_on f s) (hs : is_measurable s) : ae_measurable f := sorry theorem continuous_on.integrable_at_nhds_within {α : Type u_1} {E : Type u_3} [measurable_space α] [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [borel_space E] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : is_measurable t) (ha : a ∈ t) : measure_theory.integrable_at_filter f (nhds_within a t) := filter.tendsto.integrable_at_filter (Exists.intro t (Exists.intro self_mem_nhds_within (continuous_on.ae_measurable hft ht))) (measure_theory.measure.finite_at_nhds_within μ a t) (hft a ha) /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ennreal` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ theorem continuous_on.integral_sub_linear_is_o_ae {α : Type u_1} {E : Type u_3} [measurable_space α] {ι : Type u_5} [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [topological_space.second_countable_topology E] [complete_space E] [borel_space E] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : is_measurable t) {s : ι → set α} {li : filter ι} (hs : filter.tendsto s li (filter.lift' (nhds_within a t) set.powerset)) (m : optParam (ι → ℝ) fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) (hsμ : autoParam (filter.eventually_eq li (fun (i : ι) => ennreal.to_real (coe_fn μ (s i))) m) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.refl") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "refl") [])) : asymptotics.is_o (fun (i : ι) => (measure_theory.integral (measure_theory.measure.restrict μ (s i)) fun (x : α) => f x) - m i • f a) m li := continuous_within_at.integral_sub_linear_is_o_ae (hft a ha) ht (Exists.intro t (Exists.intro self_mem_nhds_within (continuous_on.ae_measurable hft ht))) hs m /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ theorem continuous_on.integrable_on_compact {α : Type u_1} {E : Type u_3} [measurable_space α] [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [borel_space E] [t2_space α] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : measure_theory.integrable_on f s := is_compact.integrable_on_of_nhds_within hs fun (x : α) (hx : x ∈ s) => continuous_on.integrable_at_nhds_within hf (is_compact.is_measurable hs) hx /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ theorem continuous.integrable_on_compact {α : Type u_1} {E : Type u_3} [measurable_space α] [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : measure_theory.integrable_on f s := continuous_on.integrable_on_compact hs (continuous.continuous_on hf) /-- A continuous function with compact closure of the support is integrable on the whole space. -/ theorem continuous.integrable_of_compact_closure_support {α : Type u_1} {E : Type u_3} [measurable_space α] [measurable_space E] [normed_group E] [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ] {f : α → E} (hf : continuous f) (hfc : is_compact (closure (function.support f))) : measure_theory.integrable f := sorry /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. The first step is to prove that, given a function `φ : α → E` which is measurable and integrable, and a continuous linear map `L : E →L[ℝ] F`, the function `λ a, L(φ a)` is also measurable and integrable. Note we cannot write this as `L ∘ φ` since the type of `L` is not an actual function type. The next step is translate this to `l1`, replacing the function `φ` by a term with type `α →₁[μ] E` (an equivalence class of integrable functions). The corresponding "composition" is `L.comp_l1 φ : α →₁[μ] F`. This is then upgraded to a linear map `L.comp_l1ₗ : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F)` and a continuous linear map `L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F)`. Then we can prove the commutation result using continuity of all relevant operations and the result on simple functions. -/ namespace continuous_linear_map theorem norm_comp_l1_apply_le {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [opens_measurable_space E] [topological_space.second_countable_topology E] (φ : measure_theory.l1 α E μ) (L : continuous_linear_map ℝ E F) : filter.eventually (fun (a : α) => norm (coe_fn L (coe_fn φ a)) ≤ norm L * norm (coe_fn φ a)) (measure_theory.measure.ae μ) := filter.eventually_of_forall fun (a : α) => le_op_norm L (coe_fn φ a) theorem integrable_comp {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [opens_measurable_space E] {φ : α → E} (L : continuous_linear_map ℝ E F) (φ_int : measure_theory.integrable φ) : measure_theory.integrable fun (a : α) => coe_fn L (φ a) := measure_theory.integrable.mono' (measure_theory.integrable.const_mul (measure_theory.integrable.norm φ_int) (norm L)) (measurable.comp_ae_measurable (continuous_linear_map.measurable L) (measure_theory.integrable.ae_measurable φ_int)) (filter.eventually_of_forall fun (a : α) => le_op_norm L (φ a)) /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`. -/ def comp_l1 {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] (L : continuous_linear_map ℝ E F) (φ : measure_theory.l1 α E μ) : measure_theory.l1 α F μ := measure_theory.l1.of_fun (fun (a : α) => coe_fn L (coe_fn φ a)) sorry theorem comp_l1_apply {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] (L : continuous_linear_map ℝ E F) (φ : measure_theory.l1 α E μ) : filter.eventually (fun (a : α) => coe_fn (comp_l1 L φ) a = coe_fn L (coe_fn φ a)) (measure_theory.measure.ae μ) := measure_theory.l1.to_fun_of_fun (fun (a : α) => coe_fn L (coe_fn φ a)) (comp_l1._proof_6 L φ) theorem integrable_comp_l1 {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] (L : continuous_linear_map ℝ E F) (φ : measure_theory.l1 α E μ) : measure_theory.integrable fun (a : α) => coe_fn L (coe_fn φ a) := integrable_comp L (measure_theory.l1.integrable φ) theorem measurable_comp_l1 {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] (L : continuous_linear_map ℝ E F) (φ : measure_theory.l1 α E μ) : measurable fun (a : α) => coe_fn L (coe_fn φ a) := measurable.comp (continuous_linear_map.measurable L) (measure_theory.l1.measurable φ) theorem integral_comp_l1 {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] [complete_space F] (L : continuous_linear_map ℝ E F) (φ : measure_theory.l1 α E μ) : (measure_theory.integral μ fun (a : α) => coe_fn (comp_l1 L φ) a) = measure_theory.integral μ fun (a : α) => coe_fn L (coe_fn φ a) := sorry /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1ₗ {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] (L : continuous_linear_map ℝ E F) : linear_map ℝ (measure_theory.l1 α E μ) (measure_theory.l1 α F μ) := linear_map.mk (fun (φ : measure_theory.l1 α E μ) => comp_l1 L φ) sorry sorry theorem norm_comp_l1_le {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] (φ : measure_theory.l1 α E μ) (L : continuous_linear_map ℝ E F) : norm (comp_l1 L φ) ≤ norm L * norm φ := sorry /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1L {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] (L : continuous_linear_map ℝ E F) : continuous_linear_map ℝ (measure_theory.l1 α E μ) (measure_theory.l1 α F μ) := linear_map.mk_continuous (comp_l1ₗ L) (norm L) sorry theorem norm_compl1L_le {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] (L : continuous_linear_map ℝ E F) : norm (comp_l1L L) ≤ norm L := op_norm_le_bound (comp_l1L L) (norm_nonneg L) fun (φ : measure_theory.l1 α E μ) => norm_comp_l1_le φ L theorem continuous_integral_comp_l1 {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] [complete_space F] (L : continuous_linear_map ℝ E F) : continuous fun (φ : measure_theory.l1 α E μ) => measure_theory.integral μ fun (a : α) => coe_fn L (coe_fn φ a) := sorry theorem integral_comp_comm {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] [complete_space F] [complete_space E] (L : continuous_linear_map ℝ E F) {φ : α → E} (φ_int : measure_theory.integrable φ) : (measure_theory.integral μ fun (a : α) => coe_fn L (φ a)) = coe_fn L (measure_theory.integral μ fun (a : α) => φ a) := sorry theorem integral_comp_l1_comm {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [measurable_space F] [borel_space F] [borel_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology F] [complete_space F] [complete_space E] (L : continuous_linear_map ℝ E F) (φ : measure_theory.l1 α E μ) : (measure_theory.integral μ fun (a : α) => coe_fn L (coe_fn φ a)) = coe_fn L (measure_theory.integral μ fun (a : α) => coe_fn φ a) := integral_comp_comm L (measure_theory.l1.integrable φ) end continuous_linear_map theorem fst_integral {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [measurable_space F] [borel_space F] [topological_space.second_countable_topology F] [complete_space F] {f : α → E × F} (hf : measure_theory.integrable f) : prod.fst (measure_theory.integral μ fun (x : α) => f x) = measure_theory.integral μ fun (x : α) => prod.fst (f x) := Eq.symm (continuous_linear_map.integral_comp_comm (continuous_linear_map.fst ℝ E F) hf) theorem snd_integral {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [measurable_space F] [borel_space F] [topological_space.second_countable_topology F] [complete_space F] {f : α → E × F} (hf : measure_theory.integrable f) : prod.snd (measure_theory.integral μ fun (x : α) => f x) = measure_theory.integral μ fun (x : α) => prod.snd (f x) := Eq.symm (continuous_linear_map.integral_comp_comm (continuous_linear_map.snd ℝ E F) hf) theorem integral_pair {α : Type u_1} {E : Type u_3} {F : Type u_4} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [normed_group F] [normed_space ℝ F] [borel_space E] [topological_space.second_countable_topology E] [complete_space E] [measurable_space F] [borel_space F] [topological_space.second_countable_topology F] [complete_space F] {f : α → E} {g : α → F} (hf : measure_theory.integrable f) (hg : measure_theory.integrable g) : (measure_theory.integral μ fun (x : α) => (f x, g x)) = (measure_theory.integral μ fun (x : α) => f x, measure_theory.integral μ fun (x : α) => g x) := (fun (this : measure_theory.integrable fun (x : α) => (f x, g x)) => prod.ext (fst_integral this) (snd_integral this)) (measure_theory.integrable.prod_mk hf hg) theorem integral_smul_const {α : Type u_1} {E : Type u_3} [measurable_space α] [measurable_space E] [normed_group E] {μ : measure_theory.measure α} [normed_space ℝ E] [borel_space E] [topological_space.second_countable_topology E] [complete_space E] (f : α → ℝ) (c : E) : (measure_theory.integral μ fun (x : α) => f x • c) = (measure_theory.integral μ fun (x : α) => f x) • c := sorry end Mathlib
15c06680da3bd8b587cc5183de7df0c7e60e5e38
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Ringoid1.lean
e1a76bf29432b29d7ecf2070007d4c7e8194c126
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
9,929
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Ringoid1 structure Ringoid1 (A : Type) : Type := (times : (A → (A → A))) (plus : (A → (A → A))) (one : A) (leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z)))) (rightDistributive_times_plus : (∀ {x y z : A} , (times (plus y z) x) = (plus (times y x) (times z x)))) open Ringoid1 structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) (oneS : AS) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (oneP : (Prod A A)) (leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP)))) (rightDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP (plusP yP zP) xP) = (plusP (timesP yP xP) (timesP zP xP)))) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (Ringoid1 A1)) (Ri2 : (Ringoid1 A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Ri1) x1 x2)) = ((times Ri2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ri1) x1 x2)) = ((plus Ri2) (hom x1) (hom x2)))) (pres_one : (hom (one Ri1)) = (one Ri2)) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (Ringoid1 A1)) (Ri2 : (Ringoid1 A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Ri1) x1 x2) ((times Ri2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ri1) x1 x2) ((plus Ri2) y1 y2)))))) (interp_one : (interp (one Ri1) (one Ri2))) inductive Ringoid1LTerm : Type | timesL : (Ringoid1LTerm → (Ringoid1LTerm → Ringoid1LTerm)) | plusL : (Ringoid1LTerm → (Ringoid1LTerm → Ringoid1LTerm)) | oneL : Ringoid1LTerm open Ringoid1LTerm inductive ClRingoid1ClTerm (A : Type) : Type | sing : (A → ClRingoid1ClTerm) | timesCl : (ClRingoid1ClTerm → (ClRingoid1ClTerm → ClRingoid1ClTerm)) | plusCl : (ClRingoid1ClTerm → (ClRingoid1ClTerm → ClRingoid1ClTerm)) | oneCl : ClRingoid1ClTerm open ClRingoid1ClTerm inductive OpRingoid1OLTerm (n : ℕ) : Type | v : ((fin n) → OpRingoid1OLTerm) | timesOL : (OpRingoid1OLTerm → (OpRingoid1OLTerm → OpRingoid1OLTerm)) | plusOL : (OpRingoid1OLTerm → (OpRingoid1OLTerm → OpRingoid1OLTerm)) | oneOL : OpRingoid1OLTerm open OpRingoid1OLTerm inductive OpRingoid1OL2Term2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRingoid1OL2Term2) | sing2 : (A → OpRingoid1OL2Term2) | timesOL2 : (OpRingoid1OL2Term2 → (OpRingoid1OL2Term2 → OpRingoid1OL2Term2)) | plusOL2 : (OpRingoid1OL2Term2 → (OpRingoid1OL2Term2 → OpRingoid1OL2Term2)) | oneOL2 : OpRingoid1OL2Term2 open OpRingoid1OL2Term2 def simplifyCl {A : Type} : ((ClRingoid1ClTerm A) → (ClRingoid1ClTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | oneCl := oneCl | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRingoid1OLTerm n) → (OpRingoid1OLTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | oneOL := oneOL | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRingoid1OL2Term2 n A) → (OpRingoid1OL2Term2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | oneOL2 := oneOL2 | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Ringoid1 A) → (Ringoid1LTerm → A)) | Ri (timesL x1 x2) := ((times Ri) (evalB Ri x1) (evalB Ri x2)) | Ri (plusL x1 x2) := ((plus Ri) (evalB Ri x1) (evalB Ri x2)) | Ri oneL := (one Ri) def evalCl {A : Type} : ((Ringoid1 A) → ((ClRingoid1ClTerm A) → A)) | Ri (sing x1) := x1 | Ri (timesCl x1 x2) := ((times Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri (plusCl x1 x2) := ((plus Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri oneCl := (one Ri) def evalOpB {A : Type} {n : ℕ} : ((Ringoid1 A) → ((vector A n) → ((OpRingoid1OLTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (timesOL x1 x2) := ((times Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars (plusOL x1 x2) := ((plus Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars oneOL := (one Ri) def evalOp {A : Type} {n : ℕ} : ((Ringoid1 A) → ((vector A n) → ((OpRingoid1OL2Term2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (timesOL2 x1 x2) := ((times Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars (plusOL2 x1 x2) := ((plus Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars oneOL2 := (one Ri) def inductionB {P : (Ringoid1LTerm → Type)} : ((∀ (x1 x2 : Ringoid1LTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : Ringoid1LTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((P oneL) → (∀ (x : Ringoid1LTerm) , (P x))))) | ptimesl pplusl p1l (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl p1l x1) (inductionB ptimesl pplusl p1l x2)) | ptimesl pplusl p1l (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl p1l x1) (inductionB ptimesl pplusl p1l x2)) | ptimesl pplusl p1l oneL := p1l def inductionCl {A : Type} {P : ((ClRingoid1ClTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRingoid1ClTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClRingoid1ClTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((P oneCl) → (∀ (x : (ClRingoid1ClTerm A)) , (P x)))))) | psing ptimescl ppluscl p1cl (sing x1) := (psing x1) | psing ptimescl ppluscl p1cl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl p1cl x1) (inductionCl psing ptimescl ppluscl p1cl x2)) | psing ptimescl ppluscl p1cl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl p1cl x1) (inductionCl psing ptimescl ppluscl p1cl x2)) | psing ptimescl ppluscl p1cl oneCl := p1cl def inductionOpB {n : ℕ} {P : ((OpRingoid1OLTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRingoid1OLTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpRingoid1OLTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((P oneOL) → (∀ (x : (OpRingoid1OLTerm n)) , (P x)))))) | pv ptimesol pplusol p1ol (v x1) := (pv x1) | pv ptimesol pplusol p1ol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol p1ol x1) (inductionOpB pv ptimesol pplusol p1ol x2)) | pv ptimesol pplusol p1ol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol p1ol x1) (inductionOpB pv ptimesol pplusol p1ol x2)) | pv ptimesol pplusol p1ol oneOL := p1ol def inductionOp {n : ℕ} {A : Type} {P : ((OpRingoid1OL2Term2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRingoid1OL2Term2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpRingoid1OL2Term2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((P oneOL2) → (∀ (x : (OpRingoid1OL2Term2 n A)) , (P x))))))) | pv2 psing2 ptimesol2 pplusol2 p1ol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 pplusol2 p1ol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 pplusol2 p1ol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p1ol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p1ol2 x2)) | pv2 psing2 ptimesol2 pplusol2 p1ol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p1ol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p1ol2 x2)) | pv2 psing2 ptimesol2 pplusol2 p1ol2 oneOL2 := p1ol2 def stageB : (Ringoid1LTerm → (Staged Ringoid1LTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | oneL := (Now oneL) def stageCl {A : Type} : ((ClRingoid1ClTerm A) → (Staged (ClRingoid1ClTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | oneCl := (Now oneCl) def stageOpB {n : ℕ} : ((OpRingoid1OLTerm n) → (Staged (OpRingoid1OLTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | oneOL := (Now oneOL) def stageOp {n : ℕ} {A : Type} : ((OpRingoid1OL2Term2 n A) → (Staged (OpRingoid1OL2Term2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | oneOL2 := (Now oneOL2) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (oneT : (Repr A)) end Ringoid1
79ed8a9c68759201930fb0176eba8a8db321b0df
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/measure_theory/measure_space.lean
fdb00547df5bddfe21db298602f48970c388ac80
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
97,228
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import measure_theory.outer_measure import order.filter.countable_Inter import data.set.accumulate /-! # Measure spaces Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the extended nonnegative reals that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint sets is equal to the measure of the individual sets. Every measure can be canonically extended to an outer measure, so that it assigns values to all subsets, not just the measurable subsets. On the other hand, a measure that is countably additive on measurable sets can be restricted to measurable sets to obtain a measure. In this file a measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`. We introduce the following typeclasses for measures: * `probability_measure μ`: `μ univ = 1`; * `finite_measure μ`: `μ univ < ⊤`; * `sigma_finite μ`: there exists a countable collection of measurable sets that cover `univ` where `μ` is finite; * `locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ⊤`; * `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as `∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`. Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0` on the null sets. ## Main statements * `completion` is the completion of a measure to all null measurable sets. * `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure. ## Implementation notes Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`. This conveniently allows us to apply the measure to sets without proving that they are measurable. We get countable subadditivity for all sets, but only countable additivity for measurable sets. You often don't want to define a measure via its constructor. Two ways that are sometimes more convenient: * `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets and proving the properties (1) and (2) mentioned above. * `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that all measurable sets in the measurable space are Carathéodory measurable. To prove that two measures are equal, there are multiple options: * `ext`: two measures are equal if they are equal on all measurable sets. * `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating the measurable sets, if the π-system contains a spanning increasing sequence of sets where the measures take finite value (in particular the measures are σ-finite). This is a special case of the more general `ext_of_generate_from_of_cover` * `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using `C ∪ {univ}`, but is easier to work with. A `measure_space` is a class that is a measurable space with a canonical measure. The measure is denoted `volume`. ## References * <https://en.wikipedia.org/wiki/Measure_(mathematics)> * <https://en.wikipedia.org/wiki/Complete_measure> * <https://en.wikipedia.org/wiki/Almost_everywhere> ## Tags measure, almost everywhere, measure space, completion, null set, null measurable set -/ noncomputable theory open classical set filter function measurable_space open_locale classical topological_space big_operators filter variables {α β γ δ ι : Type*} namespace measure_theory /-- A measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. -/ structure measure (α : Type*) [measurable_space α] extends outer_measure α := (m_Union ⦃f : ℕ → set α⦄ : (∀ i, is_measurable (f i)) → pairwise (disjoint on f) → measure_of (⋃ i, f i) = (∑' i, measure_of (f i))) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun [measurable_space α] : has_coe_to_fun (measure α) := ⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩ section variables [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ t : set α} namespace measure /-! ### General facts about measures -/ /-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/ def of_measurable (m : Π (s : set α), is_measurable s → ennreal) (m0 : m ∅ is_measurable.empty = 0) (mU : ∀ {{f : ℕ → set α}} (h : ∀ i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (is_measurable.Union h) = (∑' i, m (f i) (h i))) : measure α := { m_Union := λ f hf hd, show induced_outer_measure m _ m0 (Union f) = ∑' i, induced_outer_measure m _ m0 (f i), begin rw [induced_outer_measure_eq m0 mU, mU hf hd], congr, funext n, rw induced_outer_measure_eq m0 mU end, trimmed := show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin unfold outer_measure.trim, congr, funext s hs, exact induced_outer_measure_eq m0 mU hs end, ..induced_outer_measure m _ m0 } lemma of_measurable_apply {m : Π (s : set α), is_measurable s → ennreal} {m0 : m ∅ is_measurable.empty = 0} {mU : ∀ {{f : ℕ → set α}} (h : ∀ i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (is_measurable.Union h) = (∑' i, m (f i) (h i))} (s : set α) (hs : is_measurable s) : of_measurable m m0 mU s = m s hs := induced_outer_measure_eq m0 mU hs lemma to_outer_measure_injective : injective (to_outer_measure : measure α → outer_measure α) := λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h } @[ext] lemma ext (h : ∀ s, is_measurable s → μ₁ s = μ₂ s) : μ₁ = μ₂ := to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed] lemma ext_iff : μ₁ = μ₂ ↔ ∀ s, is_measurable s → μ₁ s = μ₂ s := ⟨by { rintro rfl s hs, refl }, measure.ext⟩ end measure @[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl lemma to_outer_measure_apply (s : set α) : μ.to_outer_measure s = μ s := rfl lemma measure_eq_trim (s : set α) : μ s = μ.to_outer_measure.trim s := by rw μ.trimmed; refl lemma measure_eq_infi (s : set α) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl /-- A variant of `measure_eq_infi` which has a single `infi`. This is useful when applying a lemma next that only works for non-empty infima, in which case you can use `nonempty_measurable_superset`. -/ lemma measure_eq_infi' (μ : measure α) (s : set α) : μ s = ⨅ t : { t // s ⊆ t ∧ is_measurable t}, μ t := by simp_rw [infi_subtype, infi_and, subtype.coe_mk, ← measure_eq_infi] lemma measure_eq_induced_outer_measure : μ s = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_induced_outer_measure : μ.to_outer_measure = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty := μ.trimmed.symm lemma measure_eq_extend (hs : is_measurable s) : μ s = extend (λ t (ht : is_measurable t), μ t) s := by { rw [measure_eq_induced_outer_measure, induced_outer_measure_eq_extend _ _ hs], exact μ.m_Union } @[simp] lemma measure_empty : μ ∅ = 0 := μ.empty lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty := ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 := nonpos_iff_eq_zero.1 $ h₂ ▸ measure_mono h lemma measure_mono_top (h : s₁ ⊆ s₂) (h₁ : μ s₁ = ⊤) : μ s₂ = ⊤ := top_unique $ h₁ ▸ measure_mono h lemma exists_is_measurable_superset_of_null (h : μ s = 0) : ∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 := outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h]) lemma exists_is_measurable_superset_iff_measure_eq_zero : (∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0) ↔ μ s = 0 := ⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_null⟩ theorem measure_Union_le [encodable β] (s : β → set α) : μ (⋃ i, s i) ≤ (∑' i, μ (s i)) := μ.to_outer_measure.Union _ lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑' p : s, μ (f p) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union], apply measure_Union_le end lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion_le s.countable_to_set f end lemma measure_bUnion_lt_top {s : set β} {f : β → set α} (hs : finite s) (hfin : ∀ i ∈ s, μ (f i) < ⊤) : μ (⋃ i ∈ s, f i) < ⊤ := begin convert (measure_bUnion_finset_le hs.to_finset f).trans_lt _, { ext, rw [finite.mem_to_finset] }, apply ennreal.sum_lt_top, simpa only [finite.mem_to_finset] end lemma measure_Union_null [encodable β] {s : β → set α} : (∀ i, μ (s i) = 0) → μ (⋃ i, s i) = 0 := μ.to_outer_measure.Union_null lemma measure_Union_null_iff [encodable ι] {s : ι → set α} : μ (⋃ i, s i) = 0 ↔ ∀ i, μ (s i) = 0 := ⟨λ h i, measure_mono_null (subset_Union _ _) h, measure_Union_null⟩ theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ := μ.to_outer_measure.union _ _ lemma measure_union_null : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 := μ.to_outer_measure.union_null lemma measure_union_null_iff : μ (s₁ ∪ s₂) = 0 ↔ μ s₁ = 0 ∧ μ s₂ = 0:= ⟨λ h, ⟨measure_mono_null (subset_union_left _ _) h, measure_mono_null (subset_union_right _ _) h⟩, λ h, measure_union_null h.1 h.2⟩ lemma measure_Union [encodable β] {f : β → set α} (hn : pairwise (disjoint on f)) (h : ∀ i, is_measurable (f i)) : μ (⋃ i, f i) = (∑' i, μ (f i)) := begin rw [measure_eq_extend (is_measurable.Union h), extend_Union is_measurable.empty _ is_measurable.Union _ hn h], { simp [measure_eq_extend, h] }, { exact μ.empty }, { exact μ.m_Union } end lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : μ (s₁ ∪ s₂) = μ s₁ + μ s₂ := begin rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b h₂ h₁] end lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s) (hd : pairwise_on s (disjoint on f)) (h : ∀ b ∈ s, is_measurable (f b)) : μ (⋃ b ∈ s, f b) = ∑' p : s, μ (f p) := begin haveI := hs.to_encodable, rw bUnion_eq_Union, exact measure_Union (hd.on_injective subtype.coe_injective $ λ x, x.2) (λ x, h x x.2) end lemma measure_sUnion {S : set (set α)} (hs : countable S) (hd : pairwise_on S disjoint) (h : ∀ s ∈ S, is_measurable s) : μ (⋃₀ S) = ∑' s : S, μ s := by rw [sUnion_eq_bUnion, measure_bUnion hs hd h] lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f)) (hm : ∀ b ∈ s, is_measurable (f b)) : μ (⋃ b ∈ s, f b) = ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion s.countable_to_set hd hm end /-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β} (hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) : (∑' b : s, μ (f ⁻¹' {↑b})) = μ (f ⁻¹' s) := by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf] /-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma sum_measure_preimage_singleton (s : finset β) {f : α → β} (hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) : ∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) := by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf, finset.bUnion_preimage_singleton] lemma measure_diff (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) (h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ := begin refine (ennreal.add_sub_self' h_fin).symm.trans _, rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h] end lemma measure_compl (h₁ : is_measurable s) (h_fin : μ s < ⊤) : μ (sᶜ) = μ univ - μ s := by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) is_measurable.univ h₁ h_fin } lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : pairwise_on ↑s (disjoint on t)) : ∑ i in s, μ (t i) ≤ μ (univ : set α) := by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) } lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : pairwise (disjoint on s)) : (∑' i, μ (s i)) ≤ μ (univ : set α) := begin rw [ennreal.tsum_eq_supr_sum], exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij)) end /-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then one of the intersections `s i ∩ s j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) : ∃ i j (h : i ≠ j), (s i ∩ s j).nonempty := begin contrapose! H, apply tsum_measure_le_measure_univ hs, exact λ i j hij x hx, H i j hij ⟨x, hx⟩ end /-- Pigeonhole principle for measure spaces: if `s` is a `finset` and `∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) : ∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty := begin contrapose! H, apply sum_measure_le_measure_univ h, exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩ end /-- Continuity from below: the measure of the union of a directed sequence of measurable sets is the supremum of the measures. -/ lemma measure_Union_eq_supr [encodable ι] {s : ι → set α} (h : ∀ i, is_measurable (s i)) (hd : directed (⊆) s) : μ (⋃ i, s i) = ⨆ i, μ (s i) := begin by_cases hι : nonempty ι, swap, { simp only [supr_of_empty hι, Union], exact measure_empty }, resetI, refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _), have : ∀ n, is_measurable (disjointed (λ n, ⋃ b ∈ encodable.decode2 ι n, s b) n) := is_measurable.disjointed (is_measurable.bUnion_decode2 h), rw [← encodable.Union_decode2, ← Union_disjointed, measure_Union disjoint_disjointed this, ennreal.tsum_eq_supr_nat], simp only [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (λ n _, this n)], refine supr_le (λ n, _), refine le_trans (_ : _ ≤ μ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode2 ι k), s i)) _, exact measure_mono (bUnion_subset_bUnion_right (λ k hk, disjointed_subset)), simp only [← finset.bUnion_option_to_finset, ← finset.bUnion_bind], generalize : (finset.range n).bind (λ k, (encodable.decode2 ι k).to_finset) = t, rcases hd.finset_le t with ⟨i, hi⟩, exact le_supr_of_le i (measure_mono $ bUnion_subset hi) end lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : countable t) (h : ∀ i ∈ t, is_measurable (s i)) (hd : directed_on ((⊆) on s) t) : μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) := begin haveI := ht.to_encodable, rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe, supr_subtype'], refl end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the infimum of the measures. -/ lemma measure_Inter_eq_infi [encodable ι] {s : ι → set α} (h : ∀ i, is_measurable (s i)) (hd : directed (⊇) s) (hfin : ∃ i, μ (s i) < ⊤) : μ (⋂ i, s i) = (⨅ i, μ (s i)) := begin rcases hfin with ⟨k, hk⟩, rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi, ← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)), ← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h) (lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk), diff_Inter, measure_Union_eq_supr], { congr' 1, refine le_antisymm (supr_le_supr2 $ λ i, _) (supr_le_supr $ λ i, _), { rcases hd i k with ⟨j, hji, hjk⟩, use j, rw [← measure_diff hjk (h _) (h _) ((measure_mono hjk).trans_lt hk)], exact measure_mono (diff_subset_diff_right hji) }, { rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i), set.union_comm], exact measure_mono (diff_subset_iff.1 $ subset.refl _) } }, { exact λ i, (h k).diff (h i) }, { exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) } end lemma measure_eq_inter_diff (hs : is_measurable s) (ht : is_measurable t) : μ s = μ (s ∩ t) + μ (s \ t) := have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs , by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t] lemma measure_union_add_inter (hs : is_measurable s) (ht : is_measurable t) : μ (s ∪ t) + μ (s ∩ t) = μ s + μ t := by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right, union_diff_right, measure_eq_inter_diff hs ht], ac_refl } /-- Continuity from below: the measure of the union of an increasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Union {s : ℕ → set α} (hs : ∀ n, is_measurable (s n)) (hm : monotone s) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋃ n, s n))) := begin rw measure_Union_eq_supr hs (directed_of_sup hm), exact tendsto_at_top_supr (assume n m hnm, measure_mono $ hm hnm) end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Inter {s : ℕ → set α} (hs : ∀ n, is_measurable (s n)) (hm : ∀ ⦃n m⦄, n ≤ m → s m ⊆ s n) (hf : ∃ i, μ (s i) < ⊤) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋂ n, s n))) := begin rw measure_Inter_eq_infi hs (directed_of_sup hm) hf, exact tendsto_at_top_infi (assume n m hnm, measure_mono $ hm hnm), end /-- One direction of the Borel-Cantelli lemma: if (sᵢ) is a sequence of measurable sets such that ∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/ lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∀ i, is_measurable (s i)) (hs' : (∑' i, μ (s i)) ≠ ⊤) : μ (limsup at_top s) = 0 := begin rw limsup_eq_infi_supr_of_nat', -- We will show that both `μ (⨅ n, ⨆ i, s (i + n))` and `0` are the limit of `μ (⊔ i, s (i + n))` -- as `n` tends to infinity. For the former, we use continuity from above. refine tendsto_nhds_unique (tendsto_measure_Inter (λ i, is_measurable.Union (λ b, hs (b + i))) _ ⟨0, lt_of_le_of_lt (measure_Union_le s) (ennreal.lt_top_iff_ne_top.2 hs')⟩) _, { intros n m hnm x, simp only [set.mem_Union], exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ }, { -- For the latter, notice that, `μ (⨆ i, s (i + n)) ≤ ∑' s (i + n)`. Since the right hand side -- converges to `0` by hypothesis, so does the former and the proof is complete. exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (ennreal.tendsto_sum_nat_add (μ ∘ s) hs') (eventually_of_forall (by simp only [forall_const, zero_le])) (eventually_of_forall (λ i, measure_Union_le _))) } end lemma measure_if {x : β} {t : set β} {s : set α} {μ : measure α} : μ (if x ∈ t then s else ∅) = indicator t (λ _, μ s) x := by { split_ifs; simp [h] } end section outer_measure variables [ms : measurable_space α] {s t : set α} include ms /-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are Carathéodory measurable. -/ def outer_measure.to_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : measure α := measure.of_measurable (λ s _, m s) m.empty (λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd) lemma le_to_outer_measure_caratheodory (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory := begin assume s hs, rw to_outer_measure_eq_induced_outer_measure, refine outer_measure.of_function_caratheodory (λ t, le_infi $ λ ht, _), rw [← measure_eq_extend (ht.inter hs), ← measure_eq_extend (ht.diff hs), ← measure_union _ (ht.inter hs) (ht.diff hs), inter_union_diff], exact le_refl _, exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁ end @[simp] lemma to_measure_to_outer_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : (m.to_measure h).to_outer_measure = m.trim := rfl @[simp] lemma to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) {s : set α} (hs : is_measurable s) : m.to_measure h s = m s := m.trim_eq hs lemma le_to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) (s : set α) : m s ≤ m.to_measure h s := m.le_trim s @[simp] lemma to_outer_measure_to_measure {μ : measure α} : μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ := measure.ext $ λ s, μ.to_outer_measure.trim_eq end outer_measure variables [measurable_space α] [measurable_space β] [measurable_space γ] variables {μ μ₁ μ₂ ν ν' ν₁ ν₂ : measure α} {s s' t : set α} namespace measure protected lemma caratheodory (μ : measure α) (hs : is_measurable s) : μ (t ∩ s) + μ (t \ s) = μ t := (le_to_outer_measure_caratheodory μ s hs t).symm /-! ### The `ennreal`-module of measures -/ instance : has_zero (measure α) := ⟨{ to_outer_measure := 0, m_Union := λ f hf hd, tsum_zero.symm, trimmed := outer_measure.trim_zero }⟩ @[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl @[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 := ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty] instance : inhabited (measure α) := ⟨0⟩ instance : has_add (measure α) := ⟨λ μ₁ μ₂, { to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure, m_Union := λ s hs hd, show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, μ₁ (s i) + μ₂ (s i), by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs], trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩ @[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) : (μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl @[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl theorem add_apply (μ₁ μ₂ : measure α) (s : set α) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl instance add_comm_monoid : add_comm_monoid (measure α) := to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure add_to_outer_measure instance : has_scalar ennreal (measure α) := ⟨λ c μ, { to_outer_measure := c • μ.to_outer_measure, m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left], trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩ @[simp] theorem smul_to_outer_measure (c : ennreal) (μ : measure α) : (c • μ).to_outer_measure = c • μ.to_outer_measure := rfl @[simp, norm_cast] theorem coe_smul (c : ennreal) (μ : measure α) : ⇑(c • μ) = c • μ := rfl theorem smul_apply (c : ennreal) (μ : measure α) (s : set α) : (c • μ) s = c * μ s := rfl instance : semimodule ennreal (measure α) := injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩ to_outer_measure_injective smul_to_outer_measure /-! ### The complete lattice of measures -/ instance : partial_order (measure α) := { le := λ m₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s, le_refl := assume m s hs, le_refl _, le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs), le_antisymm := assume m₁ m₂ h₁ h₂, ext $ assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) } theorem le_iff : μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl theorem to_outer_measure_le : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ := by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl theorem le_iff' : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s := to_outer_measure_le.symm theorem lt_iff : μ < ν ↔ μ ≤ ν ∧ ∃ s, is_measurable s ∧ μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop] theorem lt_iff' : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le] -- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)` protected lemma add_le_add_left (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ := λ s hs, add_le_add_left (hμ s hs) _ protected lemma add_le_add_right (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν := λ s hs, add_le_add_right (hμ s hs) _ protected lemma add_le_add (hμ : μ₁ ≤ μ₂) (hν : ν₁ ≤ ν₂) : μ₁ + ν₁ ≤ μ₂ + ν₂ := λ s hs, add_le_add (hμ s hs) (hν s hs) protected lemma le_add_left (h : μ ≤ ν) : μ ≤ ν' + ν := λ s hs, le_add_left (h s hs) protected lemma le_add_right (h : μ ≤ ν) : μ ≤ ν + ν' := λ s hs, le_add_right (h s hs) section Inf variables {m : set (measure α)} lemma Inf_caratheodory (s : set α) (hs : is_measurable s) : (Inf (to_outer_measure '' m)).caratheodory.is_measurable' s := begin rw [outer_measure.Inf_eq_bounded_by_Inf_gen], refine outer_measure.bounded_by_caratheodory (λ t, _), simp only [outer_measure.Inf_gen, le_infi_iff, ball_image_iff, coe_to_outer_measure, measure_eq_infi t], intros μ hμ u htu hu, have hm : ∀ {s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t, { intros s t hst, rw [outer_measure.Inf_gen_def], refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _), rw [to_outer_measure_apply], refine measure_mono hst }, rw [measure_eq_inter_diff hu hs], refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu) end instance : has_Inf (measure α) := ⟨λ m, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩ lemma Inf_apply (hs : is_measurable s) : Inf m s = Inf (to_outer_measure '' m) s := to_measure_apply _ _ hs private lemma measure_Inf_le (h : μ ∈ m) : Inf m ≤ μ := have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h), assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s private lemma measure_le_Inf (h : ∀ μ' ∈ m, μ ≤ μ') : μ ≤ Inf m := have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) := le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ, assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s instance : complete_lattice (measure α) := { bot := 0, bot_le := assume a s hs, by exact bot_le, /- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top), le_top := assume a s hs, by cases s.eq_empty_or_nonempty with h h; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply], -/ .. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, measure_Inf_le, λ _, measure_le_Inf⟩) } end Inf protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le lemma nonpos_iff_eq_zero' : μ ≤ 0 ↔ μ = 0 := μ.zero_le.le_iff_eq @[simp] lemma measure_univ_eq_zero : μ univ = 0 ↔ μ = 0 := ⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩ /-! ### Pushforward and pullback -/ /-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/ def lift_linear (f : outer_measure α →ₗ[ennreal] outer_measure β) (hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) : measure α →ₗ[ennreal] measure β := { to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ), map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs], map_smul' := λ c μ, ext $ λ s hs, by simp [hs] } @[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf) {s : set β} (hs : is_measurable s) : lift_linear f hf μ s = f μ.to_outer_measure s := to_measure_apply _ _ hs lemma le_lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf) (s : set β) : f μ.to_outer_measure s ≤ lift_linear f hf μ s := le_to_measure_apply _ _ s /-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/ def map (f : α → β) : measure α →ₗ[ennreal] measure β := if hf : measurable f then lift_linear (outer_measure.map f) $ λ μ s hs t, le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t) else 0 /-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see `measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/ @[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : map f μ s = μ (f ⁻¹' s) := by simp [map, dif_pos hf, hs] @[simp] lemma map_id : map id μ = μ := ext $ λ s, map_apply measurable_id lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : map g (map f μ) = map (g ∘ f) μ := ext $ λ s hs, by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp] lemma map_mono {f : α → β} (hf : measurable f) (h : μ ≤ ν) : map f μ ≤ map f ν := λ s hs, by simp [hf, hs, h _ (hf hs)] /-- Even if `s` is not measurable, we can bound `map f μ s` from below. See also `measurable_equiv.map_apply`. -/ theorem le_map_apply {f : α → β} (hf : measurable f) (s : set β) : μ (f ⁻¹' s) ≤ map f μ s := begin rw [measure_eq_infi' (map f μ)], refine le_infi _, rintro ⟨t, hst, ht⟩, convert measure_mono (preimage_mono hst), exact map_apply hf ht end /-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each measurable set `s` we have `comap f μ s = μ (f '' s)`. -/ def comap (f : α → β) : measure β →ₗ[ennreal] measure α := if hf : injective f ∧ ∀ s, is_measurable s → is_measurable (f '' s) then lift_linear (outer_measure.comap f) $ λ μ s hs t, begin simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1], apply le_to_outer_measure_caratheodory, exact hf.2 s hs end else 0 lemma comap_apply (f : α → β) (hfi : injective f) (hf : ∀ s, is_measurable s → is_measurable (f '' s)) (μ : measure β) (hs : is_measurable s) : comap f μ s = μ (f '' s) := begin rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure], exact ⟨hfi, hf⟩ end /-! ### Restricting a measure -/ /-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/ def restrictₗ (s : set α) : measure α →ₗ[ennreal] measure α := lift_linear (outer_measure.restrict s) $ λ μ s' hs' t, begin suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'), { simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] }, exact le_to_outer_measure_caratheodory _ _ hs' _, end /-- Restrict a measure `μ` to a set `s`. -/ def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ @[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) : restrictₗ s μ = μ.restrict s := rfl @[simp] lemma restrict_apply (ht : is_measurable t) : μ.restrict s t = μ (t ∩ s) := by simp [← restrictₗ_apply, restrictₗ, ht] lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s := by rw [restrict_apply is_measurable.univ, set.univ_inter] lemma le_restrict_apply (s t : set α) : μ (t ∩ s) ≤ μ.restrict s t := by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp } @[simp] lemma restrict_add (μ ν : measure α) (s : set α) : (μ + ν).restrict s = μ.restrict s + ν.restrict s := (restrictₗ s).map_add μ ν @[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 := (restrictₗ s).map_zero @[simp] lemma restrict_smul (c : ennreal) (μ : measure α) (s : set α) : (c • μ).restrict s = c • μ.restrict s := (restrictₗ s).map_smul c μ @[simp] lemma restrict_restrict (hs : is_measurable s) : (μ.restrict t).restrict s = μ.restrict (s ∩ t) := ext $ λ u hu, by simp [*, set.inter_assoc] lemma restrict_apply_eq_zero (ht : is_measurable t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := by rw [restrict_apply ht] lemma measure_inter_eq_zero_of_restrict (h : μ.restrict s t = 0) : μ (t ∩ s) = 0 := nonpos_iff_eq_zero.1 (h ▸ le_restrict_apply _ _) lemma restrict_apply_eq_zero' (hs : is_measurable s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := begin refine ⟨measure_inter_eq_zero_of_restrict, λ h, _⟩, rcases exists_is_measurable_superset_of_null h with ⟨t', htt', ht', ht'0⟩, apply measure_mono_null ((inter_subset _ _ _).1 htt'), rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self, set.empty_union], exact measure_mono_null (inter_subset_left _ _) ht'0 end @[simp] lemma restrict_eq_zero : μ.restrict s = 0 ↔ μ s = 0 := by rw [← measure_univ_eq_zero, restrict_apply_univ] @[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs] @[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs] lemma restrict_union_apply (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s) (hs' : is_measurable s') (ht : is_measurable t) : μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t := begin simp only [restrict_apply, ht, set.inter_union_distrib_left], exact measure_union h (ht.inter hs) (ht.inter hs'), end lemma restrict_union (h : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) : μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t := ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht' lemma restrict_union_add_inter (hs : is_measurable s) (ht : is_measurable t) : μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t := begin ext1 u hu, simp only [add_apply, restrict_apply hu, inter_union_distrib_left], convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3, rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self] end @[simp] lemma restrict_add_restrict_compl (hs : is_measurable s) : μ.restrict s + μ.restrict sᶜ = μ := by rw [← restrict_union disjoint_compl_right hs hs.compl, union_compl_self, restrict_univ] @[simp] lemma restrict_compl_add_restrict (hs : is_measurable s) : μ.restrict sᶜ + μ.restrict s = μ := by rw [add_comm, restrict_add_restrict_compl hs] lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' := begin intros t ht, suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'), by simpa [ht, inter_union_distrib_left], apply measure_union_le end lemma restrict_Union_apply [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, is_measurable (s i)) {t : set α} (ht : is_measurable t) : μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t := begin simp only [restrict_apply, ht, inter_Union], exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right) (λ i, ht.inter (hm i)) end lemma restrict_Union_apply_eq_supr [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) (hd : directed (⊆) s) {t : set α} (ht : is_measurable t) : μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t := begin simp only [restrict_apply ht, inter_Union], rw [measure_Union_eq_supr], exacts [λ i, ht.inter (hm i), hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)] end lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : (map f μ).restrict s = map f (μ.restrict $ f ⁻¹' s) := ext $ λ t ht, by simp [*, hf ht] lemma map_comap_subtype_coe (hs : is_measurable s) : (map (coe : s → α)).comp (comap coe) = restrictₗ s := linear_map.ext $ λ μ, ext $ λ t ht, by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply, map_apply measurable_subtype_coe ht, comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _ (measurable_subtype_coe ht), subtype.image_preimage_coe] /-- Restriction of a measure to a subset is monotone both in set and in measure. -/ @[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) : μ.restrict s ≤ ν.restrict s' := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs ... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s') ... = ν.restrict s' t : (restrict_apply ht).symm lemma restrict_le_self : μ.restrict s ≤ μ := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ t : measure_mono $ inter_subset_left t s lemma restrict_congr_meas (hs : is_measurable s) : μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, is_measurable t → μ t = ν t := ⟨λ H t hts ht, by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht], λ H, ext $ λ t ht, by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩ lemma restrict_congr_mono (hs : s ⊆ t) (hm : is_measurable s) (h : μ.restrict t = ν.restrict t) : μ.restrict s = ν.restrict s := by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm] /-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all measurable subsets of `s ∪ t`. -/ lemma restrict_union_congr (hsm : is_measurable s) (htm : is_measurable t) : μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔ μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t := begin refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h, restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩, simp only [restrict_congr_meas, hsm, htm, hsm.union htm], rintros ⟨hs, ht⟩ u hu hum, rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm, hs _ (inter_subset_right _ _) (hum.inter hsm), ht _ (diff_subset_iff.2 hu) (hum.diff hsm)] end lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α} (htm : ∀ i ∈ s, is_measurable (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin induction s using finset.induction_on with i s hi hs, { simp }, simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊢, simp only [finset.bUnion_insert, ← hs htm.2], exact restrict_union_congr htm.1 (s.is_measurable_bUnion htm.2) end lemma restrict_Union_congr [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) : μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := begin refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, λ h, _⟩, ext1 t ht, have M : ∀ t : finset ι, is_measurable (⋃ i ∈ t, s i) := λ t, t.is_measurable_bUnion (λ i _, hm i), have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) := directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht), rw [Union_eq_Union_finset], simp only [restrict_Union_apply_eq_supr M D ht, (restrict_finset_bUnion_congr (λ i hi, hm i)).2 (λ i hi, h i)], end lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : countable s) (htm : ∀ i ∈ s, is_measurable (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊢, haveI := hc.to_encodable, exact restrict_Union_congr htm end lemma restrict_sUnion_congr {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, is_measurable s) : μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm] /-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a restrict on measures and the RHS has a restrict on outer measures. -/ lemma restrict_to_outer_measure_eq_to_outer_measure_restrict (h : is_measurable s) : (μ.restrict s).to_outer_measure = outer_measure.restrict s μ.to_outer_measure := by simp_rw [restrict, restrictₗ, lift_linear, linear_map.coe_mk, to_measure_to_outer_measure, outer_measure.restrict_trim h, μ.trimmed] /-- This lemma shows that `Inf` and `restrict` commute for measures. -/ lemma restrict_Inf_eq_Inf_restrict {m : set (measure α)} (hm : m.nonempty) (ht : is_measurable t) : (Inf m).restrict t = Inf ((λ μ : measure α, μ.restrict t) '' m) := begin ext1 s hs, simp_rw [Inf_apply hs, restrict_apply hs, Inf_apply (is_measurable.inter hs ht), set.image_image, restrict_to_outer_measure_eq_to_outer_measure_restrict ht, ← set.image_image _ to_outer_measure, ← outer_measure.restrict_Inf_eq_Inf_restrict _ (hm.image _), outer_measure.restrict_apply] end /-! ### Extensionality results -/ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `Union`). -/ lemma ext_iff_of_Union_eq_univ [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) (hs : (⋃ i, s i) = univ) : μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `bUnion`). -/ lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : countable S) (hm : ∀ i ∈ S, is_measurable (s i)) (hs : (⋃ i ∈ S, s i) = univ) : μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `sUnion`). -/ lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, is_measurable s) (hs : (⋃₀ S) = univ) : μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ lemma ext_of_generate_from_of_cover {S T : set (set α)} (h_gen : ‹_› = generate_from S) (hc : countable T) (h_inter : is_pi_system S) (hm : ∀ t ∈ T, is_measurable t) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t < ⊤) (ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) : μ = ν := begin refine ext_of_sUnion_eq_univ hc hm hU (λ t ht, _), ext1 u hu, simp only [restrict_apply hu], refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu, { simp only [set.empty_inter, measure_empty] }, { intros v hv hvt, have := T_eq t ht, rw [set.inter_comm] at hvt ⊢, rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt, ennreal.add_right_inj] at this, exact (measure_mono $ set.inter_subset_left _ _).trans_lt (htop t ht) }, { intros f hfd hfm h_eq, have : pairwise (disjoint on λ n, f n ∩ t) := λ m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _), simp only [Union_inter, measure_Union this (λ n, is_measurable.inter (hfm n) (hm t ht)), h_eq] } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `sUnion`. -/ lemma ext_of_generate_from_of_cover_subset {S T : set (set α)} (h_gen : ‹_› = generate_from S) (h_inter : is_pi_system S) (h_sub : T ⊆ S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s < ⊤) (h_eq : ∀ s ∈ S, μ s = ν s) : μ = ν := begin refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (λ t ht, h_eq t (h_sub ht)), { intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) }, { intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H, { simp only [H, measure_empty] }, { exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `Union`. `finite_spanning_sets_in.ext` is a reformulation of this lemma. -/ lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α) (hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ) (h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) < ⊤) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := begin refine ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq, { rintro _ ⟨i, rfl⟩, apply h2B }, { rintro _ ⟨i, rfl⟩, apply hμB } end /-- The dirac measure. -/ def dirac (a : α) : measure α := (outer_measure.dirac a).to_measure (by simp) lemma dirac_apply' (a : α) (hs : is_measurable s) : dirac a s = ⨆ h : a ∈ s, 1 := to_measure_apply _ _ hs @[simp] lemma dirac_apply (a : α) (hs : is_measurable s) : dirac a s = s.indicator 1 a := (dirac_apply' a hs).trans $ by { by_cases h : a ∈ s; simp [h] } lemma dirac_apply_of_mem {a : α} (h : a ∈ s) : dirac a s = 1 := begin rw [measure_eq_infi, infi_subtype', infi_subtype'], convert infi_const, { ext1 ⟨⟨t, hst⟩, ht⟩, dsimp only [subtype.coe_mk] at *, simp only [dirac_apply _ ht, indicator_of_mem (hst h), pi.one_apply] }, { exact ⟨⟨⟨set.univ, subset_univ _⟩, is_measurable.univ⟩⟩ } end /-- Sum of an indexed family of measures. -/ def sum (f : ι → measure α) : measure α := (outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $ le_trans (by exact le_infi (λ i, le_to_outer_measure_caratheodory _)) (outer_measure.le_sum_caratheodory _) @[simp] lemma sum_apply (f : ι → measure α) {s : set α} (hs : is_measurable s) : sum f s = ∑' i, f i s := to_measure_apply _ _ hs lemma le_sum (μ : ι → measure α) (i : ι) : μ i ≤ sum μ := λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i] lemma restrict_Union [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, is_measurable (s i)) : μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) := ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht] lemma restrict_Union_le [encodable ι] {s : ι → set α} : μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) := begin intros t ht, suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union], apply measure_Union_le end @[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff := ext $ λ s hs, by simp [hs, tsum_fintype] @[simp] lemma sum_cond (μ ν : measure α) : sum (λ b, cond b μ ν) = μ + ν := sum_bool _ @[simp] lemma restrict_sum (μ : ι → measure α) {s : set α} (hs : is_measurable s) : (sum μ).restrict s = sum (λ i, (μ i).restrict s) := ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs] /-- Counting measure on any measurable space. -/ def count : measure α := sum dirac lemma count_apply (hs : is_measurable s) : count s = ∑' i : s, 1 := by simp only [count, sum_apply, hs, dirac_apply, ← tsum_subtype s 1, pi.one_apply] @[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) : count (↑s : set α) = s.card := calc count (↑s : set α) = ∑' i : (↑s : set α), (1 : α → ennreal) i : count_apply s.is_measurable ... = ∑ i in s, 1 : s.tsum_subtype 1 ... = s.card : by simp lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : finite s) : count s = hs.to_finset.card := by rw [← count_apply_finset, finite.coe_to_finset] /-- `count` measure evaluates to infinity at infinite sets. -/ lemma count_apply_infinite [measurable_singleton_class α] (hs : s.infinite) : count s = ⊤ := begin by_contra H, rcases ennreal.exists_nat_gt H with ⟨n, hn⟩, rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩, have := lt_of_le_of_lt (measure_mono ht) hn, simpa [lt_irrefl] using this end @[simp] lemma count_apply_eq_top [measurable_singleton_class α] : count s = ⊤ ↔ s.infinite := begin by_cases hs : s.finite, { simp [set.infinite, hs, count_apply_finite] }, { change s.infinite at hs, simp [hs, count_apply_infinite] } end @[simp] lemma count_apply_lt_top [measurable_singleton_class α] : count s < ⊤ ↔ s.finite := calc count s < ⊤ ↔ count s ≠ ⊤ : lt_top_iff_ne_top ... ↔ ¬s.infinite : not_congr count_apply_eq_top ... ↔ s.finite : not_not /-! ### The almost everywhere filter -/ /-- The “almost everywhere” filter of co-null sets. -/ def ae (μ : measure α) : filter α := { sets := {s | μ sᶜ = 0}, univ_sets := by simp, inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq]; exact measure_union_null hs ht, sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } /-- The filter of sets `s` such that `sᶜ` has finite measure. -/ def cofinite (μ : measure α) : filter α := { sets := {s | μ sᶜ < ⊤}, univ_sets := by simp, inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq], calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _ ... < ⊤ : ennreal.add_lt_top.2 ⟨hs, ht⟩ }, sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs } lemma mem_cofinite : s ∈ μ.cofinite ↔ μ sᶜ < ⊤ := iff.rfl lemma compl_mem_cofinite : sᶜ ∈ μ.cofinite ↔ μ s < ⊤ := by rw [mem_cofinite, compl_compl] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ⊤ := iff.rfl end measure open measure notation `∀ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl lemma compl_mem_ae_iff {s : set α} : sᶜ ∈ μ.ae ↔ μ s = 0 := by simp only [mem_ae_iff, compl_compl] lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s := compl_mem_ae_iff.symm @[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 := by rw [← empty_in_sets_eq_bot, mem_ae_iff, compl_empty, measure_univ_eq_zero] @[simp] lemma ae_zero : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀ a, p a) → ∀ᵐ a ∂ μ, p a := eventually_of_forall @[mono] lemma ae_mono {μ ν : measure α} (h : μ ≤ ν) : μ.ae ≤ ν.ae := λ s hs, bot_unique $ trans_rel_left (≤) (measure.le_iff'.1 h _) hs instance : countable_Inter_filter μ.ae := ⟨begin intros S hSc hS, simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢, haveI := hSc.to_encodable, exact measure_Union_null (subtype.forall.2 hS) end⟩ instance ae_is_measurably_generated : is_measurably_generated μ.ae := ⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_is_measurable_superset_of_null hs in ⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩ lemma ae_all_iff [encodable ι] {p : α → ι → Prop} : (∀ᵐ a ∂ μ, ∀ i, p a i) ↔ (∀ i, ∀ᵐ a ∂ μ, p a i) := eventually_countable_forall lemma ae_ball_iff {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} : (∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› := eventually_countable_ball hS lemma ae_eq_refl (f : α → δ) : f =ᵐ[μ] f := eventually_eq.refl _ _ lemma ae_eq_symm {f g : α → δ} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f := h.symm lemma ae_eq_trans {f g h: α → δ} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) : f =ᵐ[μ] h := h₁.trans h₂ lemma ae_eq_empty : s =ᵐ[μ] (∅ : set α) ↔ μ s = 0 := eventually_eq_empty.trans $ by simp [ae_iff] lemma ae_le_set : s ≤ᵐ[μ] t ↔ μ (s \ t) = 0 := calc s ≤ᵐ[μ] t ↔ ∀ᵐ x ∂μ, x ∈ s → x ∈ t : iff.rfl ... ↔ μ (s \ t) = 0 : by simp [ae_iff]; refl lemma union_ae_eq_right : (s ∪ t : set α) =ᵐ[μ] t ↔ μ (s \ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right, diff_eq_empty.2 (set.subset_union_right _ _)] lemma diff_ae_eq_self : (s \ t : set α) =ᵐ[μ] s ↔ μ (s ∩ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right, diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)] lemma ae_eq_set {s t : set α} : s =ᵐ[μ] t ↔ μ (s \ t) = 0 ∧ μ (t \ s) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set] lemma mem_ae_map_iff {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : s ∈ (map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae := by simp only [mem_ae_iff, map_apply hf hs.compl, preimage_compl] lemma ae_map_iff {f : α → β} (hf : measurable f) {p : β → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ y ∂ (map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) := mem_ae_map_iff hf hp lemma ae_restrict_iff {p : α → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply hp.compl], congr' with x, simp [and_comm] end lemma ae_imp_of_ae_restrict {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂(μ.restrict s), p x) : ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff] at h ⊢, simpa [set_of_and, inter_comm] using measure_inter_eq_zero_of_restrict h end lemma ae_restrict_iff' {s : set α} {p : α → Prop} (hp : is_measurable s) : (∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply_eq_zero' hp], congr' with x, simp [and_comm] end lemma ae_smul_measure {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) (c : ennreal) : ∀ᵐ x ∂(c • μ), p x := ae_iff.2 $ by rw [smul_apply, ae_iff.1 h, mul_zero] lemma ae_smul_measure_iff {p : α → Prop} {c : ennreal} (hc : c ≠ 0) : (∀ᵐ x ∂(c • μ), p x) ↔ ∀ᵐ x ∂μ, p x := by simp [ae_iff, hc] lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x := add_eq_zero_iff lemma ae_eq_comp {f : α → β} {g g' : β → δ} (hf : measurable f) (h : g =ᵐ[measure.map f μ] g') : g ∘ f =ᵐ[μ] g' ∘ f := begin rcases exists_is_measurable_superset_of_null h with ⟨t, ht, tmeas, tzero⟩, refine le_antisymm _ bot_le, calc μ {x | g (f x) ≠ g' (f x)} ≤ μ (f⁻¹' t) : measure_mono (λ x hx, ht hx) ... = 0 : by rwa ← measure.map_apply hf tmeas end lemma le_ae_restrict : μ.ae ⊓ 𝓟 s ≤ (μ.restrict s).ae := λ s hs, eventually_inf_principal.2 (ae_imp_of_ae_restrict hs) @[simp] lemma ae_restrict_eq (hs : is_measurable s) : (μ.restrict s).ae = μ.ae ⊓ 𝓟 s := begin ext t, simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_set_of, not_imp, and_comm (_ ∈ s)], refl end @[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 := ae_eq_bot.trans restrict_eq_zero @[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s := (not_congr ae_restrict_eq_bot).trans pos_iff_ne_zero.symm /-- A version of the Borel-Cantelli lemma: if sᵢ is a sequence of measurable sets such that ∑ μ sᵢ exists, then for almost all x, x does not belong to almost all sᵢ. -/ lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∀ i, is_measurable (s i)) (hs' : (∑' i, μ (s i)) ≠ ⊤) : ∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n := begin refine measure_mono_null _ (measure_limsup_eq_zero hs hs'), rw ←set.le_eq_subset, refine le_Inf (λ t ht x hx, _), simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq, eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht, rcases ht with ⟨i, hi⟩, rcases hx i with ⟨j, ⟨hj, hj'⟩⟩, exact hi j hj hj' end lemma mem_dirac_ae_iff {a : α} (hs : is_measurable s) : s ∈ (dirac a).ae ↔ a ∈ s := by by_cases a ∈ s; simp [mem_ae_iff, dirac_apply, hs.compl, indicator_apply, *] lemma eventually_dirac {a : α} {p : α → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ x ∂(dirac a), p x) ↔ p a := mem_dirac_ae_iff hp lemma eventually_eq_dirac [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) : f =ᵐ[dirac a] const α (f a) := (eventually_dirac $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl lemma dirac_ae_eq [measurable_singleton_class α] (a : α) : (dirac a).ae = pure a := begin ext s, simp only [mem_ae_iff, mem_pure_sets], by_cases ha : a ∈ s, { simp only [ha, iff_true], rw [← set.singleton_subset_iff, ← compl_subset_compl] at ha, refine measure_mono_null ha _, simp [dirac_apply a (is_measurable_singleton a).compl] }, { simp only [ha, iff_false, dirac_apply_of_mem (mem_compl ha)], exact one_ne_zero } end lemma eventually_eq_dirac' [measurable_singleton_class α] {a : α} (f : α → δ) : f =ᵐ[dirac a] const α (f a) := by { rw [dirac_ae_eq], show f a = f a, refl } /-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/ lemma measure_mono_ae (H : s ≤ᵐ[μ] t) : μ s ≤ μ t := calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t ... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm] ... ≤ μ t + μ (s \ t) : measure_union_le _ _ ... = μ t : by rw [ae_le_set.1 H, add_zero] alias measure_mono_ae ← filter.eventually_le.measure_le /-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/ lemma measure_congr (H : s =ᵐ[μ] t) : μ s = μ t := le_antisymm H.le.measure_le H.symm.le.measure_le lemma restrict_mono_ae (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t := begin intros u hu, simp only [restrict_apply hu], exact measure_mono_ae (h.mono $ λ x hx, and.imp id hx) end lemma restrict_congr_set (H : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t := le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le) /-- A measure `μ` is called a probability measure if `μ univ = 1`. -/ class probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1) instance measure.dirac.probability_measure {x : α} : probability_measure (dirac x) := ⟨dirac_apply_of_mem $ mem_univ x⟩ /-- A measure `μ` is called finite if `μ univ < ⊤`. -/ class finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ⊤) instance restrict.finite_measure (μ : measure α) [hs : fact (μ s < ⊤)] : finite_measure (μ.restrict s) := ⟨by simp [hs.elim]⟩ /-- Measure `μ` *has no atoms* if the measure of each singleton is zero. NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure, there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`, the converse is not true. -/ class has_no_atoms (μ : measure α) : Prop := (measure_singleton : ∀ x, μ {x} = 0) export probability_measure (measure_univ) has_no_atoms (measure_singleton) attribute [simp] measure_singleton lemma measure_lt_top (μ : measure α) [finite_measure μ] (s : set α) : μ s < ⊤ := (measure_mono (subset_univ s)).trans_lt finite_measure.measure_univ_lt_top lemma measure_ne_top (μ : measure α) [finite_measure μ] (s : set α) : μ s ≠ ⊤ := ne_of_lt (measure_lt_top μ s) /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds for measures with the additional assumption that μ is finite. -/ lemma measure.le_of_add_le_add_left {μ ν₁ ν₂ : measure α} [finite_measure μ] (A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ := λ S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_lt_top μ S) (A2 S B1) @[priority 100] instance probability_measure.to_finite_measure (μ : measure α) [probability_measure μ] : finite_measure μ := ⟨by simp only [measure_univ, ennreal.one_lt_top]⟩ lemma probability_measure.ne_zero (μ : measure α) [probability_measure μ] : μ ≠ 0 := mt measure_univ_eq_zero.2 $ by simp [measure_univ] section no_atoms variables [has_no_atoms μ] lemma measure_countable (h : countable s) : μ s = 0 := begin rw [← bUnion_of_singleton s, ← nonpos_iff_eq_zero], refine le_trans (measure_bUnion_le h _) _, simp end lemma measure_finite (h : s.finite) : μ s = 0 := measure_countable h.countable lemma measure_finset (s : finset α) : μ ↑s = 0 := measure_finite s.finite_to_set lemma insert_ae_eq_self (a : α) (s : set α) : (insert a s : set α) =ᵐ[μ] s := union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _) variables [partial_order α] {a b : α} lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a := by simp only [← Iic_diff_right, diff_ae_eq_self, measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)] lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a := @Iio_ae_eq_Iic (order_dual α) ‹_› ‹_› _ _ _ lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b := Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc end no_atoms namespace measure /-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`. Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/ def finite_at_filter (μ : measure α) (f : filter α) : Prop := ∃ s ∈ f, μ s < ⊤ lemma finite_at_filter_of_finite (μ : measure α) [finite_measure μ] (f : filter α) : μ.finite_at_filter f := ⟨univ, univ_mem_sets, measure_lt_top μ univ⟩ lemma finite_at_filter.exists_mem_basis {μ : measure α} {f : filter α} (hμ : finite_at_filter μ f) {p : ι → Prop} {s : ι → set α} (hf : f.has_basis p s) : ∃ i (hi : p i), μ (s i) < ⊤ := (hf.exists_iff (λ s t hst ht, (measure_mono hst).trans_lt ht)).1 hμ lemma finite_at_bot (μ : measure α) : μ.finite_at_filter ⊥ := ⟨∅, mem_bot_sets, by simp only [measure_empty, with_top.zero_lt_top]⟩ /-- `μ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have finite measures. This structure is a type, which is useful if we want to record extra properties about the sets, such as that they are monotone. `sigma_finite` is defined in terms of this: `μ` is σ-finite if there exists a sequence of finite spanning sets in the collection of all measurable sets. -/ @[protect_proj, nolint has_inhabited_instance] structure finite_spanning_sets_in (μ : measure α) (C : set (set α)) := (set : ℕ → set α) (set_mem : ∀ i, set i ∈ C) (finite : ∀ i, μ (set i) < ⊤) (spanning : (⋃ i, set i) = univ) end measure open measure /-- A measure `μ` is called σ-finite if there is a countable collection of sets `{ A i | i ∈ ℕ }` such that `μ (A i) < ⊤` and `⋃ i, A i = s`. -/ @[class] def sigma_finite (μ : measure α) : Prop := nonempty (μ.finite_spanning_sets_in {s | is_measurable s}) /-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/ def measure.to_finite_spanning_sets_in (μ : measure α) [h : sigma_finite μ] : μ.finite_spanning_sets_in {s | is_measurable s} := classical.choice h /-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite measure using `classical.some`. This definition satisfies monotonicity in addition to all other properties in `sigma_finite`. -/ def spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : set α := accumulate μ.to_finite_spanning_sets_in.set i lemma monotone_spanning_sets (μ : measure α) [sigma_finite μ] : monotone (spanning_sets μ) := monotone_accumulate lemma is_measurable_spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : is_measurable (spanning_sets μ i) := is_measurable.Union $ λ j, is_measurable.Union_Prop $ λ hij, μ.to_finite_spanning_sets_in.set_mem j lemma measure_spanning_sets_lt_top (μ : measure α) [sigma_finite μ] (i : ℕ) : μ (spanning_sets μ i) < ⊤ := measure_bUnion_lt_top (finite_le_nat i) $ λ j _, μ.to_finite_spanning_sets_in.finite j lemma Union_spanning_sets (μ : measure α) [sigma_finite μ] : (⋃ i : ℕ, spanning_sets μ i) = univ := by simp_rw [spanning_sets, Union_accumulate, μ.to_finite_spanning_sets_in.spanning] lemma is_countably_spanning_spanning_sets (μ : measure α) [sigma_finite μ] : is_countably_spanning (range (spanning_sets μ)) := ⟨spanning_sets μ, mem_range_self, Union_spanning_sets μ⟩ namespace measure lemma supr_restrict_spanning_sets [sigma_finite μ] (hs : is_measurable s) : (⨆ i, μ.restrict (spanning_sets μ i) s) = μ s := begin convert (restrict_Union_apply_eq_supr (is_measurable_spanning_sets μ) _ hs).symm, { simp [Union_spanning_sets] }, { exact directed_of_sup (monotone_spanning_sets μ) } end namespace finite_spanning_sets_in variables {C D : set (set α)} /-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/ protected def mono (h : μ.finite_spanning_sets_in C) (hC : C ⊆ D) : μ.finite_spanning_sets_in D := ⟨h.set, λ i, hC (h.set_mem i), h.finite, h.spanning⟩ /-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite. -/ protected lemma sigma_finite (h : μ.finite_spanning_sets_in C) (hC : ∀ s ∈ C, is_measurable s) : sigma_finite μ := ⟨h.mono hC⟩ /-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of `finite_spanning_sets_in`. -/ protected lemma ext {ν : measure α} {C : set (set α)} (hA : ‹_› = generate_from C) (hC : is_pi_system C) (h : μ.finite_spanning_sets_in C) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := ext_of_generate_from_of_Union C _ hA hC h.spanning h.set_mem h.finite h_eq protected lemma is_countably_spanning (h : μ.finite_spanning_sets_in C) : is_countably_spanning C := ⟨_, h.set_mem, h.spanning⟩ end finite_spanning_sets_in lemma sigma_finite_of_not_nonempty (μ : measure α) (hα : ¬ nonempty α) : sigma_finite μ := ⟨⟨λ _, ∅, λ n, is_measurable.empty, λ n, by simp, by simp [eq_empty_of_not_nonempty hα univ]⟩⟩ lemma sigma_finite_of_countable {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, is_measurable s) (hμ : ∀ s ∈ S, μ s < ⊤) (hU : ⋃₀ S = univ) : sigma_finite μ := begin by_cases hα : nonempty α, { resetI, have : S.nonempty, { clear hc, -- otherwise `rintro rfl` fails. TODO: why? rw ← ne_empty_iff_nonempty, rintro rfl, simpa [eq_comm] using hU }, rcases (countable_iff_exists_surjective_to_subtype this).1 hc with ⟨s, hs⟩, refine ⟨⟨λ n, s n, λ n, hm _ (s n).coe_prop, λ n, hμ _ (s n).coe_prop, _⟩⟩, rw [Union, hs.supr_comp, ← hU, sUnion_eq_Union] }, { exact sigma_finite_of_not_nonempty μ hα } end end measure /-- Every finite measure is σ-finite. -/ @[priority 100] instance finite_measure.to_sigma_finite (μ : measure α) [finite_measure μ] : sigma_finite μ := ⟨⟨λ _, univ, λ _, is_measurable.univ, λ _, measure_lt_top μ _, Union_const _⟩⟩ instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) : sigma_finite (μ.restrict s) := begin refine ⟨⟨spanning_sets μ, is_measurable_spanning_sets μ, λ i, _, Union_spanning_sets μ⟩⟩, rw [restrict_apply (is_measurable_spanning_sets μ i)], exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top μ i) end instance sum.sigma_finite {ι} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : sigma_finite (sum μ) := begin haveI : encodable ι := (encodable.trunc_encodable_of_fintype ι).out, have : ∀ n, is_measurable (⋂ (i : ι), spanning_sets (μ i) n) := λ n, is_measurable.Inter (λ i, is_measurable_spanning_sets (μ i) n), refine ⟨⟨λ n, ⋂ i, spanning_sets (μ i) n, this, λ n, _, _⟩⟩, { rw [sum_apply _ (this n), tsum_fintype, ennreal.sum_lt_top_iff], rintro i -, exact (measure_mono $ Inter_subset _ i).trans_lt (measure_spanning_sets_lt_top (μ i) n) }, { rw [Union_Inter_of_monotone], simp_rw [Union_spanning_sets, Inter_univ], exact λ i, monotone_spanning_sets (μ i), } end instance add.sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] : sigma_finite (μ + ν) := by { rw [← sum_cond], refine @sum.sigma_finite _ _ _ _ _ (bool.rec _ _); simpa } /-- A measure is called locally finite if it is finite in some neighborhood of each point. -/ class locally_finite_measure [topological_space α] (μ : measure α) : Prop := (finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x)) @[priority 100] instance finite_measure.to_locally_finite_measure [topological_space α] (μ : measure α) [finite_measure μ] : locally_finite_measure μ := ⟨λ x, finite_at_filter_of_finite _ _⟩ lemma measure.finite_at_nhds [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) : μ.finite_at_filter (𝓝 x) := locally_finite_measure.finite_at_nhds x lemma measure.exists_is_open_measure_lt_top [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) : ∃ s : set α, x ∈ s ∧ is_open s ∧ μ s < ⊤ := by simpa only [exists_prop, and.assoc] using (μ.finite_at_nhds x).exists_mem_basis (nhds_basis_opens x) /-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra (and `univ`). -/ lemma ext_of_generate_finite (C : set (set α)) (hA : _inst_1 = generate_from C) (hC : is_pi_system C) {μ ν : measure α} [finite_measure μ] [finite_measure ν] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) : μ = ν := begin ext1 s hs, refine induction_on_inter hA hC (by simp) hμν _ _ hs, { rintros t h1t h2t, change is_measurable t at h1t, simp [measure_compl, measure_lt_top, *] }, { rintros f h1f h2f h3f, simp [measure_Union, is_measurable.Union, *] } end namespace measure namespace finite_at_filter variables {f g : filter α} lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f := λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩ lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_left lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_right @[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hμ⟩, suffices : μ t ≤ μ s, from ⟨t, ht, this.trans_lt hμ⟩, exact measure_mono_ae (mem_sets_of_superset hu (λ x hu ht, hs ⟨ht, hu⟩)) end alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _ lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f := inf_ae_iff.1 (hg.filter_mono h) protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f := λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩ @[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) : ν.finite_at_filter g → μ.finite_at_filter f := λ h, (h.filter_mono hf).measure_mono hμ protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.lift' powerset, μ s < ⊤ := (eventually_lift'_powerset' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) := λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩, ⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩ end finite_at_filter lemma finite_at_nhds_within [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) (s : set α) : μ.finite_at_filter (𝓝[s] x) := (finite_at_nhds μ x).inf_of_left @[simp] lemma finite_at_principal : μ.finite_at_filter (𝓟 s) ↔ μ s < ⊤ := ⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩ /-! ### Subtraction of measures -/ /-- The measure `μ - ν` is defined to be the least measure `τ` such that `μ ≤ τ + ν`. It is the equivalent of `(μ - ν) ⊔ 0` if `μ` and `ν` were signed measures. Compare with `ennreal.has_sub`. Specifically, note that if you have `α = {1,2}`, and `μ {1} = 2`, `μ {2} = 0`, and `ν {2} = 2`, `ν {1} = 0`, then `(μ - ν) {1, 2} = 2`. However, if `μ ≤ ν`, and `ν univ ≠ ⊤`, then `(μ - ν) + ν = μ`. -/ noncomputable instance has_sub {α : Type*} [measurable_space α] : has_sub (measure α) := ⟨λ μ ν, Inf {τ | μ ≤ τ + ν} ⟩ section measure_sub lemma sub_def : μ - ν = Inf {d | μ ≤ d + ν} := rfl lemma sub_eq_zero_of_le (h : μ ≤ ν) : μ - ν = 0 := begin rw [← nonpos_iff_eq_zero', measure.sub_def], apply @Inf_le (measure α) _ _, simp [h], end /-- This application lemma only works in special circumstances. Given knowledge of when `μ ≤ ν` and `ν ≤ μ`, a more general application lemma can be written. -/ lemma sub_apply [finite_measure ν] (h₁ : is_measurable s) (h₂ : ν ≤ μ) : (μ - ν) s = μ s - ν s := begin -- We begin by defining `measure_sub`, which will be equal to `(μ - ν)`. let measure_sub : measure α := @measure_theory.measure.of_measurable α _ (λ (t : set α) (h_t_is_measurable : is_measurable t), (μ t - ν t)) begin simp end begin intros g h_meas h_disj, simp only, rw ennreal.tsum_sub, repeat { rw ← measure_theory.measure_Union h_disj h_meas }, apply measure_theory.measure_lt_top, intro i, apply h₂, apply h_meas end, -- Now, we demonstrate `μ - ν = measure_sub`, and apply it. begin have h_measure_sub_add : (ν + measure_sub = μ), { ext t h_t_is_measurable, simp only [pi.add_apply, coe_add], rw [measure_theory.measure.of_measurable_apply _ h_t_is_measurable, add_comm, ennreal.sub_add_cancel_of_le (h₂ t h_t_is_measurable)] }, have h_measure_sub_eq : (μ - ν) = measure_sub, { rw measure_theory.measure.sub_def, apply le_antisymm, { apply @Inf_le (measure α) (measure.complete_lattice), simp [le_refl, add_comm, h_measure_sub_add] }, apply @le_Inf (measure α) (measure.complete_lattice), intros d h_d, rw [← h_measure_sub_add, mem_set_of_eq, add_comm d] at h_d, apply measure.le_of_add_le_add_left h_d }, rw h_measure_sub_eq, apply measure.of_measurable_apply _ h₁, end end lemma sub_add_cancel_of_le [finite_measure ν] (h₁ : ν ≤ μ) : μ - ν + ν = μ := begin ext s h_s_meas, rw [add_apply, sub_apply h_s_meas h₁, ennreal.sub_add_cancel_of_le (h₁ s h_s_meas)], end end measure_sub end measure end measure_theory open measure_theory measure_theory.measure namespace measurable_equiv open equiv variables [measurable_space α] [measurable_space β] {μ : measure α} {ν : measure β} /-- If we map a measure along a measurable equivalence, we can compute the measure on all sets (not just the measurable ones). -/ protected theorem map_apply (f : α ≃ᵐ β) (s : set β) : measure.map f μ s = μ (f ⁻¹' s) := begin refine le_antisymm _ (le_map_apply f.measurable s), rw [measure_eq_infi' μ], refine le_infi _, rintro ⟨t, hst, ht⟩, rw [subtype.coe_mk], have := f.symm.to_equiv.image_eq_preimage, simp only [←coe_eq, symm_symm, symm_to_equiv] at this, rw [← this, image_subset_iff] at hst, convert measure_mono hst, rw [map_apply, preimage_preimage], { refine congr_arg μ (eq.symm _), convert preimage_id, exact funext f.left_inv }, exacts [f.measurable, f.measurable_inv_fun ht] end end measurable_equiv section is_complete /-- A measure is complete if every null set is also measurable. A null set is a subset of a measurable set with measure `0`. Since every measure is defined as a special case of an outer measure, we can more simply state that a set `s` is null if `μ s = 0`. -/ @[class] def measure_theory.measure.is_complete {_ : measurable_space α} (μ : measure α) : Prop := ∀ s, μ s = 0 → is_measurable s variables [measurable_space α] {μ : measure α} {s t z : set α} /-- A set is null measurable if it is the union of a null set and a measurable set. -/ def is_null_measurable (μ : measure α) (s : set α) : Prop := ∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0 theorem is_null_measurable_iff : is_null_measurable μ s ↔ ∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 := begin split, { rintro ⟨t, z, rfl, ht, hz⟩, refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩, simp [union_diff_left, diff_subset] }, { rintro ⟨t, st, ht, hz⟩, exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ } end theorem is_null_measurable_measure_eq (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t := begin refine le_antisymm _ (measure_mono st), have := measure_union_le t (s \ t), rw [union_diff_cancel st, hz] at this, simpa end theorem is_measurable.is_null_measurable (μ : measure α) (hs : is_measurable s) : is_null_measurable μ s := ⟨s, ∅, by simp, hs, μ.empty⟩ theorem is_null_measurable_of_complete (μ : measure α) [c : μ.is_complete] : is_null_measurable μ s ↔ is_measurable s := ⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact is_measurable.union ht (c _ hz), λ h, h.is_null_measurable _⟩ theorem is_null_measurable.union_null (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s ∪ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩ end theorem null_is_null_measurable (hz : μ z = 0) : is_null_measurable μ z := by simpa using (is_measurable.empty.is_null_measurable _).union_null hz theorem is_null_measurable.Union_nat {s : ℕ → set α} (hs : ∀ i, is_null_measurable μ (s i)) : is_null_measurable μ (Union s) := begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, refine is_null_measurable_iff.2 ⟨Union t, Union_subset_Union st, is_measurable.Union ht, measure_mono_null _ (measure_Union_null hz)⟩, rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) end theorem is_measurable.diff_null (hs : is_measurable s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rw measure_eq_infi at hz, choose f hf using show ∀ q : {q : ℚ // q > 0}, ∃ t : set α, z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal), { rintro ⟨ε, ε0⟩, have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 }, rw ← hz at this, simpa [infi_lt_iff] }, refine is_null_measurable_iff.2 ⟨s \ Inter f, diff_subset_diff_right (subset_Inter (λ i, (hf i).1)), hs.diff (is_measurable.Inter (λ i, (hf i).2.1)), measure_mono_null _ (nonpos_iff_eq_zero.1 $ le_of_not_lt $ λ h, _)⟩, { exact Inter f }, { rw [diff_subset_iff, diff_union_self], exact subset.trans (diff_subset _ _) (subset_union_left _ _) }, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩, simp at ε0, apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h), exact measure_mono (Inter_subset _ _) end theorem is_null_measurable.diff_null (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, rw [set.union_diff_distrib], exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz') end theorem is_null_measurable.compl (hs : is_null_measurable μ s) : is_null_measurable μ sᶜ := begin rcases hs with ⟨t, z, rfl, ht, hz⟩, rw compl_union, exact ht.compl.diff_null hz end theorem is_null_measurable_iff_ae {s : set α} : is_null_measurable μ s ↔ ∃ t, is_measurable t ∧ s =ᵐ[μ] t := begin simp only [ae_eq_set], split, { assume h, rcases is_null_measurable_iff.1 h with ⟨t, ts, tmeas, ht⟩, refine ⟨t, tmeas, ht, _⟩, rw [diff_eq_empty.2 ts, measure_empty] }, { rintros ⟨t, tmeas, h₁, h₂⟩, have : is_null_measurable μ (t ∪ (s \ t)) := is_null_measurable.union_null (tmeas.is_null_measurable _) h₁, have A : is_null_measurable μ ((t ∪ (s \ t)) \ (t \ s)) := is_null_measurable.diff_null this h₂, have : (t ∪ (s \ t)) \ (t \ s) = s, { apply subset.antisymm, { assume x hx, simp only [mem_union_eq, not_and, mem_diff, not_not_mem] at hx, cases hx.1, { exact hx.2 h }, { exact h.1 } }, { assume x hx, simp [hx, classical.em (x ∈ t)] } }, rwa this at A } end theorem is_null_measurable_iff_sandwich {s : set α} : is_null_measurable μ s ↔ ∃ (t u : set α), is_measurable t ∧ is_measurable u ∧ t ⊆ s ∧ s ⊆ u ∧ μ (u \ t) = 0 := begin split, { assume h, rcases is_null_measurable_iff.1 h with ⟨t, ts, tmeas, ht⟩, rcases is_null_measurable_iff.1 h.compl with ⟨u', u's, u'meas, hu'⟩, have A : s ⊆ u'ᶜ := subset_compl_comm.mp u's, refine ⟨t, u'ᶜ, tmeas, u'meas.compl, ts, A, _⟩, have : sᶜ \ u' = u'ᶜ \ s, by simp [compl_eq_univ_diff, diff_diff, union_comm], rw this at hu', apply le_antisymm _ bot_le, calc μ (u'ᶜ \ t) ≤ μ ((u'ᶜ \ s) ∪ (s \ t)) : begin apply measure_mono, assume x hx, simp at hx, simp [hx, or_comm, classical.em], end ... ≤ μ (u'ᶜ \ s) + μ (s \ t) : measure_union_le _ _ ... = 0 : by rw [ht, hu', zero_add] }, { rintros ⟨t, u, tmeas, umeas, ts, su, hμ⟩, refine is_null_measurable_iff.2 ⟨t, ts, tmeas, _⟩, apply le_antisymm _ bot_le, calc μ (s \ t) ≤ μ (u \ t) : measure_mono (diff_subset_diff_left su) ... = 0 : hμ } end lemma restrict_apply_of_is_null_measurable {s t : set α} (ht : is_null_measurable (μ.restrict s) t) : μ.restrict s t = μ (t ∩ s) := begin rcases is_null_measurable_iff_sandwich.1 ht with ⟨u, v, umeas, vmeas, ut, tv, huv⟩, apply le_antisymm _ (le_restrict_apply _ _), calc μ.restrict s t ≤ μ.restrict s v : measure_mono tv ... = μ (v ∩ s) : restrict_apply vmeas ... ≤ μ ((u ∩ s) ∪ ((v \ u) ∩ s)) : measure_mono $ by { assume x hx, simp at hx, simp [hx, classical.em] } ... ≤ μ (u ∩ s) + μ ((v \ u) ∩ s) : measure_union_le _ _ ... = μ (u ∩ s) + μ.restrict s (v \ u) : by rw measure.restrict_apply (vmeas.diff umeas) ... = μ (u ∩ s) : by rw [huv, add_zero] ... ≤ μ (t ∩ s) : measure_mono $ inter_subset_inter_left s ut end /-- The measurable space of all null measurable sets. -/ def null_measurable (μ : measure α) : measurable_space α := { is_measurable' := is_null_measurable μ, is_measurable_empty := is_measurable.empty.is_null_measurable _, is_measurable_compl := λ s hs, hs.compl, is_measurable_Union := λ f, is_null_measurable.Union_nat } /-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/ def completion (μ : measure α) : @measure_theory.measure α (null_measurable μ) := { to_outer_measure := μ.to_outer_measure, m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, rw is_null_measurable_measure_eq (Union_subset_Union st), { rw measure_Union _ ht, { congr, funext i, exact (is_null_measurable_measure_eq (st i) (hz i)).symm }, { rintro i j ij x ⟨h₁, h₂⟩, exact hd i j ij ⟨st i h₁, st j h₂⟩ } }, { refine measure_mono_null _ (measure_Union_null hz), rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) } end, trimmed := begin letI := null_measurable μ, refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, dsimp, clear _inst, resetI, rw measure_eq_infi s, exact infi_le_infi (λ t, infi_le_infi $ λ st, infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩) end } instance completion.is_complete (μ : measure α) : (completion μ).is_complete := λ z hz, null_is_null_measurable hz lemma measurable.ae_eq {α β} [measurable_space α] [measurable_space β] {μ : measure α} [hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) : measurable g := begin intros s hs, let t := {x | f x = g x}, have ht_compl : μ tᶜ = 0, by rwa [filter.eventually_eq, ae_iff] at hfg, rw (set.inter_union_compl (g ⁻¹' s) t).symm, refine is_measurable.union _ _, { have h_g_to_f : (g ⁻¹' s) ∩ t = (f ⁻¹' s) ∩ t, { ext, simp only [set.mem_inter_iff, set.mem_preimage, and.congr_left_iff, set.mem_set_of_eq], exact λ hx, by rw hx, }, rw h_g_to_f, exact is_measurable.inter (hf hs) (is_measurable.compl_iff.mp (hμ tᶜ ht_compl)), }, { exact hμ (g ⁻¹' s ∩ tᶜ) (measure_mono_null (set.inter_subset_right _ _) ht_compl), }, end end is_complete namespace measure_theory /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (α : Type*) extends measurable_space α := (volume : measure α) export measure_space (volume) /-- `volume` is the canonical measure on `α`. -/ add_decl_doc volume section measure_space variables [measure_space α] {s₁ s₂ : set α} notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r /-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/ meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume] end measure_space end measure_theory /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. We define this property, called `ae_measurable f μ`, and discuss several of its properties that are analogous to properties of measurable functions. -/ section open measure_theory variables [measurable_space α] [measurable_space β] {f g : α → β} {μ ν : measure α} /-- A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. -/ def ae_measurable (f : α → β) (μ : measure α . measure_theory.volume_tac) : Prop := ∃ g : α → β, measurable g ∧ f =ᵐ[μ] g lemma measurable.ae_measurable (h : measurable f) : ae_measurable f μ := ⟨f, h, ae_eq_refl f⟩ @[nontriviality] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ := subsingleton.measurable.ae_measurable @[simp] lemma ae_measurable_zero : ae_measurable f 0 := begin nontriviality α, inhabit α, exact ⟨λ x, f (default α), measurable_const, rfl⟩ end lemma ae_measurable_iff_measurable [μ.is_complete] : ae_measurable f μ ↔ measurable f := begin split; intro h, { rcases h with ⟨g, hg_meas, hfg⟩, exact hg_meas.ae_eq hfg.symm, }, { exact h.ae_measurable, }, end namespace ae_measurable /-- Given an almost everywhere measurable function `f`, associate to it a measurable function that coincides with it almost everywhere. `f` is explicit in the definition to make sure that it shows in pretty-printing. -/ def mk (f : α → β) (h : ae_measurable f μ) : α → β := classical.some h lemma measurable_mk (h : ae_measurable f μ) : measurable (h.mk f) := (classical.some_spec h).1 lemma ae_eq_mk (h : ae_measurable f μ) : f =ᵐ[μ] (h.mk f) := (classical.some_spec h).2 lemma congr (hf : ae_measurable f μ) (h : f =ᵐ[μ] g) : ae_measurable g μ := ⟨hf.mk f, hf.measurable_mk, h.symm.trans hf.ae_eq_mk⟩ lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) : ae_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f := le_ae_restrict h.ae_eq_mk lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) : ae_measurable f (μ + ν) := begin let s := {x | f x ≠ hμ.mk f x}, have : μ s = 0 := hμ.ae_eq_mk, obtain ⟨t, st, t_meas, μt⟩ : ∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 := exists_is_measurable_superset_of_null this, let g : α → β := t.piecewise (hν.mk f) (hμ.mk f), refine ⟨g, measurable.piecewise t_meas hν.measurable_mk hμ.measurable_mk, _⟩, change μ {x | f x ≠ g x} + ν {x | f x ≠ g x} = 0, suffices : μ {x | f x ≠ g x} = 0 ∧ ν {x | f x ≠ g x} = 0, by simp [this.1, this.2], have ht : {x | f x ≠ g x} ⊆ t, { assume x hx, by_contra h, simp only [g, h, mem_set_of_eq, ne.def, not_false_iff, piecewise_eq_of_not_mem] at hx, exact h (st hx) }, split, { have : μ {x | f x ≠ g x} ≤ μ t := measure_mono ht, rw μt at this, exact le_antisymm this bot_le }, { have : {x | f x ≠ g x} ⊆ {x | f x ≠ hν.mk f x}, { assume x hx, simpa [ht hx, g] using hx }, apply le_antisymm _ bot_le, calc ν {x | f x ≠ g x} ≤ ν {x | f x ≠ hν.mk f x} : measure_mono this ... = 0 : hν.ae_eq_mk } end lemma smul_measure (h : ae_measurable f μ) (c : ennreal) : ae_measurable f (c • μ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_measurable [measurable_space δ] {f : α → δ} {g : δ → β} (hg : ae_measurable g (measure.map f μ)) (hf : measurable f) : ae_measurable (g ∘ f) μ := ⟨(hg.mk g) ∘ f, hg.measurable_mk.comp hf, ae_eq_comp hf hg.ae_eq_mk⟩ lemma prod_mk {γ : Type*} [measurable_space γ] {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ := ⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk, eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩ lemma is_null_measurable (h : ae_measurable f μ) {s : set β} (hs : is_measurable s) : is_null_measurable μ (f ⁻¹' s) := begin apply is_null_measurable_iff_ae.2, refine ⟨(h.mk f) ⁻¹' s, h.measurable_mk hs, _⟩, filter_upwards [h.ae_eq_mk], assume x hx, change (f x ∈ s) = ((h.mk f) x ∈ s), rwa hx end end ae_measurable lemma ae_measurable_congr (h : f =ᵐ[μ] g) : ae_measurable f μ ↔ ae_measurable g μ := ⟨λ hf, ae_measurable.congr hf h, λ hg, ae_measurable.congr hg h.symm⟩ @[simp] lemma ae_measurable_add_measure_iff : ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ @[simp] lemma ae_measurable_const {b : β} : ae_measurable (λ a : α, b) μ := measurable_const.ae_measurable @[simp] lemma ae_measurable_smul_measure_iff {c : ennreal} (hc : c ≠ 0) : ae_measurable f (c • μ) ↔ ae_measurable f μ := ⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩, λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩ lemma measurable.comp_ae_measurable [measurable_space δ] {f : α → δ} {g : δ → β} (hg : measurable g) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨g ∘ hf.mk f, hg.comp hf.measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk _⟩ end namespace is_compact variables [topological_space α] [measurable_space α] {μ : measure α} {s : set α} lemma finite_measure_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, μ.finite_at_filter (𝓝[s] a)) → μ s < ⊤ := by simpa only [← measure.compl_mem_cofinite, measure.finite_at_filter] using hs.compl_mem_sets_of_nhds_within lemma finite_measure [locally_finite_measure μ] (hs : is_compact s) : μ s < ⊤ := hs.finite_measure_of_nhds_within $ λ a ha, μ.finite_at_nhds_within _ _ lemma measure_zero_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 := by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within end is_compact lemma metric.bounded.finite_measure [metric_space α] [proper_space α] [measurable_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : metric.bounded s) : μ s < ⊤ := (measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2 ⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).finite_measure
c983f8ac38267166e9c462069153fa8b533a81c1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/CommRing/colimits_auto.lean
ecc5e7ca065fa89c15bbb402de6561300c11dcf3
[]
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
12,836
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.algebra.category.CommRing.basic import Mathlib.category_theory.limits.limits import Mathlib.category_theory.limits.concrete_category import Mathlib.PostPort universes v l u_1 namespace Mathlib /-! # The category of commutative rings has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `comm_ring` and `ring_hom`. -/ -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. /- `#print comm_ring` says: structure comm_ring : Type u → Type u fields: comm_ring.zero : Π (α : Type u) [c : comm_ring α], α comm_ring.one : Π (α : Type u) [c : comm_ring α], α comm_ring.neg : Π {α : Type u} [c : comm_ring α], α → α comm_ring.add : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.mul : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.zero_add : ∀ {α : Type u} [c : comm_ring α] (a : α), 0 + a = a comm_ring.add_zero : ∀ {α : Type u} [c : comm_ring α] (a : α), a + 0 = a comm_ring.one_mul : ∀ {α : Type u} [c : comm_ring α] (a : α), 1 * a = a comm_ring.mul_one : ∀ {α : Type u} [c : comm_ring α] (a : α), a * 1 = a comm_ring.add_left_neg : ∀ {α : Type u} [c : comm_ring α] (a : α), -a + a = 0 comm_ring.add_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a + b = b + a comm_ring.mul_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a * b = b * a comm_ring.add_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a + b + c_1 = a + (b + c_1) comm_ring.mul_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) comm_ring.left_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * (b + c_1) = a * b + a * c_1 comm_ring.right_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), (a + b) * c_1 = a * c_1 + b * c_1 -/ namespace CommRing.colimits /-! We build the colimit of a diagram in `CommRing` by constructing the free commutative ring on the disjoint union of all the commutative rings in the diagram, then taking the quotient by the commutative ring laws within each commutative ring, and the identifications given by the morphisms in the diagram. -/ /-- An inductive type representing all commutative ring expressions (without relations) on a collection of types indexed by the objects of `J`. -/ -- There's always `of` inductive prequotient {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) where | of : (j : J) → ↥(category_theory.functor.obj F j) → prequotient F | zero : prequotient F | one : prequotient F | neg : prequotient F → prequotient F | add : prequotient F → prequotient F → prequotient F | mul : prequotient F → prequotient F → prequotient F -- Then one generator for each operation protected instance prequotient.inhabited {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : Inhabited (prequotient F) := { default := prequotient.zero } /-- The relation on `prequotient` saying when two expressions are equal because of the commutative ring laws, or because one element is mapped to another by a morphism in the diagram. -/ -- Make it an equivalence relation: inductive relation {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : prequotient F → prequotient F → Prop where | refl : ∀ (x : prequotient F), relation F x x | symm : ∀ (x y : prequotient F), relation F x y → relation F y x | trans : ∀ (x y z : prequotient F), relation F x y → relation F y z → relation F x z | map : ∀ (j j' : J) (f : j ⟶ j') (x : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j' (coe_fn (category_theory.functor.map F f) x)) (prequotient.of j x) | zero : ∀ (j : J), relation F (prequotient.of j 0) prequotient.zero | one : ∀ (j : J), relation F (prequotient.of j 1) prequotient.one | neg : ∀ (j : J) (x : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j (-x)) (prequotient.neg (prequotient.of j x)) | add : ∀ (j : J) (x y : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j (x + y)) (prequotient.add (prequotient.of j x) (prequotient.of j y)) | mul : ∀ (j : J) (x y : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j (x * y)) (prequotient.mul (prequotient.of j x) (prequotient.of j y)) | neg_1 : ∀ (x x' : prequotient F), relation F x x' → relation F (prequotient.neg x) (prequotient.neg x') | add_1 : ∀ (x x' y : prequotient F), relation F x x' → relation F (prequotient.add x y) (prequotient.add x' y) | add_2 : ∀ (x y y' : prequotient F), relation F y y' → relation F (prequotient.add x y) (prequotient.add x y') | mul_1 : ∀ (x x' y : prequotient F), relation F x x' → relation F (prequotient.mul x y) (prequotient.mul x' y) | mul_2 : ∀ (x y y' : prequotient F), relation F y y' → relation F (prequotient.mul x y) (prequotient.mul x y') | zero_add : ∀ (x : prequotient F), relation F (prequotient.add prequotient.zero x) x | add_zero : ∀ (x : prequotient F), relation F (prequotient.add x prequotient.zero) x | one_mul : ∀ (x : prequotient F), relation F (prequotient.mul prequotient.one x) x | mul_one : ∀ (x : prequotient F), relation F (prequotient.mul x prequotient.one) x | add_left_neg : ∀ (x : prequotient F), relation F (prequotient.add (prequotient.neg x) x) prequotient.zero | add_comm : ∀ (x y : prequotient F), relation F (prequotient.add x y) (prequotient.add y x) | mul_comm : ∀ (x y : prequotient F), relation F (prequotient.mul x y) (prequotient.mul y x) | add_assoc : ∀ (x y z : prequotient F), relation F (prequotient.add (prequotient.add x y) z) (prequotient.add x (prequotient.add y z)) | mul_assoc : ∀ (x y z : prequotient F), relation F (prequotient.mul (prequotient.mul x y) z) (prequotient.mul x (prequotient.mul y z)) | left_distrib : ∀ (x y z : prequotient F), relation F (prequotient.mul x (prequotient.add y z)) (prequotient.add (prequotient.mul x y) (prequotient.mul x z)) | right_distrib : ∀ (x y z : prequotient F), relation F (prequotient.mul (prequotient.add x y) z) (prequotient.add (prequotient.mul x z) (prequotient.mul y z)) -- There's always a `map` relation -- Then one relation per operation, describing the interaction with `of` -- Then one relation per argument of each operation -- And one relation per axiom /-- The setoid corresponding to commutative expressions modulo monoid relations and identifications. -/ instance colimit_setoid {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : setoid (prequotient F) := setoid.mk (relation F) sorry /-- The underlying type of the colimit of a diagram in `CommRing`. -/ def colimit_type {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) := quotient (colimit_setoid F) protected instance colimit_type.comm_ring {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : comm_ring (colimit_type F) := comm_ring.mk (Quot.lift (fun (x : prequotient F) => Quot.lift (fun (y : prequotient F) => Quot.mk setoid.r (prequotient.add x y)) sorry) sorry) sorry (Quot.mk setoid.r prequotient.zero) sorry sorry (Quot.lift (fun (x : prequotient F) => Quot.mk setoid.r (prequotient.neg x)) sorry) (ring.sub._default (Quot.lift (fun (x : prequotient F) => Quot.lift (fun (y : prequotient F) => Quot.mk setoid.r (prequotient.add x y)) sorry) sorry) sorry (Quot.mk setoid.r prequotient.zero) sorry sorry (Quot.lift (fun (x : prequotient F) => Quot.mk setoid.r (prequotient.neg x)) sorry)) sorry sorry (Quot.lift (fun (x : prequotient F) => Quot.lift (fun (y : prequotient F) => Quot.mk setoid.r (prequotient.mul x y)) sorry) sorry) sorry (Quot.mk setoid.r prequotient.one) sorry sorry sorry sorry sorry @[simp] theorem quot_zero {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : Quot.mk setoid.r prequotient.zero = 0 := rfl @[simp] theorem quot_one {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : Quot.mk setoid.r prequotient.one = 1 := rfl @[simp] theorem quot_neg {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (x : prequotient F) : Quot.mk setoid.r (prequotient.neg x) = -Quot.mk setoid.r x := rfl @[simp] theorem quot_add {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (x : prequotient F) (y : prequotient F) : Quot.mk setoid.r (prequotient.add x y) = Quot.mk setoid.r x + Quot.mk setoid.r y := rfl @[simp] theorem quot_mul {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (x : prequotient F) (y : prequotient F) : Quot.mk setoid.r (prequotient.mul x y) = Quot.mk setoid.r x * Quot.mk setoid.r y := rfl /-- The bundled commutative ring giving the colimit of a diagram. -/ def colimit {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : CommRing := of (colimit_type F) /-- The function from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_fun {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (j : J) (x : ↥(category_theory.functor.obj F j)) : colimit_type F := Quot.mk setoid.r (prequotient.of j x) /-- The ring homomorphism from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_morphism {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (j : J) : category_theory.functor.obj F j ⟶ colimit F := ring_hom.mk (cocone_fun F j) sorry sorry sorry sorry @[simp] theorem cocone_naturality {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) {j : J} {j' : J} (f : j ⟶ j') : category_theory.functor.map F f ≫ cocone_morphism F j' = cocone_morphism F j := ring_hom.ext fun (x : ↥(category_theory.functor.obj F j)) => quot.sound (relation.map j j' f x) @[simp] theorem cocone_naturality_components {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (j : J) (j' : J) (f : j ⟶ j') (x : ↥(category_theory.functor.obj F j)) : coe_fn (cocone_morphism F j') (coe_fn (category_theory.functor.map F f) x) = coe_fn (cocone_morphism F j) x := sorry /-- The cocone over the proposed colimit commutative ring. -/ def colimit_cocone {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : category_theory.limits.cocone F := category_theory.limits.cocone.mk (colimit F) (category_theory.nat_trans.mk (cocone_morphism F)) /-- The function from the free commutative ring on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (s : category_theory.limits.cocone F) : prequotient F → ↥(category_theory.limits.cocone.X s) := sorry /-- The function from the colimit commutative ring to the cone point of any other cocone. -/ def desc_fun {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (s : category_theory.limits.cocone F) : colimit_type F → ↥(category_theory.limits.cocone.X s) := Quot.lift (desc_fun_lift F s) sorry /-- The ring homomorphism from the colimit commutative ring to the cone point of any other cocone. -/ def desc_morphism {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) (s : category_theory.limits.cocone F) : colimit F ⟶ category_theory.limits.cocone.X s := ring_hom.mk (desc_fun F s) sorry sorry sorry sorry /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit {J : Type v} [category_theory.small_category J] (F : J ⥤ CommRing) : category_theory.limits.is_colimit (colimit_cocone F) := category_theory.limits.is_colimit.mk fun (s : category_theory.limits.cocone F) => desc_morphism F s protected instance has_colimits_CommRing : category_theory.limits.has_colimits CommRing := category_theory.limits.has_colimits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_colimits_of_shape.mk fun (F : J ⥤ CommRing) => category_theory.limits.has_colimit.mk (category_theory.limits.colimit_cocone.mk (colimit_cocone F) (colimit_is_colimit F)) end Mathlib
81a530233224061fc6327a21a7db35a4e960da0d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/lcnfTypes.lean
4477bdafc8eb7ea9bbdec1ee43589e6b739d05f0
[ "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
3,991
lean
import Lean open Lean Compiler LCNF Meta def test (declName : Name) : MetaM Unit := do IO.println s!"{declName} : {← ppExpr (← LCNF.getOtherDeclBaseType declName [])}" inductive Vec (α : Type u) : Nat → Type u | nil : Vec α 0 | cons : α → Vec α n → Vec α (n+1) def Vec.zip : Vec α n → Vec β n → Vec (α × β) n | .cons a as, .cons b bs => .cons (a, b) (zip as bs) | .nil, .nil => .nil def Tuple (α : Type u) : Nat → Type u | 0 => PUnit | 1 => α | n+2 => α × Tuple α n def mkConstTuple (a : α) : (n : Nat) → Tuple α n | 0 => ⟨⟩ | 1 => a | n+2 => (a, mkConstTuple a n) #eval test ``Vec.zip #eval test ``mkConstTuple #eval test ``Fin.add #eval test ``Vec.cons #eval test ``Eq.rec #eval test ``GetElem.getElem inductive HList {α : Type v} (β : α → Type u) : List α → Type (max u v) | nil : HList β [] | cons : β i → HList β is → HList β (i::is) infix:67 " :: " => HList.cons inductive Member : α → List α → Type _ | head : Member a (a::as) | tail : Member a bs → Member a (b::bs) def HList.get : HList β is → Member i is → β i | a::as, .head => a | _::as, .tail h => as.get h inductive Ty where | nat | fn : Ty → Ty → Ty abbrev Ty.denote : Ty → Type | nat => Nat | fn a b => a.denote → b.denote inductive Term : List Ty → Ty → Type | var : Member ty ctx → Term ctx ty | const : Nat → Term ctx .nat | plus : Term ctx .nat → Term ctx .nat → Term ctx .nat | app : Term ctx (.fn dom ran) → Term ctx dom → Term ctx ran | lam : Term (dom :: ctx) ran → Term ctx (.fn dom ran) | «let» : Term ctx ty₁ → Term (ty₁ :: ctx) ty₂ → Term ctx ty₂ def Term.denote : Term ctx ty → HList Ty.denote ctx → ty.denote | var h, env => env.get h | const n, _ => n | plus a b, env => a.denote env + b.denote env | app f a, env => f.denote env (a.denote env) | lam b, env => fun x => b.denote (x :: env) | «let» a b, env => b.denote (a.denote env :: env) def Term.constFold : Term ctx ty → Term ctx ty | const n => const n | var h => var h | app f a => app f.constFold a.constFold | lam b => lam b.constFold | «let» a b => «let» a.constFold b.constFold | plus a b => match a.constFold, b.constFold with | const n, const m => const (n+m) | a', b' => plus a' b' #eval test ``Term.constFold #eval test ``Term.denote #eval test ``HList.get #eval test ``Member.head #eval test ``Ty.denote #eval test ``MonadControl.liftWith #eval test ``MonadControl.restoreM #eval test ``Decidable.casesOn #eval test ``getConstInfo #eval test ``instMonadMetaM #eval test ``Lean.Meta.inferType #eval test ``Elab.Term.elabTerm #eval test ``Nat.add structure Magma where carrier : Type mul : carrier → carrier → carrier #eval test ``Magma.mul def weird1 (c : Bool) : (cond c List Array) Nat := match c with | true => [] | false => #[] #eval test ``weird1 axiom monadList₁.{u} : Monad List.{u} axiom monadList₂.{u} : Monad (fun α : Type u => List α) axiom lamAny₁ (c : Bool) : Monad (fun α : Type => cond c (List α) (Array α)) axiom lamAny₂ (c : Bool) : Monad (cond c List.{0} Array.{0}) #eval test ``lamAny₁ #eval test ``lamAny₂ def testMono (declName : Name) : MetaM Unit := do let base ← LCNF.getOtherDeclBaseType declName [] let mono ← LCNF.toMonoType base IO.println s!"{declName} : {← ppExpr mono}" set_option pp.explicit true #eval testMono ``Term.constFold #eval testMono ``Term.denote #eval testMono ``HList.get #eval testMono ``Member.head #eval testMono ``Ty.denote #eval testMono ``MonadControl.liftWith #eval testMono ``MonadControl.restoreM #eval testMono ``Decidable.casesOn #eval testMono ``getConstInfo #eval testMono ``instMonadMetaM #eval testMono ``Lean.Meta.inferType #eval testMono ``Elab.Term.elabTerm #eval testMono ``Nat.add #eval testMono ``Fin.add #eval testMono ``HashSetBucket.update
172425d81f12c003ea9e6a56cc7b0c8332e04cea
dd24e6c3b8dc14dc504f8a906fc04c51e4312e6b
/src/instructor/lectures/lecture_16.lean
af7ef4138ed434cc647cc544ffd8ec8849ab110d
[]
no_license
njeyasingh/CS-2120
dd781a90dd0645b74e61cee1813483fb7cb4a111
b3356f665a246f295b3f1e6d61901bfca331810d
refs/heads/main
1,693,294,711,274
1,635,188,659,000
1,635,188,659,000
399,945,420
0
0
null
null
null
null
UTF-8
Lean
false
false
4,690
lean
/- Algebraic structure: - collection of values - collection of applicable operations Examples: - int, + - int, +, * - string, ++ - bool, &&, ! (and, not) -/ /- We now introduce the algebraic structure that we call the set, by explaining what are the objects of this type and what are the applicable operations. -/ /- OBJECTS The objects of this algebraic structure are values of type "set T," where T is the type of objects "in" the set: of the "members" of the set. For example, consider the set, written in what's caledl display notation: { 1, 2, 3, 4 }. The set has four members, as enumerated here. The key distinction we want to make is between the type of the elements, here ℕ, and the type of the set, here, set ℕ. Lean in fact supports this notation. A little later in the lecture, we'll figure out what it actually means. Then you'll see the power that comes with the corresponding epiphany. -/ /- OPERATIONS Assume that we've been given some type, T. The operations of the "set T" algebraic structure include the following: empty set -- containing no elements of type T complete set -- containing all T-valued elts membership (s : set T) (val : T) : is member? complement (s : set T) : set T -- not in s union (s1 s2 : set T) : set T -- in either intersection (s1 s2 : set T) : set T -- in both product (s1 : set T) (s2 : set V) : set (T × V) power (s : set T) : set (set T) -- set of subsets -/ /- CHANGE IN PERSPECTIVE! You might visualize a set as being a collection of objects (such as natural numbers, for example). But let's make a fundamental shift in perspective, one that builds on everything we've learned so far. We will now think of a set defined by the property that distinguishes objects that are in the set from those that are not. -/ def s1 : set ℕ := { n : ℕ | n = 0 } #check s1 #reduce s1 #check λ (n : ℕ), n = 0 def s1' : ℕ → Prop := { n : ℕ | n = 0 } #check s1 0 #reduce s1' 0 #reduce s1 1 #reduce s1 2 #reduce s1' 3 /- Let's meet up once again with our favorite one-place predicate on the natural numbers. -/ def ev (n : ℕ) : Prop := n % 2 = 0 /- In a sense that we can now make precise, this *predicate* defines a set: the set of all natural numbers that *satisfy* it. We can think of ev as being a membership predicate that indicates whether a given value is in a given set or not. It should be clear that every predicate defines a set, and perhaps that there is a predicate for every set. The next section of the course introduces the lovely topic of set theory based exactly on this idea: represent sets as predicates, and operations on sets (such as intersection and union) as corresponding to operations on predicates. Indeed we will define the type "set T" just to be the predicate T → Prop! A set is thus represented *exactly* as a predicate in our logic. -/ -- set comprehension notation def s0 : set ℕ := { n : ℕ | ev n } def s0' : ℕ → Prop := { n : ℕ | ev n } --! def s0'' := { n : ℕ | ev n } -- Set predicate: proposition for each value #reduce s0 0 -- by rfl #reduce s0 1 -- false #reduce s0 2 -- by rfl #reduce s0 3 -- false --We can prove these two example : s0 0 := rfl example : s0 2 := rfl -- But not these two example : s0 1 := rfl example : s0 3 := rfl -- set membership notation #reduce 0 ∈ s0 -- yes #reduce 1 ∈ s0 -- no #reduce 2 ∈ s0 -- yes #reduce 3 ∈ s0 -- no example : 0 ∈ s0 := rfl example : 2 ∈ s0 := rfl -- But not these two example : 1 ∉ s0 := begin assume h, cases h, end example : 3 ∈ s0 := begin show s0 3, show ev 3, simp [ev], show 1 = 0, -- stuck end -- set display notation def s1'' : set nat := { 1, 2, 3, 4 } def s1''' := {1, 2, 3, 4} -- need explicit type /- #1: Represent the empty set using set comprehension. Here's the empty set (of natural numbers) in display notation. Write the same set using set comprehension notation. -/ def empty' : set ℕ := {} def empty : set ℕ := _ /- #2: Represent the entire set of the natural numbers using set comprehension notation. -/ def s2 : set ℕ := _ /- #3: Represent the set containinly all and only the natural numbers, 1, 2, 3, and 4. -/ def s1'' : set nat := _ /- What we see is that we can represent a given set with the right predicate in a set comprehension expression. Now let's think about having two sets, with two characteristic predicates, P and Q. We will continue to assume these operate on natural numbers, but the argument type could be anything. -/ axioms (P Q : ℕ → Prop) def pSet : set nat := { n : ℕ | P n} def qSet : set nat := { n : ℕ | Q n} #reduce pSet ∪ qSet
6d0e459d2196b66b65acb97e3c96ddae270c08cf
510e96af568b060ed5858226ad954c258549f143
/data/num/bitwise.lean
2e5138693091b342f2bd2bcaf9df0ad6dd7544b9
[]
no_license
Shamrock-Frost/library_dev
cb6d1739237d81e17720118f72ba0a6db8a5906b
0245c71e4931d3aceeacf0aea776454f6ee03c9c
refs/heads/master
1,609,481,034,595
1,500,165,215,000
1,500,165,347,000
97,350,162
0
0
null
1,500,164,969,000
1,500,164,969,000
null
UTF-8
Lean
false
false
3,074
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Bitwise operations using binary representation of integers. -/ import .basic namespace pos_num def lor : pos_num → pos_num → pos_num | 1 (bit0 q) := bit1 q | 1 q := q | (bit0 p) 1 := bit1 p | p 1 := p | (bit0 p) (bit0 q) := bit0 (lor p q) | (bit0 p) (bit1 q) := bit1 (lor p q) | (bit1 p) (bit0 q) := bit1 (lor p q) | (bit1 p) (bit1 q) := bit1 (lor p q) def land : pos_num → pos_num → num | 1 (bit0 q) := 0 | 1 _ := 1 | (bit0 p) 1 := 0 | _ 1 := 1 | (bit0 p) (bit0 q) := num.bit0 (land p q) | (bit0 p) (bit1 q) := num.bit0 (land p q) | (bit1 p) (bit0 q) := num.bit0 (land p q) | (bit1 p) (bit1 q) := num.bit1 (land p q) def ldiff : pos_num → pos_num → num | 1 (bit0 q) := 1 | 1 _ := 0 | (bit0 p) 1 := bit0 p | (bit1 p) 1 := bit0 p | (bit0 p) (bit0 q) := num.bit0 (ldiff p q) | (bit0 p) (bit1 q) := num.bit0 (ldiff p q) | (bit1 p) (bit0 q) := num.bit1 (ldiff p q) | (bit1 p) (bit1 q) := num.bit0 (ldiff p q) def lxor : pos_num → pos_num → num | 1 1 := 0 | 1 (bit0 q) := bit1 q | 1 (bit1 q) := bit0 q | (bit0 p) 1 := bit1 p | (bit1 p) 1 := bit0 p | (bit0 p) (bit0 q) := num.bit0 (lxor p q) | (bit0 p) (bit1 q) := num.bit1 (lxor p q) | (bit1 p) (bit0 q) := num.bit1 (lxor p q) | (bit1 p) (bit1 q) := num.bit0 (lxor p q) def test_bit : pos_num → nat → bool | 1 0 := tt | 1 (n+1) := ff | (bit0 p) 0 := ff | (bit0 p) (n+1) := test_bit p n | (bit1 p) 0 := tt | (bit1 p) (n+1) := test_bit p n def one_bits : pos_num → nat → list nat | 1 d := [d] | (bit0 p) d := one_bits p (d+1) | (bit1 p) d := d :: one_bits p (d+1) def shiftl (p : pos_num) : nat → pos_num | 0 := p | (n+1) := bit0 (shiftl n) def shiftr : pos_num → nat → num | p 0 := 1 | 1 (n+1) := 0 | (bit0 p) (n+1) := shiftr p n | (bit1 p) (n+1) := shiftr p n end pos_num namespace num def lor : num → num → num | 0 q := q | p 0 := p | (pos p) (pos q) := p.lor q def land : num → num → num | 0 q := 0 | p 0 := 0 | (pos p) (pos q) := p.land q def ldiff : num → num → num | 0 q := 0 | p 0 := p | (pos p) (pos q) := p.ldiff q def lxor : num → num → num | 0 q := q | p 0 := p | (pos p) (pos q) := p.lxor q def shiftl : num → nat → num | 0 n := 0 | (pos p) n := pos (p.shiftl n) def shiftr : num → nat → num | 0 n := 0 | (pos p) n := p.shiftr n def test_bit : num → nat → bool | 0 n := ff | (pos p) n := p.test_bit n def one_bits : num → list nat | 0 := [] | (pos p) := p.one_bits 0 end num
68d748865731fb95d006a80f3724afba4e89c5b9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/polynomial/eisenstein.lean
e1c05e1080d69ab3bfe09765eddd660a855b33d5
[ "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
28,625
lean
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.eisenstein_criterion import ring_theory.integrally_closed import ring_theory.norm import ring_theory.polynomial.cyclotomic.basic /-! # Eisenstein polynomials Given an ideal `𝓟` of a commutative semiring `R`, we say that a polynomial `f : R[X]` is *Eisenstein at `𝓟`* if `f.leading_coeff ∉ 𝓟`, `∀ n, n < f.nat_degree → f.coeff n ∈ 𝓟` and `f.coeff 0 ∉ 𝓟 ^ 2`. In this file we gather miscellaneous results about Eisenstein polynomials. ## Main definitions * `polynomial.is_eisenstein_at f 𝓟`: the property of being Eisenstein at `𝓟`. ## Main results * `polynomial.is_eisenstein_at.irreducible`: if a primitive `f` satisfies `f.is_eisenstein_at 𝓟`, where `𝓟.is_prime`, then `f` is irreducible. * `mem_adjoin_of_smul_prime_pow_smul_of_minpoly_is_eiseinstein_at`: let `K` be the field of fraction of an integrally closed domain `R` and let `L` be a separable extension of `K`, generated by an integral power basis `B` such that the minimal polynomial of `B.gen` is Eisenstein at `p`. Given `z : L` integral over `R`, if `p ^ n • z ∈ adjoin R {B.gen}`, then `z ∈ adjoin R {B.gen}`. Together with `algebra.discr_mul_is_integral_mem_adjoin` this result often allows to compute the ring of integers of `L`. ## Implementation details We also define a notion `is_weakly_eisenstein_at` requiring only that `∀ n < f.nat_degree → f.coeff n ∈ 𝓟`. This makes certain results slightly more general and it is useful since it is sometimes better behaved (for example it is stable under `polynomial.map`). -/ universes u v w z variables {R : Type u} open ideal algebra finset open_locale big_operators polynomial namespace polynomial /-- Given an ideal `𝓟` of a commutative semiring `R`, we say that a polynomial `f : R[X]` is *weakly Eisenstein at `𝓟`* if `∀ n, n < f.nat_degree → f.coeff n ∈ 𝓟`. -/ @[mk_iff] structure is_weakly_eisenstein_at [comm_semiring R] (f : R[X]) (𝓟 : ideal R) : Prop := (mem : ∀ {n}, n < f.nat_degree → f.coeff n ∈ 𝓟) /-- Given an ideal `𝓟` of a commutative semiring `R`, we say that a polynomial `f : R[X]` is *Eisenstein at `𝓟`* if `f.leading_coeff ∉ 𝓟`, `∀ n, n < f.nat_degree → f.coeff n ∈ 𝓟` and `f.coeff 0 ∉ 𝓟 ^ 2`. -/ @[mk_iff] structure is_eisenstein_at [comm_semiring R] (f : R[X]) (𝓟 : ideal R) : Prop := (leading : f.leading_coeff ∉ 𝓟) (mem : ∀ {n}, n < f.nat_degree → f.coeff n ∈ 𝓟) (not_mem : f.coeff 0 ∉ 𝓟 ^ 2) namespace is_weakly_eisenstein_at section comm_semiring variables [comm_semiring R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_weakly_eisenstein_at 𝓟) include hf lemma map {A : Type v} [comm_ring A] (φ : R →+* A) : (f.map φ).is_weakly_eisenstein_at (𝓟.map φ) := begin refine (is_weakly_eisenstein_at_iff _ _).2 (λ n hn, _), rw [coeff_map], exact mem_map_of_mem _ (hf.mem (lt_of_lt_of_le hn (nat_degree_map_le _ _))) end end comm_semiring section comm_ring variables [comm_ring R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_weakly_eisenstein_at 𝓟) variables {S : Type v} [comm_ring S] [algebra R S] section principal variable {p : R} local notation `P` := submodule.span R {p} lemma exists_mem_adjoin_mul_eq_pow_nat_degree {x : S} (hx : aeval x f = 0) (hmo : f.monic) (hf : f.is_weakly_eisenstein_at P) : ∃ y ∈ adjoin R ({x} : set S), (algebra_map R S) p * y = x ^ (f.map (algebra_map R S)).nat_degree := begin rw [aeval_def, polynomial.eval₂_eq_eval_map, eval_eq_sum_range, range_add_one, sum_insert not_mem_range_self, sum_range, (hmo.map (algebra_map R S)).coeff_nat_degree, one_mul] at hx, replace hx := eq_neg_of_add_eq_zero_left hx, have : ∀ n < f.nat_degree, p ∣ f.coeff n, { intros n hn, refine mem_span_singleton.1 (by simpa using hf.mem hn) }, choose! φ hφ using this, conv_rhs at hx { congr, congr, skip, funext, rw [fin.coe_eq_val, coeff_map, hφ i.1 (lt_of_lt_of_le i.2 (nat_degree_map_le _ _)), ring_hom.map_mul, mul_assoc] }, rw [hx, ← mul_sum, neg_eq_neg_one_mul, ← mul_assoc (-1 : S), mul_comm (-1 : S), mul_assoc], refine ⟨-1 * ∑ (i : fin (f.map (algebra_map R S)).nat_degree), (algebra_map R S) (φ i.1) * x ^ i.1, _, rfl⟩, exact subalgebra.mul_mem _ (subalgebra.neg_mem _ (subalgebra.one_mem _)) (subalgebra.sum_mem _ (λ i hi, subalgebra.mul_mem _ (subalgebra.algebra_map_mem _ _) (subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton x)) _))) end lemma exists_mem_adjoin_mul_eq_pow_nat_degree_le {x : S} (hx : aeval x f = 0) (hmo : f.monic) (hf : f.is_weakly_eisenstein_at P) : ∀ i, (f.map (algebra_map R S)).nat_degree ≤ i → ∃ y ∈ adjoin R ({x} : set S), (algebra_map R S) p * y = x ^ i := begin intros i hi, obtain ⟨k, hk⟩ := exists_add_of_le hi, rw [hk, pow_add], obtain ⟨y, hy, H⟩ := exists_mem_adjoin_mul_eq_pow_nat_degree hx hmo hf, refine ⟨y * x ^ k, _, _⟩, { exact subalgebra.mul_mem _ hy (subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton x)) _) }, { rw [← mul_assoc _ y, H] } end end principal include hf lemma pow_nat_degree_le_of_root_of_monic_mem {x : R} (hroot : is_root f x) (hmo : f.monic) : ∀ i, f.nat_degree ≤ i → x ^ i ∈ 𝓟 := begin intros i hi, obtain ⟨k, hk⟩ := exists_add_of_le hi, rw [hk, pow_add], suffices : x ^ f.nat_degree ∈ 𝓟, { exact mul_mem_right (x ^ k) 𝓟 this }, rw [is_root.def, eval_eq_sum_range, finset.range_add_one, finset.sum_insert finset.not_mem_range_self, finset.sum_range, hmo.coeff_nat_degree, one_mul] at hroot, rw [eq_neg_of_add_eq_zero_left hroot, neg_mem_iff], refine submodule.sum_mem _ (λ i hi, mul_mem_right _ _ (hf.mem (fin.is_lt i))) end lemma pow_nat_degree_le_of_aeval_zero_of_monic_mem_map {x : S} (hx : aeval x f = 0) (hmo : f.monic) : ∀ i, (f.map (algebra_map R S)).nat_degree ≤ i → x ^ i ∈ 𝓟.map (algebra_map R S) := begin suffices : x ^ (f.map (algebra_map R S)).nat_degree ∈ 𝓟.map (algebra_map R S), { intros i hi, obtain ⟨k, hk⟩ := exists_add_of_le hi, rw [hk, pow_add], refine mul_mem_right _ _ this }, rw [aeval_def, eval₂_eq_eval_map, ← is_root.def] at hx, refine pow_nat_degree_le_of_root_of_monic_mem (hf.map _) hx (hmo.map _) _ rfl.le end end comm_ring end is_weakly_eisenstein_at section scale_roots variables {A : Type*} [comm_ring R] [comm_ring A] lemma scale_roots.is_weakly_eisenstein_at (p : R[X]) {x : R} {P : ideal R} (hP : x ∈ P) : (scale_roots p x).is_weakly_eisenstein_at P := begin refine ⟨λ i hi, _⟩, rw coeff_scale_roots, rw [nat_degree_scale_roots, ← tsub_pos_iff_lt] at hi, exact ideal.mul_mem_left _ _ (ideal.pow_mem_of_mem P hP _ hi) end lemma dvd_pow_nat_degree_of_eval₂_eq_zero {f : R →+* A} (hf : function.injective f) {p : R[X]} (hp : p.monic) (x y : R) (z : A) (h : p.eval₂ f z = 0) (hz : f x * z = f y) : x ∣ y ^ p.nat_degree := begin rw [← nat_degree_scale_roots p x, ← ideal.mem_span_singleton], refine (scale_roots.is_weakly_eisenstein_at _ (ideal.mem_span_singleton.mpr $ dvd_refl x)) .pow_nat_degree_le_of_root_of_monic_mem _ ((monic_scale_roots_iff x).mpr hp) _ le_rfl, rw injective_iff_map_eq_zero' at hf, have := scale_roots_eval₂_eq_zero f h, rwa [hz, polynomial.eval₂_at_apply, hf] at this end lemma dvd_pow_nat_degree_of_aeval_eq_zero [algebra R A] [nontrivial A] [no_zero_smul_divisors R A] {p : R[X]} (hp : p.monic) (x y : R) (z : A) (h : polynomial.aeval z p = 0) (hz : z * algebra_map R A x = algebra_map R A y) : x ∣ y ^ p.nat_degree := dvd_pow_nat_degree_of_eval₂_eq_zero (no_zero_smul_divisors.algebra_map_injective R A) hp x y z h ((mul_comm _ _).trans hz) end scale_roots namespace is_eisenstein_at section comm_semiring variables [comm_semiring R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_eisenstein_at 𝓟) lemma _root_.polynomial.monic.leading_coeff_not_mem (hf : f.monic) (h : 𝓟 ≠ ⊤) : ¬f.leading_coeff ∈ 𝓟 := hf.leading_coeff.symm ▸ (ideal.ne_top_iff_one _).1 h lemma _root_.polynomial.monic.is_eisenstein_at_of_mem_of_not_mem (hf : f.monic) (h : 𝓟 ≠ ⊤) (hmem : ∀ {n}, n < f.nat_degree → f.coeff n ∈ 𝓟) (hnot_mem : f.coeff 0 ∉ 𝓟 ^ 2) : f.is_eisenstein_at 𝓟 := { leading := hf.leading_coeff_not_mem h, mem := λ n hn, hmem hn, not_mem := hnot_mem } include hf lemma is_weakly_eisenstein_at : is_weakly_eisenstein_at f 𝓟 := ⟨λ _, hf.mem⟩ lemma coeff_mem {n : ℕ} (hn : n ≠ f.nat_degree) : f.coeff n ∈ 𝓟 := begin cases ne_iff_lt_or_gt.1 hn, { exact hf.mem h }, { rw [coeff_eq_zero_of_nat_degree_lt h], exact ideal.zero_mem _} end end comm_semiring section is_domain variables [comm_ring R] [is_domain R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_eisenstein_at 𝓟) /-- If a primitive `f` satisfies `f.is_eisenstein_at 𝓟`, where `𝓟.is_prime`, then `f` is irreducible. -/ lemma irreducible (hprime : 𝓟.is_prime) (hu : f.is_primitive) (hfd0 : 0 < f.nat_degree) : irreducible f := irreducible_of_eisenstein_criterion hprime hf.leading (λ n hn, hf.mem (coe_lt_degree.1 hn)) (nat_degree_pos_iff_degree_pos.1 hfd0) hf.not_mem hu end is_domain end is_eisenstein_at end polynomial section cyclotomic variables (p : ℕ) local notation `𝓟` := submodule.span ℤ {p} open polynomial lemma cyclotomic_comp_X_add_one_is_eisenstein_at [hp : fact p.prime] : ((cyclotomic p ℤ).comp (X + 1)).is_eisenstein_at 𝓟 := begin refine monic.is_eisenstein_at_of_mem_of_not_mem _ (ideal.is_prime.ne_top $(ideal.span_singleton_prime (by exact_mod_cast hp.out.ne_zero)).2 $ nat.prime_iff_prime_int.1 hp.out) (λ i hi, _) _, { rw [show (X + 1 : ℤ[X]) = X + C 1, by simp], refine ((cyclotomic.monic p ℤ).comp (monic_X_add_C 1) (λ h, _)), rw [nat_degree_X_add_C] at h, exact zero_ne_one h.symm }, { rw [cyclotomic_prime, geom_sum_X_comp_X_add_one_eq_sum, ← lcoeff_apply, linear_map.map_sum], conv { congr, congr, skip, funext, rw [lcoeff_apply, ← C_eq_nat_cast, C_mul_X_pow_eq_monomial, coeff_monomial] }, rw [nat_degree_comp, show (X + 1 : ℤ[X]) = X + C 1, by simp, nat_degree_X_add_C, mul_one, nat_degree_cyclotomic, nat.totient_prime hp.out] at hi, simp only [lt_of_lt_of_le hi (nat.sub_le _ _), sum_ite_eq', mem_range, if_true, ideal.submodule_span_eq, ideal.mem_span_singleton], exact int.coe_nat_dvd.2 (nat.prime.dvd_choose_self (nat.succ_pos i) (lt_tsub_iff_right.1 hi) hp.out) }, { rw [coeff_zero_eq_eval_zero, eval_comp, cyclotomic_prime, eval_add, eval_X, eval_one, zero_add, eval_geom_sum, one_geom_sum, ideal.submodule_span_eq, ideal.span_singleton_pow, ideal.mem_span_singleton], intro h, obtain ⟨k, hk⟩ := int.coe_nat_dvd.1 h, rw [← mul_assoc, mul_one, mul_assoc] at hk, nth_rewrite 0 [← nat.mul_one p] at hk, rw [mul_right_inj' hp.out.ne_zero] at hk, exact nat.prime.not_dvd_one hp.out (dvd.intro k (hk.symm)) } end lemma cyclotomic_prime_pow_comp_X_add_one_is_eisenstein_at [hp : fact p.prime] (n : ℕ) : ((cyclotomic (p ^ (n + 1)) ℤ).comp (X + 1)).is_eisenstein_at 𝓟 := begin refine monic.is_eisenstein_at_of_mem_of_not_mem _ (ideal.is_prime.ne_top $(ideal.span_singleton_prime (by exact_mod_cast hp.out.ne_zero)).2 $ nat.prime_iff_prime_int.1 hp.out) _ _, { rw [show (X + 1 : ℤ[X]) = X + C 1, by simp], refine ((cyclotomic.monic _ ℤ).comp (monic_X_add_C 1) (λ h, _)), rw [nat_degree_X_add_C] at h, exact zero_ne_one h.symm }, { induction n with n hn, { intros i hi, rw [zero_add, pow_one] at hi ⊢, exact (cyclotomic_comp_X_add_one_is_eisenstein_at p).mem hi }, { intros i hi, rw [ideal.submodule_span_eq, ideal.mem_span_singleton, ← zmod.int_coe_zmod_eq_zero_iff_dvd, ← int.coe_cast_ring_hom, ← coeff_map, map_comp, map_cyclotomic, polynomial.map_add, map_X, polynomial.map_one, pow_add, pow_one, cyclotomic_mul_prime_dvd_eq_pow, pow_comp, ← zmod.expand_card, coeff_expand hp.out.pos], { simp only [ite_eq_right_iff], rintro ⟨k, hk⟩, rw [nat_degree_comp, show (X + 1 : ℤ[X]) = X + C 1, by simp, nat_degree_X_add_C, mul_one, nat_degree_cyclotomic, nat.totient_prime_pow hp.out (nat.succ_pos _), nat.succ_sub_one] at hn hi, rw [hk, pow_succ, mul_assoc] at hi, rw [hk, mul_comm, nat.mul_div_cancel _ hp.out.pos], replace hn := hn (lt_of_mul_lt_mul_left' hi), rw [ideal.submodule_span_eq, ideal.mem_span_singleton, ← zmod.int_coe_zmod_eq_zero_iff_dvd, ← int.coe_cast_ring_hom, ← coeff_map] at hn, simpa [map_comp] using hn }, { exact ⟨p ^ n, by rw [pow_succ]⟩ } } }, { rw [coeff_zero_eq_eval_zero, eval_comp, cyclotomic_prime_pow_eq_geom_sum hp.out, eval_add, eval_X, eval_one, zero_add, eval_finset_sum], simp only [eval_pow, eval_X, one_pow, sum_const, card_range, nat.smul_one_eq_coe, submodule_span_eq, ideal.submodule_span_eq, ideal.span_singleton_pow, ideal.mem_span_singleton], intro h, obtain ⟨k, hk⟩ := int.coe_nat_dvd.1 h, rw [← mul_assoc, mul_one, mul_assoc] at hk, nth_rewrite 0 [← nat.mul_one p] at hk, rw [mul_right_inj' hp.out.ne_zero] at hk, exact nat.prime.not_dvd_one hp.out (dvd.intro k (hk.symm)) } end end cyclotomic section is_integral variables {K : Type v} {L : Type z} {p : R} [comm_ring R] [field K] [field L] variables [algebra K L] [algebra R L] [algebra R K] [is_scalar_tower R K L] [is_separable K L] variables [is_domain R] [normalized_gcd_monoid R] [is_fraction_ring R K] [is_integrally_closed R] local notation `𝓟` := submodule.span R {p} open is_integrally_closed power_basis nat polynomial is_scalar_tower /-- Let `K` be the field of fraction of an integrally closed domain `R` and let `L` be a separable extension of `K`, generated by an integral power basis `B` such that the minimal polynomial of `B.gen` is Eisenstein at `p`. Given `z : L` integral over `R`, if `Q : R[X]` is such that `aeval B.gen Q = p • z`, then `p ∣ Q.coeff 0`. -/ lemma dvd_coeff_zero_of_aeval_eq_prime_smul_of_minpoly_is_eiseinstein_at {B : power_basis K L} (hp : prime p) (hBint : is_integral R B.gen) {z : L} {Q : R[X]} (hQ : aeval B.gen Q = p • z) (hzint : is_integral R z) (hei : (minpoly R B.gen).is_eisenstein_at 𝓟) : p ∣ Q.coeff 0 := begin -- First define some abbreviations. letI := B.finite_dimensional, let P := minpoly R B.gen, obtain ⟨n , hn⟩ := nat.exists_eq_succ_of_ne_zero B.dim_pos.ne', have finrank_K_L : finite_dimensional.finrank K L = B.dim := B.finrank, have deg_K_P : (minpoly K B.gen).nat_degree = B.dim := B.nat_degree_minpoly, have deg_R_P : P.nat_degree = B.dim, { rw [← deg_K_P, minpoly.gcd_domain_eq_field_fractions' K hBint, (minpoly.monic hBint).nat_degree_map (algebra_map R K)] }, choose! f hf using hei.is_weakly_eisenstein_at.exists_mem_adjoin_mul_eq_pow_nat_degree_le (minpoly.aeval R B.gen) (minpoly.monic hBint), simp only [(minpoly.monic hBint).nat_degree_map, deg_R_P] at hf, -- The Eisenstein condition shows that `p` divides `Q.coeff 0` -- if `p^n.succ` divides the following multiple of `Q.coeff 0^n.succ`: suffices : p ^ n.succ ∣ (Q.coeff 0 ^ n.succ * ((-1) ^ (n.succ * n) * (minpoly R B.gen).coeff 0 ^ n)), { have hndiv : ¬ p ^ 2 ∣ ((minpoly R B.gen)).coeff 0 := λ h, hei.not_mem ((span_singleton_pow p 2).symm ▸ (ideal.mem_span_singleton.2 h)), refine prime.dvd_of_pow_dvd_pow_mul_pow_of_square_not_dvd hp ((_ : _ ^ n.succ ∣ _)) hndiv, convert (is_unit.dvd_mul_right ⟨(-1) ^ (n.succ * n), rfl⟩).mpr this using 1, push_cast, ring_nf, simp [pow_right_comm _ _ 2] }, -- We claim the quotient of `Q^n * _` by `p^n` is the following `r`: have aux : ∀ i ∈ (range (Q.nat_degree + 1)).erase 0, B.dim ≤ i + n, { intros i hi, simp only [mem_range, mem_erase] at hi, rw [hn], exact le_add_pred_of_pos _ hi.1 }, have hintsum : is_integral R (z * B.gen ^ n - ∑ (x : ℕ) in (range (Q.nat_degree + 1)).erase 0, Q.coeff x • f (x + n)), { refine is_integral_sub (is_integral_mul hzint (is_integral.pow hBint _)) (is_integral.sum _ (λ i hi, (is_integral_smul _ _))), exact adjoin_le_integral_closure hBint (hf _ (aux i hi)).1 }, obtain ⟨r, hr⟩ := is_integral_iff.1 (is_integral_norm K hintsum), use r, -- Do the computation in `K` so we can work in terms of `z` instead of `r`. apply is_fraction_ring.injective R K, simp only [_root_.map_mul, _root_.map_pow, _root_.map_neg, _root_.map_one], -- Both sides are actually norms: calc _ = norm K (Q.coeff 0 • B.gen ^ n) : _ ... = norm K (p • (z * B.gen ^ n) - ∑ (x : ℕ) in (range (Q.nat_degree + 1)).erase 0, p • Q.coeff x • f (x + n)) : congr_arg (norm K) (eq_sub_of_add_eq _) ... = _ : _, { simp only [algebra.smul_def, algebra_map_apply R K L, algebra.norm_algebra_map, _root_.map_mul, _root_.map_pow, finrank_K_L, power_basis.norm_gen_eq_coeff_zero_minpoly, minpoly.gcd_domain_eq_field_fractions' K hBint, coeff_map, ← hn], ring_exp }, swap, { simp_rw [← smul_sum, ← smul_sub, algebra.smul_def p, algebra_map_apply R K L, _root_.map_mul, algebra.norm_algebra_map, finrank_K_L, hr, ← hn] }, calc _ = (Q.coeff 0 • 1 + ∑ (x : ℕ) in (range (Q.nat_degree + 1)).erase 0, Q.coeff x • B.gen ^ x) * B.gen ^ n : _ ... = (Q.coeff 0 • B.gen ^ 0 + ∑ (x : ℕ) in (range (Q.nat_degree + 1)).erase 0, Q.coeff x • B.gen ^ x) * B.gen ^ n : by rw pow_zero ... = (aeval B.gen Q) * B.gen ^ n : _ ... = _ : by rw [hQ, algebra.smul_mul_assoc], { have : ∀ i ∈ (range (Q.nat_degree + 1)).erase 0, Q.coeff i • (B.gen ^ i * B.gen ^ n) = p • Q.coeff i • f (i + n), { intros i hi, rw [←pow_add, ←(hf _ (aux i hi)).2, ←algebra.smul_def, smul_smul, mul_comm _ p, smul_smul] }, simp only [add_mul, smul_mul_assoc, one_mul, sum_mul, sum_congr rfl this] }, { rw [aeval_eq_sum_range, finset.add_sum_erase (range (Q.nat_degree + 1)) (λ i, Q.coeff i • B.gen ^ i)], simp }, end lemma mem_adjoin_of_dvd_coeff_of_dvd_aeval {A B : Type*} [comm_semiring A] [comm_ring B] [algebra A B] [no_zero_smul_divisors A B] {Q : A[X]} {p : A} {x z : B} (hp : p ≠ 0) (hQ : ∀ i ∈ range (Q.nat_degree + 1), p ∣ Q.coeff i) (hz : aeval x Q = p • z) : z ∈ adjoin A ({x} : set B) := begin choose! f hf using hQ, rw [aeval_eq_sum_range, sum_range] at hz, conv_lhs at hz { congr, skip, funext, rw [hf i (mem_range.2 (fin.is_lt i)), ← smul_smul] }, rw [← smul_sum] at hz, rw [← smul_right_injective _ hp hz], exact subalgebra.sum_mem _ (λ _ _, subalgebra.smul_mem _ (subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton _)) _) _) end /-- Let `K` be the field of fraction of an integrally closed domain `R` and let `L` be a separable extension of `K`, generated by an integral power basis `B` such that the minimal polynomial of `B.gen` is Eisenstein at `p`. Given `z : L` integral over `R`, if `p • z ∈ adjoin R {B.gen}`, then `z ∈ adjoin R {B.gen}`. -/ lemma mem_adjoin_of_smul_prime_smul_of_minpoly_is_eiseinstein_at {B : power_basis K L} (hp : prime p) (hBint : is_integral R B.gen) {z : L} (hzint : is_integral R z) (hz : p • z ∈ adjoin R ({B.gen} : set L)) (hei : (minpoly R B.gen).is_eisenstein_at 𝓟) : z ∈ adjoin R ({B.gen} : set L) := begin -- First define some abbreviations. have hndiv : ¬ p ^ 2 ∣ ((minpoly R B.gen)).coeff 0 := λ h, hei.not_mem ((span_singleton_pow p 2).symm ▸ (ideal.mem_span_singleton.2 h)), letI := finite_dimensional B, set P := minpoly R B.gen with hP, obtain ⟨n , hn⟩ := nat.exists_eq_succ_of_ne_zero B.dim_pos.ne', haveI : no_zero_smul_divisors R L := no_zero_smul_divisors.trans R K L, let P₁ := P.map (algebra_map R L), -- There is a polynomial `Q` such that `p • z = aeval B.gen Q`. We can assume that -- `Q.degree < P.degree` and `Q ≠ 0`. rw [adjoin_singleton_eq_range_aeval] at hz, obtain ⟨Q₁, hQ⟩ := hz, set Q := Q₁ %ₘ P with hQ₁, replace hQ : aeval B.gen Q = p • z, { rw [← mod_by_monic_add_div Q₁ (minpoly.monic hBint)] at hQ, simpa using hQ }, by_cases hQzero : Q = 0, { simp only [hQzero, algebra.smul_def, zero_eq_mul, aeval_zero] at hQ, cases hQ with H H₁, { have : function.injective (algebra_map R L), { rw [algebra_map_eq R K L], exact (algebra_map K L).injective.comp (is_fraction_ring.injective R K) }, exfalso, exact hp.ne_zero ((injective_iff_map_eq_zero _).1 this _ H) }, { rw [H₁], exact subalgebra.zero_mem _ } }, -- It is enough to prove that all coefficients of `Q` are divisible by `p`, by induction. -- The base case is `dvd_coeff_zero_of_aeval_eq_prime_smul_of_minpoly_is_eiseinstein_at`. refine mem_adjoin_of_dvd_coeff_of_dvd_aeval hp.ne_zero (λ i, _) hQ, refine nat.case_strong_induction_on i _ (λ j hind, _), { intro H, exact dvd_coeff_zero_of_aeval_eq_prime_smul_of_minpoly_is_eiseinstein_at hp hBint hQ hzint hei }, { intro hj, refine hp.dvd_of_pow_dvd_pow_mul_pow_of_square_not_dvd _ hndiv, exact n, -- Two technical results we will need about `P.nat_degree` and `Q.nat_degree`. have H := degree_mod_by_monic_lt Q₁ (minpoly.monic hBint), rw [← hQ₁, ← hP] at H, replace H:= nat.lt_iff_add_one_le.1 (lt_of_lt_of_le (lt_of_le_of_lt (nat.lt_iff_add_one_le.1 (nat.lt_of_succ_lt_succ (mem_range.1 hj))) (lt_succ_self _)) (nat.lt_iff_add_one_le.1 (((nat_degree_lt_nat_degree_iff hQzero).2 H)))), rw [add_assoc] at H, have Hj : Q.nat_degree + 1 = j + 1 + (Q.nat_degree - j), { rw [← add_comm 1, ← add_comm 1, add_assoc, add_right_inj, ← nat.add_sub_assoc (nat.lt_of_succ_lt_succ (mem_range.1 hj)).le, add_comm, nat.add_sub_cancel] }, -- By induction hypothesis we can find `g : ℕ → R` such that -- `k ∈ range (j + 1) → Q.coeff k • B.gen ^ k = (algebra_map R L) p * g k • B.gen ^ k`- choose! g hg using hind, replace hg : ∀ k ∈ range (j + 1), Q.coeff k • B.gen ^ k = (algebra_map R L p) * (g k • B.gen ^ k), { intros k hk, rw [hg k (mem_range_succ_iff.1 hk) (mem_range_succ_iff.2 (le_trans (mem_range_succ_iff.1 hk) (succ_le_iff.1 (mem_range_succ_iff.1 hj)).le)), algebra.smul_def, algebra.smul_def, ring_hom.map_mul, mul_assoc] }, -- Since `minpoly R B.gen` is Eiseinstein, we can find `f : ℕ → L` such that -- `(map (algebra_map R L) (minpoly R B.gen)).nat_degree ≤ i` implies `f i ∈ adjoin R {B.gen}` -- and `(algebra_map R L) p * f i = B.gen ^ i`. We will also need `hf₁`, a reformulation of this -- property. choose! f hf using (is_weakly_eisenstein_at.exists_mem_adjoin_mul_eq_pow_nat_degree_le (minpoly.aeval R B.gen) (minpoly.monic hBint) hei.is_weakly_eisenstein_at), have hf₁ : ∀ k ∈ (range (Q.nat_degree - j)).erase 0, Q.coeff (j + 1 + k) • B.gen ^ (j + 1 + k) * B.gen ^ (P.nat_degree - (j + 2)) = (algebra_map R L) p * Q.coeff (j + 1 + k) • f (k + P.nat_degree - 1), { intros k hk, rw [smul_mul_assoc, ← pow_add, ← nat.add_sub_assoc H, ← add_assoc j 1 1, add_comm (j + 1) 1, add_assoc (j + 1), add_comm _ (k + P.nat_degree), nat.add_sub_add_right, ← (hf (k + P.nat_degree - 1) _).2, mul_smul_comm], rw [(minpoly.monic hBint).nat_degree_map, add_comm, nat.add_sub_assoc, le_add_iff_nonneg_right], { exact nat.zero_le _ }, { refine one_le_iff_ne_zero.2 (λ h, _), rw [h] at hk, simpa using hk }, { apply_instance } }, -- The Eisenstein condition shows that `p` divides `Q.coeff j` -- if `p^n.succ` divides the following multiple of `Q.coeff (succ j)^n.succ`: suffices : p ^ n.succ ∣ Q.coeff (succ j) ^ n.succ * (minpoly R B.gen).coeff 0 ^ (succ j + (P.nat_degree - (j + 2))), { convert this, rw [nat.succ_eq_add_one, add_assoc, ← nat.add_sub_assoc H, ← add_assoc, add_comm (j + 1), nat.add_sub_add_left, ← nat.add_sub_assoc, nat.add_sub_add_left, hP, ← (minpoly.monic hBint).nat_degree_map (algebra_map R K), ← minpoly.gcd_domain_eq_field_fractions' K hBint, nat_degree_minpoly, hn, nat.sub_one, nat.pred_succ], linarith }, -- Using `hQ : aeval B.gen Q = p • z`, we write `p • z` as a sum of terms of degree less than -- `j+1`, that are multiples of `p` by induction, and terms of degree at least `j+1`. rw [aeval_eq_sum_range, Hj, range_add, sum_union (disjoint_range_add_left_embedding _ _), sum_congr rfl hg, add_comm] at hQ, -- We multiply this equality by `B.gen ^ (P.nat_degree-(j+2))`, so we can use `hf₁` on the terms -- we didn't know were multiples of `p`, and we take the norm on both sides. replace hQ := congr_arg (λ x, x * B.gen ^ (P.nat_degree - (j + 2))) hQ, simp_rw [sum_map, add_left_embedding_apply, add_mul, sum_mul, mul_assoc] at hQ, rw [← insert_erase (mem_range.2 (tsub_pos_iff_lt.2 $ nat.lt_of_succ_lt_succ $ mem_range.1 hj)), sum_insert (not_mem_erase 0 _), add_zero, sum_congr rfl hf₁, ← mul_sum, ← mul_sum, add_assoc, ← mul_add, smul_mul_assoc, ← pow_add, algebra.smul_def] at hQ, replace hQ := congr_arg (norm K) (eq_sub_of_add_eq hQ), -- We obtain an equality of elements of `K`, but everything is integral, so we can move to `R` -- and simplify `hQ`. have hintsum : is_integral R (z * B.gen ^ (P.nat_degree - (j + 2)) - (∑ (x : ℕ) in (range (Q.nat_degree - j)).erase 0, Q.coeff (j + 1 + x) • f (x + P.nat_degree - 1) + ∑ (x : ℕ) in range (j + 1), g x • B.gen ^ x * B.gen ^ (P.nat_degree - (j + 2)))), { refine is_integral_sub (is_integral_mul hzint (is_integral.pow hBint _)) (is_integral_add (is_integral.sum _ (λ k hk, is_integral_smul _ _)) (is_integral.sum _ (λ k hk, is_integral_mul (is_integral_smul _ (is_integral.pow hBint _)) ((is_integral.pow hBint _))))), refine adjoin_le_integral_closure hBint (hf _ _).1, rw [(minpoly.monic hBint).nat_degree_map (algebra_map R L)], rw [add_comm, nat.add_sub_assoc, le_add_iff_nonneg_right], { exact zero_le _ }, { refine one_le_iff_ne_zero.2 (λ h, _), rw [h] at hk, simpa using hk } }, obtain ⟨r, hr⟩ := is_integral_iff.1 (is_integral_norm K hintsum), rw [algebra.smul_def, mul_assoc, ← mul_sub, _root_.map_mul, algebra_map_apply R K L, map_pow, algebra.norm_algebra_map, _root_.map_mul, algebra_map_apply R K L, algebra.norm_algebra_map, finrank B, ← hr, power_basis.norm_gen_eq_coeff_zero_minpoly, minpoly.gcd_domain_eq_field_fractions' K hBint, coeff_map, show (-1 : K) = algebra_map R K (-1), by simp, ← map_pow, ← map_pow, ← _root_.map_mul, ← map_pow, ← _root_.map_mul, ← map_pow, ← _root_.map_mul] at hQ, -- We can now finish the proof. have hppdiv : p ^ B.dim ∣ p ^ B.dim * r := dvd_mul_of_dvd_left dvd_rfl _, rwa [← is_fraction_ring.injective R K hQ, mul_comm, ← units.coe_neg_one, mul_pow, ← units.coe_pow, ← units.coe_pow, mul_assoc, is_unit.dvd_mul_left _ _ _ ⟨_, rfl⟩, mul_comm, ← nat.succ_eq_add_one, hn] at hppdiv } end /-- Let `K` be the field of fraction of an integrally closed domain `R` and let `L` be a separable extension of `K`, generated by an integral power basis `B` such that the minimal polynomial of `B.gen` is Eisenstein at `p`. Given `z : L` integral over `R`, if `p ^ n • z ∈ adjoin R {B.gen}`, then `z ∈ adjoin R {B.gen}`. Together with `algebra.discr_mul_is_integral_mem_adjoin` this result often allows to compute the ring of integers of `L`. -/ lemma mem_adjoin_of_smul_prime_pow_smul_of_minpoly_is_eiseinstein_at {B : power_basis K L} (hp : prime p) (hBint : is_integral R B.gen) {n : ℕ} {z : L} (hzint : is_integral R z) (hz : p ^ n • z ∈ adjoin R ({B.gen} : set L)) (hei : (minpoly R B.gen).is_eisenstein_at 𝓟) : z ∈ adjoin R ({B.gen} : set L) := begin induction n with n hn, { simpa using hz }, { rw [pow_succ, mul_smul] at hz, exact hn (mem_adjoin_of_smul_prime_smul_of_minpoly_is_eiseinstein_at hp hBint (is_integral_smul _ hzint) hz hei) } end end is_integral
ce04fc40b8051fdd0b00f23ce7d1ed3fe8178299
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/gaussian.lean
59de701ce2c8aa72563a0c43686521ca0a0c3d7e
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
3,795
lean
import data.matrix .matrix_pequiv tactic.linarith data.zmod.basic variables {α : Type*} open equiv pequiv matrix local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose namespace pequiv def diagonal_ul (m n r : ℕ) : fin m ≃. fin n := { to_fun := λ i, if hi : i.1 < r ∧ i.1 < n then some ⟨i.1, hi.2⟩ else none, inv_fun := λ j, if hj : j.1 < r ∧ j.1 < m then some ⟨j.1, hj.2⟩ else none, inv := λ ⟨i, hi⟩ ⟨j, hj⟩, begin clear_aux_decl, dsimp, split_ifs, { simp [eq_comm] }, { simp, intros h, simp [*, -not_lt] at * }, { simp, intro h, simp [*, -not_lt] at * }, { simp } end } lemma symm_diagonal_ul (m n r : ℕ) : (diagonal_ul m n r).symm = diagonal_ul n m r := rfl def equiv.anti_diagonal (n : ℕ) : fin n ≃ fin n := { to_fun := λ i, ⟨n - (i.1 + 1), nat.sub_lt (lt_of_le_of_lt (nat.zero_le _) i.2) (nat.succ_pos _)⟩, inv_fun := λ i, ⟨n - (i.1 + 1), nat.sub_lt (lt_of_le_of_lt (nat.zero_le _) i.2) (nat.succ_pos _)⟩, left_inv := λ ⟨i, hi⟩, fin.eq_of_veq $ by dsimp; rw [nat.sub_add_eq_add_sub hi, nat.succ_sub_succ, nat.sub_sub_self (le_of_lt hi)], right_inv := λ ⟨i, hi⟩, fin.eq_of_veq $ by dsimp; rw [nat.sub_add_eq_add_sub hi, nat.succ_sub_succ, nat.sub_sub_self (le_of_lt hi)] } def diagonal_dr (m n r : ℕ) : fin m ≃. fin n := ((equiv.anti_diagonal m).to_pequiv.trans (diagonal_ul m n r)).trans (equiv.anti_diagonal n).to_pequiv end pequiv /-- pick a matrix element that matches a given property or return none in case of no match. -/ def pick (p : α → Prop) [decidable_pred p] {m n : ℕ} (A : matrix (fin m) (fin n) α) : option (fin m × fin n) := if h : ∃ (ij : fin m × fin n), p (A ij.1 ij.2) then some (encodable.choose h) else none open pequiv def Gaussian_elimination [discrete_field α] : Π {m n}, matrix (fin m) (fin n) α → (matrix (fin m) (fin m) α × matrix (fin n) (fin n) α × ℕ) | (x+1) (y+1) A := match pick (λ el : α, el ≠ 0) A with | none := (1, 1, 0) | some (i, j) := let B := (swap 0 i).to_pequiv.to_matrix ⬝ A ⬝ (swap 0 j).to_pequiv.to_matrix in let ur := (diagonal_ul 1 (x+1) 1).to_matrix ⬝ B ⬝ (diagonal_dr (y+1) y y).to_matrix in let dl := (A i j)⁻¹ • (diagonal_dr x (x+1) x).to_matrix ⬝ B ⬝ (diagonal_ul (y+1) 1 1).to_matrix in let dr := (diagonal_dr x (x+1) x).to_matrix ⬝ B ⬝ (diagonal_dr (y+1) y y).to_matrix in let ⟨L, U, r⟩ := Gaussian_elimination (dr - dl ⬝ ur) in --L ((swap 0 i).to_pequiv.to_matrix ⬝ ((single 0 0).to_matrix + (diagonal_dr (x+1) x x).to_matrix ⬝ (dl ⬝ (diagonal_ul 1 (x+1) 1).to_matrix + L ⬝ (diagonal_dr x (x+1) x).to_matrix)), --U (A i j • (single 0 0).to_matrix + ((diagonal_dr _ _ y).to_matrix ⬝ U + (diagonal_ul _ _ y).to_matrix ⬝ ur) ⬝ (diagonal_dr y (y+1) y).to_matrix) ⬝ (swap 0 j).to_pequiv.to_matrix, --r r+1) end | x y A := ((1 : matrix (fin x) (fin x) α), (1 : matrix (fin y) (fin y) α), 0) instance C {p : ℕ} (hp : nat.prime p) : has_repr (zmodp p hp) := fin.has_repr _ instance matrix.has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) := ⟨λ f, repr (vector.of_fn f).to_list⟩ instance {m n} {α : Type*} [has_repr α]: has_repr (matrix (fin m) (fin n) α) := matrix.has_repr_fin_fun def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ := λ i j, (l.nth_le i sorry).nth_le j sorry #eval ((diagonal_ul 5 4 3).to_matrix : matrix _ _ ℚ) def M := list.to_matrix 2 4 [[1,2,1,0], [4,5,0,1]] #eval let S := Gaussian_elimination M in S.1 ⬝ (list.to_matrix 2 4 [[1,0,0,0], [0,1,0,0]]) ⬝ S.2.1
28c506caa638d89366707b3e20ef116b05f8e44a
874a8d2247ab9a4516052498f80da2e32d0e3a48
/euler.lean
ae5095ae23a4ffdb1dba76ca6b0415a4058e533f
[]
no_license
AlexKontorovich/Spring2020Math492
378b36c643ee029f5ab91c1677889baa591f5e85
659108c5d864ff5c75b9b3b13b847aa5cff4348a
refs/heads/master
1,610,780,595,457
1,588,174,859,000
1,588,174,859,000
243,017,788
0
1
null
null
null
null
UTF-8
Lean
false
false
6,409
lean
import analysis.normed_space.basic import topology.instances.ennreal import analysis.normed_space.basic import topology.instances.ennreal import algebra.archimedean algebra.geom_sum import data.nat.choose data.complex.basic import tactic.linarith import analysis.calculus.deriv import data.complex.exponential open finset open cau_seq namespace complex noncomputable theory lemma is_cau_abs_cos (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs ( ((-1) ^ m) * z ^ (2 * m ) / nat.fact (2 * m )))) := begin sorry, end lemma is_cau_abs_sin (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs ( ((-1) ^ m) * z ^ (2 * m + 1) / nat.fact (2 * m + 1)))) := begin sorry, /- let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) -/ end lemma is_cau_sin (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, ((-1) ^ m) * z ^ (2 * m + 1) / nat.fact (2 * m + 1))) := begin exact is_cau_series_of_abv_cau (is_cau_abs_sin z), end lemma is_cau_cos (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, ((-1) ^ m) * z ^ (2 * m ) / nat.fact (2 * m))) := begin exact is_cau_series_of_abv_cau (is_cau_abs_cos z), end def sin' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, ((-1) ^ m) * z ^ (2 * m + 1) / nat.fact (2 * m + 1)), is_cau_sin z⟩ def sin1 (z : ℂ) : ℂ := lim (sin' z) def cos' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, (-1) ^ m * z ^ (2 * m) / nat.fact (2 * m)), is_cau_cos z⟩ def cos1 (z : ℂ) : ℂ := lim (cos' z) theorem euler : ∀ x, exp (x * I) = cos1 x + sin1 x * I := begin intros, have partials: ∀ n:ℕ , (exp' (x*I)).1 (2*n+1) = (cos' x).1 (n+1) + ((sin' x).1 n) * I, { intros, rw exp', simp, rw cos', simp, rw sin', simp, induction n with n0 hn, { -- case n0=0 simp, -- simp, }, { -- induction on n0 rw sum_range_succ _ _, -- takes out last term in cos have lastSin : sum (range (nat.succ n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (1 + 2 * x_1) / ↑(nat.fact (1 + 2 * x_1))) = (-1) ^ n0 * x ^ (1 + 2 * n0) / ↑(nat.fact (1 + 2 * n0)) + sum (range (n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (1 + 2 * x_1) / ↑(nat.fact (1 + 2 * x_1))) , { rw sum_range_succ _ _, }, have sinFactorial : sum (range (nat.succ n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (2 * x_1 + 1) / ((2 * ↑x_1 + 1) * ↑(nat.fact (2 * x_1)))) = sum (range (nat.succ n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (1 + 2 * x_1) / ↑(nat.fact (1 + 2 * x_1))), { sorry, --lean should fuckin know this! }, rw sinFactorial, rw lastSin, have twoFromExp: sum (range (nat.succ (2 * nat.succ n0))) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) = (x * I) ^ ( 2 * nat.succ n0) / ↑(nat.fact ( 2 * nat.succ n0))+ sum (range ( 2 * nat.succ n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) , { rw sum_range_succ _ ( 2 * nat.succ n0), }, have twoFromExpv1 : (x * I) ^ ( 2 * nat.succ n0) / ↑(nat.fact ( 2 * nat.succ n0))+sum (range ( 2 * nat.succ n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) = sum (range (nat.succ (2 * nat.succ n0))) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)), { by exact eq.symm twoFromExp, }, have twoNP1 : 1+ (2 * nat.succ n0) =nat.succ (2 * nat.succ n0) , { exact add_comm 1 (2 * nat.succ n0), }, have twoNP1v1 : nat.succ ( 2 * nat.succ n0) = 1 + (2 * nat.succ n0), { by exact eq.symm twoNP1, }, --rw twoNP1v1, rw twoFromExpv1, have oneFromExp: sum (range (2 * nat.succ n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) = (x * I) ^ (1+2 * n0) / ↑(nat.fact (1+2 * n0)) + sum (range (1+ 2 * n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) , { have stupid : 2 * nat.succ n0 = nat.succ(1+2*n0), { have RRS : nat.succ(1+2*n0) = 1+(1+2*n0) , { sorry, }, rw RRS, have realSt : 1+(1+2*n0) = 1+1+2*n0, { simp, }, rw realSt, exact nat.add_comm (nat.mul 2 n0) 2, }, rw stupid, rw sum_range_succ _ (1 + 2 * n0), }, --rw oneFromExp, --rw hn, --simp, -- need (x*I)^(2 n0 )= x^(2n0) (-1)^n0 etc, commutativity sorry, --ring, }, }, have partialExp : lim (exp' (x * I)) = exp (x*I), { sorry, }, have pulled_outta_my_derriere : ∀ (n : ℕ), (cos' x).val (n + 1) = cos1 x, { sorry, }, rw exp, rw partialExp, -- Now: need to take limits on both sides, they're same, -- but need to convince Lean that limit of exp' (2n+1) is same as -- limit of exp' (n) which is what exp is defined to be end end complex
9b8990f3609f8ea60c2de46dd087b05d7399af62
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Data/Lsp/Internal.lean
d8e3b1cd0a8d5a0238b123d1bbc608828042370c
[ "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
3,029
lean
/- Copyright (c) 2022 Joscha Mennicken. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joscha Mennicken -/ import Lean.Expr import Lean.Data.Lsp.Basic /-! This file contains types for communication between the watchdog and the workers. These messages are not visible externally to users of the LSP server. -/ namespace Lean.Lsp /-! Most reference-related types have custom FromJson/ToJson implementations to reduce the size of the resulting JSON. -/ inductive RefIdent where | const : Name → RefIdent | fvar : FVarId → RefIdent deriving BEq, Hashable, Inhabited namespace RefIdent def toString : RefIdent → String | RefIdent.const n => s!"c:{n}" | RefIdent.fvar id => s!"f:{id.name}" def fromString (s : String) : Except String RefIdent := do let sPrefix := s.take 2 let sName := s.drop 2 -- See `FromJson Name` let name ← match sName with | "[anonymous]" => pure Name.anonymous | _ => match Syntax.decodeNameLit ("`" ++ sName) with | some n => pure n | none => throw s!"expected a Name, got {sName}" match sPrefix with | "c:" => return RefIdent.const name | "f:" => return RefIdent.fvar <| FVarId.mk name | _ => throw "string must start with 'c:' or 'f:'" end RefIdent structure RefInfo where definition : Option Lsp.Range usages : Array Lsp.Range instance : ToJson RefInfo where toJson i := let rangeToList (r : Lsp.Range) : List Nat := [r.start.line, r.start.character, r.end.line, r.end.character] Json.mkObj [ ("definition", toJson $ i.definition.map rangeToList), ("usages", toJson $ i.usages.map rangeToList) ] instance : FromJson RefInfo where fromJson? j := do let listToRange (l : List Nat) : Except String Lsp.Range := match l with | [sLine, sChar, eLine, eChar] => pure ⟨⟨sLine, sChar⟩, ⟨eLine, eChar⟩⟩ | _ => throw s!"Expected list of length 4, not {l.length}" let definition ← j.getObjValAs? (Option $ List Nat) "definition" let definition ← match definition with | none => pure none | some list => some <$> listToRange list let usages ← j.getObjValAs? (Array $ List Nat) "usages" let usages ← usages.mapM listToRange pure { definition, usages } /-- References from a single module/file -/ def ModuleRefs := HashMap RefIdent RefInfo instance : ToJson ModuleRefs where toJson m := Json.mkObj <| m.toList.map fun (ident, info) => (ident.toString, toJson info) instance : FromJson ModuleRefs where fromJson? j := do let node ← j.getObj? node.foldM (init := HashMap.empty) fun m k v => return m.insert (← RefIdent.fromString k) (← fromJson? v) /-- `$/lean/ileanInfoUpdate` and `$/lean/ileanInfoFinal` watchdog<-worker notifications. Contains the file's definitions and references. -/ structure LeanIleanInfoParams where /-- Version of the file these references are from. -/ version : Nat references : ModuleRefs deriving FromJson, ToJson end Lean.Lsp
1317accd1ad85e5495939b551f617d7d5b83b539
9dc8cecdf3c4634764a18254e94d43da07142918
/archive/100-theorems-list/45_partition.lean
8661c762b129b8999f1a1e5d67438e52ad0bf584
[ "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
21,115
lean
/- Copyright (c) 2020 Bhavik Mehta, Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Aaron Anderson -/ import ring_theory.power_series.basic import combinatorics.partition import data.nat.parity import data.finset.nat_antidiagonal import data.fin.tuple.nat_antidiagonal import tactic.interval_cases import tactic.apply_fun import tactic.congrm /-! # Euler's Partition Theorem This file proves Theorem 45 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). The theorem concerns the counting of integer partitions -- ways of writing a positive integer `n` as a sum of positive integer parts. Specifically, Euler proved that the number of integer partitions of `n` into *distinct* parts equals the number of partitions of `n` into *odd* parts. ## Proof outline The proof is based on the generating functions for odd and distinct partitions, which turn out to be equal: $$\prod_{i=0}^\infty \frac {1}{1-X^{2i+1}} = \prod_{i=0}^\infty (1+X^{i+1})$$ In fact, we do not take a limit: it turns out that comparing the `n`'th coefficients of the partial products up to `m := n + 1` is sufficient. In particular, we 1. define the partial product for the generating function for odd partitions `partial_odd_gf m` := $$\prod_{i=0}^m \frac {1}{1-X^{2i+1}}$$; 2. prove `odd_gf_prop`: if `m` is big enough (`m * 2 > n`), the partial product's coefficient counts the number of odd partitions; 3. define the partial product for the generating function for distinct partitions `partial_distinct_gf m` := $$\prod_{i=0}^m (1+X^{i+1})$$; 4. prove `distinct_gf_prop`: if `m` is big enough (`m + 1 > n`), the `n`th coefficient of the partial product counts the number of distinct partitions of `n`; 5. prove `same_coeffs`: if m is big enough (`m ≥ n`), the `n`th coefficient of the partial products are equal; 6. combine the above in `partition_theorem`. ## References https://en.wikipedia.org/wiki/Partition_(number_theory)#Odd_parts_and_distinct_parts -/ open power_series noncomputable theory variables {α : Type*} open finset open_locale big_operators open_locale classical /-- The partial product for the generating function for odd partitions. TODO: As `m` tends to infinity, this converges (in the `X`-adic topology). If `m` is sufficiently large, the `i`th coefficient gives the number of odd partitions of the natural number `i`: proved in `odd_gf_prop`. It is stated for an arbitrary field `α`, though it usually suffices to use `ℚ` or `ℝ`. -/ def partial_odd_gf (m : ℕ) [field α] := ∏ i in range m, (1 - (X : power_series α)^(2*i+1))⁻¹ /-- The partial product for the generating function for distinct partitions. TODO: As `m` tends to infinity, this converges (in the `X`-adic topology). If `m` is sufficiently large, the `i`th coefficient gives the number of distinct partitions of the natural number `i`: proved in `distinct_gf_prop`. It is stated for an arbitrary commutative semiring `α`, though it usually suffices to use `ℕ`, `ℚ` or `ℝ`. -/ def partial_distinct_gf (m : ℕ) [comm_semiring α] := ∏ i in range m, (1 + (X : power_series α)^(i+1)) /-- Functions defined only on `s`, which sum to `n`. In other words, a partition of `n` indexed by `s`. Every function in here is finitely supported, and the support is a subset of `s`. This should be thought of as a generalisation of `finset.nat.antidiagonal_tuple` where `antidiagonal_tuple k n` is the same thing as `cut (s : finset.univ (fin k)) n`. -/ def cut {ι : Type*} (s : finset ι) (n : ℕ) : finset (ι → ℕ) := finset.filter (λ f, s.sum f = n) ((s.pi (λ _, range (n+1))).map ⟨λ f i, if h : i ∈ s then f i h else 0, λ f g h, by { ext i hi, simpa [dif_pos hi] using congr_fun h i }⟩) lemma mem_cut {ι : Type*} (s : finset ι) (n : ℕ) (f : ι → ℕ) : f ∈ cut s n ↔ s.sum f = n ∧ ∀ i ∉ s, f i = 0 := begin rw [cut, mem_filter, and_comm, and_congr_right], intro h, simp only [mem_map, exists_prop, function.embedding.coe_fn_mk, mem_pi], split, { rintro ⟨_, _, rfl⟩ _ _, simp [dif_neg H] }, { intro hf, refine ⟨λ i hi, f i, λ i hi, _, _⟩, { rw [mem_range, nat.lt_succ_iff, ← h], apply single_le_sum _ hi, simp }, { ext, rw [dite_eq_ite, ite_eq_left_iff, eq_comm], exact hf x } } end lemma cut_equiv_antidiag (n : ℕ) : equiv.finset_congr (equiv.bool_arrow_equiv_prod _) (cut univ n) = nat.antidiagonal n := begin ext ⟨x₁, x₂⟩, simp_rw [equiv.finset_congr_apply, mem_map, equiv.to_embedding, function.embedding.coe_fn_mk, ←equiv.eq_symm_apply], simp [mem_cut, add_comm], end lemma cut_univ_fin_eq_antidiagonal_tuple (n : ℕ) (k : ℕ) : cut univ n = nat.antidiagonal_tuple k n := by { ext, simp [nat.mem_antidiagonal_tuple, mem_cut] } /-- There is only one `cut` of 0. -/ @[simp] lemma cut_zero {ι : Type*} (s : finset ι) : cut s 0 = {0} := begin -- In general it's nice to prove things using `mem_cut` but in this case it's easier to just -- use the definition. rw [cut, range_one, pi_const_singleton, map_singleton, function.embedding.coe_fn_mk, filter_singleton, if_pos, singleton_inj], { ext, split_ifs; refl }, rw sum_eq_zero_iff, intros x hx, apply dif_pos hx, end @[simp] lemma cut_empty_succ {ι : Type*} (n : ℕ) : cut (∅ : finset ι) (n+1) = ∅ := begin apply eq_empty_of_forall_not_mem, intros x hx, rw [mem_cut, sum_empty] at hx, cases hx.1, end lemma cut_insert {ι : Type*} (n : ℕ) (a : ι) (s : finset ι) (h : a ∉ s) : cut (insert a s) n = (nat.antidiagonal n).bUnion (λ (p : ℕ × ℕ), (cut s p.snd).map ⟨λ f, f + λ t, if t = a then p.fst else 0, add_left_injective _⟩) := begin ext f, rw [mem_cut, mem_bUnion, sum_insert h], split, { rintro ⟨rfl, h₁⟩, simp only [exists_prop, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists], refine ⟨f a, s.sum f, rfl, λ i, if i = a then 0 else f i, _, _⟩, { rw [mem_cut], refine ⟨_, _⟩, { rw [sum_ite], have : (filter (λ x, x ≠ a) s) = s, { apply filter_true_of_mem, rintro i hi rfl, apply h hi }, simp [this] }, { intros i hi, rw ite_eq_left_iff, intro hne, apply h₁, simp [not_or_distrib, hne, hi] } }, { ext, obtain rfl|h := eq_or_ne x a, { simp }, { simp [if_neg h] } } }, { simp only [mem_insert, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists, exists_prop, mem_cut, not_or_distrib], rintro ⟨p, q, rfl, g, ⟨rfl, hg₂⟩, rfl⟩, refine ⟨_, _⟩, { simp [sum_add_distrib, if_neg h, hg₂ _ h, add_comm] }, { rintro i ⟨h₁, h₂⟩, simp [if_neg h₁, hg₂ _ h₂] } } end lemma coeff_prod_range [comm_semiring α] {ι : Type*} (s : finset ι) (f : ι → power_series α) (n : ℕ) : coeff α n (∏ j in s, f j) = ∑ l in cut s n, ∏ i in s, coeff α (l i) (f i) := begin revert n, apply finset.induction_on s, { rintro ⟨_ | n⟩, { simp }, simp [cut_empty_succ, if_neg (nat.succ_ne_zero _)] }, intros a s hi ih n, rw [cut_insert _ _ _ hi, prod_insert hi, coeff_mul, sum_bUnion], { congrm finset.sum _ (λ i, _), simp only [sum_map, pi.add_apply, function.embedding.coe_fn_mk, prod_insert hi, if_pos rfl, ih, mul_sum], apply sum_congr rfl _, intros x hx, rw mem_cut at hx, rw [hx.2 a hi, zero_add], congrm _ * _, apply prod_congr rfl, intros k hk, rw [if_neg, add_zero], exact ne_of_mem_of_not_mem hk hi }, { simp only [set.pairwise_disjoint, set.pairwise, prod.forall, not_and, ne.def, nat.mem_antidiagonal, disjoint_left, mem_map, exists_prop, function.embedding.coe_fn_mk, exists_imp_distrib, not_exists, finset.mem_coe], rintro p₁ q₁ rfl p₂ q₂ h t x hx, simp only [finset.inf_eq_inter, finset.mem_map, finset.mem_inter, mem_cut, exists_prop, function.embedding.coe_fn_mk] at hx, rcases hx with ⟨⟨p, ⟨hp, hp2⟩, hp3⟩, ⟨q, ⟨hq, hq2⟩, hq3⟩⟩, have z := hp3.trans hq3.symm, have := sum_congr (eq.refl s) (λ x _, function.funext_iff.1 z x), obtain rfl : q₁ = q₂, { simpa [sum_add_distrib, hp, hq, if_neg hi] using this }, obtain rfl : p₂ = p₁, { simpa using h }, exact (t rfl).elim } end /-- A convenience constructor for the power series whose coefficients indicate a subset. -/ def indicator_series (α : Type*) [semiring α] (s : set ℕ) : power_series α := power_series.mk (λ n, if n ∈ s then 1 else 0) lemma coeff_indicator (s : set ℕ) [semiring α] (n : ℕ) : coeff α n (indicator_series _ s) = if n ∈ s then 1 else 0 := coeff_mk _ _ lemma coeff_indicator_pos (s : set ℕ) [semiring α] (n : ℕ) (h : n ∈ s): coeff α n (indicator_series _ s) = 1 := by rw [coeff_indicator, if_pos h] lemma coeff_indicator_neg (s : set ℕ) [semiring α] (n : ℕ) (h : n ∉ s): coeff α n (indicator_series _ s) = 0 := by rw [coeff_indicator, if_neg h] lemma constant_coeff_indicator (s : set ℕ) [semiring α] : constant_coeff α (indicator_series _ s) = if 0 ∈ s then 1 else 0 := rfl lemma two_series (i : ℕ) [semiring α] : (1 + (X : power_series α)^i.succ) = indicator_series α {0, i.succ} := begin ext, simp only [coeff_indicator, coeff_one, coeff_X_pow, set.mem_insert_iff, set.mem_singleton_iff, map_add], cases n with d, { simp [(nat.succ_ne_zero i).symm] }, { simp [nat.succ_ne_zero d], }, end lemma num_series' [field α] (i : ℕ) : (1 - (X : power_series α)^(i+1))⁻¹ = indicator_series α { k | i + 1 ∣ k } := begin rw power_series.inv_eq_iff_mul_eq_one, { ext, cases n, { simp [mul_sub, zero_pow, constant_coeff_indicator] }, { simp only [coeff_one, if_neg n.succ_ne_zero, mul_sub, mul_one, coeff_indicator, linear_map.map_sub], simp_rw [coeff_mul, coeff_X_pow, coeff_indicator, boole_mul, sum_ite, filter_filter, sum_const_zero, add_zero, sum_const, nsmul_eq_mul, mul_one, sub_eq_iff_eq_add, zero_add, filter_congr_decidable], symmetry, split_ifs, { suffices : ((nat.antidiagonal n.succ).filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1)).card = 1, { simp only [set.mem_set_of_eq], rw this, norm_cast }, rw card_eq_one, cases h with p hp, refine ⟨((i+1) * (p-1), i+1), _⟩, ext ⟨a₁, a₂⟩, simp only [mem_filter, prod.mk.inj_iff, nat.mem_antidiagonal, mem_singleton], split, { rintro ⟨a_left, ⟨a, rfl⟩, rfl⟩, refine ⟨_, rfl⟩, rw [nat.mul_sub_left_distrib, ← hp, ← a_left, mul_one, nat.add_sub_cancel] }, { rintro ⟨rfl, rfl⟩, cases p, { rw mul_zero at hp, cases hp }, rw hp, simp [nat.succ_eq_add_one, mul_add] } }, { suffices : (filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1) (nat.antidiagonal n.succ)).card = 0, { simp only [set.mem_set_of_eq], rw this, norm_cast }, rw card_eq_zero, apply eq_empty_of_forall_not_mem, simp only [prod.forall, mem_filter, not_and, nat.mem_antidiagonal], rintro _ h₁ h₂ ⟨a, rfl⟩ rfl, apply h, simp [← h₂] } } }, { simp [zero_pow] }, end def mk_odd : ℕ ↪ ℕ := ⟨λ i, 2 * i + 1, λ x y h, by linarith⟩ -- The main workhorse of the partition theorem proof. lemma partial_gf_prop (α : Type*) [comm_semiring α] (n : ℕ) (s : finset ℕ) (hs : ∀ i ∈ s, 0 < i) (c : ℕ → set ℕ) (hc : ∀ i ∉ s, 0 ∈ c i) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, (∀ j, p.parts.count j ∈ c j) ∧ ∀ j ∈ p.parts, j ∈ s)) : α) = (coeff α n) (∏ (i : ℕ) in s, indicator_series α ((* i) '' c i)) := begin simp_rw [coeff_prod_range, coeff_indicator, prod_boole, sum_boole], congr' 1, refine finset.card_congr (λ p _ i, multiset.count i p.parts • i) _ _ _, { simp only [mem_filter, mem_cut, mem_univ, true_and, exists_prop, and_assoc, and_imp, smul_eq_zero, function.embedding.coe_fn_mk, exists_imp_distrib], rintro ⟨p, hp₁, hp₂⟩ hp₃ hp₄, dsimp only at *, refine ⟨_, _, _⟩, { rw [←hp₂, ←sum_multiset_count_of_subset p s (λ x hx, hp₄ _ (multiset.mem_to_finset.mp hx))] }, { intros i hi, left, exact multiset.count_eq_zero_of_not_mem (mt (hp₄ i) hi) }, { exact λ i hi, ⟨_, hp₃ i, rfl⟩ } }, { intros p₁ p₂ hp₁ hp₂ h, apply nat.partition.ext, simp only [true_and, mem_univ, mem_filter] at hp₁ hp₂, ext i, rw function.funext_iff at h, specialize h i, cases i, { rw multiset.count_eq_zero_of_not_mem, rw multiset.count_eq_zero_of_not_mem, intro a, exact nat.lt_irrefl 0 (hs 0 (hp₂.2 0 a)), intro a, exact nat.lt_irrefl 0 (hs 0 (hp₁.2 0 a)) }, { rwa [nat.nsmul_eq_mul, nat.nsmul_eq_mul, nat.mul_left_inj i.succ_pos] at h } }, { simp only [mem_filter, mem_cut, mem_univ, exists_prop, true_and, and_assoc], rintros f ⟨hf₁, hf₂, hf₃⟩, refine ⟨⟨∑ i in s, multiset.repeat i (f i / i), _, _⟩, _, _, _⟩, { intros i hi, simp only [exists_prop, mem_sum, mem_map, function.embedding.coe_fn_mk] at hi, rcases hi with ⟨t, ht, z⟩, apply hs, rwa multiset.eq_of_mem_repeat z }, { simp_rw [multiset.sum_sum, multiset.sum_repeat, nat.nsmul_eq_mul, ←hf₁], refine sum_congr rfl (λ i hi, nat.div_mul_cancel _), rcases hf₃ i hi with ⟨w, hw, hw₂⟩, rw ← hw₂, exact dvd_mul_left _ _ }, { intro i, simp_rw [multiset.count_sum', multiset.count_repeat, sum_ite_eq], split_ifs with h h, { rcases hf₃ i h with ⟨w, hw₁, hw₂⟩, rwa [← hw₂, nat.mul_div_cancel _ (hs i h)] }, { exact hc _ h } }, { intros i hi, rw mem_sum at hi, rcases hi with ⟨j, hj₁, hj₂⟩, rwa multiset.eq_of_mem_repeat hj₂ }, { ext i, simp_rw [multiset.count_sum', multiset.count_repeat, sum_ite_eq], split_ifs, { apply nat.div_mul_cancel, rcases hf₃ i h with ⟨w, hw, hw₂⟩, apply dvd.intro_left _ hw₂ }, { rw [zero_smul, hf₂ i h] } } }, end lemma partial_odd_gf_prop [field α] (n m : ℕ) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, ∀ j ∈ p.parts, j ∈ (range m).map mk_odd)) : α) = coeff α n (partial_odd_gf m) := begin rw partial_odd_gf, convert partial_gf_prop α n ((range m).map mk_odd) _ (λ _, set.univ) (λ _ _, trivial) using 2, { congrm card (filter (λ p, _) _), simp only [true_and, forall_const, set.mem_univ] }, { rw finset.prod_map, simp_rw num_series', congrm finset.prod _ (λ x, indicator_series α _), ext k, split, { rintro ⟨p, rfl⟩, refine ⟨p, ⟨⟩, _⟩, apply mul_comm }, rintro ⟨a_w, -, rfl⟩, apply dvd.intro_left a_w rfl }, { intro i, rw mem_map, rintro ⟨a, -, rfl⟩, exact nat.succ_pos _ }, end /-- If m is big enough, the partial product's coefficient counts the number of odd partitions -/ theorem odd_gf_prop [field α] (n m : ℕ) (h : n < m * 2) : (finset.card (nat.partition.odds n) : α) = coeff α n (partial_odd_gf m) := begin rw [← partial_odd_gf_prop], congrm card (filter (λ p, (_ : Prop)) _), apply ball_congr, intros i hi, have hin : i ≤ n, { simpa [p.parts_sum] using multiset.single_le_sum (λ _ _, nat.zero_le _) _ hi }, simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map], split, { intro hi₂, have := nat.mod_add_div i 2, rw nat.not_even_iff at hi₂, rw [hi₂, add_comm] at this, refine ⟨i / 2, _, this⟩, rw nat.div_lt_iff_lt_mul zero_lt_two, exact lt_of_le_of_lt hin h }, { rintro ⟨a, -, rfl⟩, rw even_iff_two_dvd, apply nat.two_not_dvd_two_mul_add_one }, end lemma partial_distinct_gf_prop [comm_semiring α] (n m : ℕ) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, p.parts.nodup ∧ ∀ j ∈ p.parts, j ∈ (range m).map ⟨nat.succ, nat.succ_injective⟩)) : α) = coeff α n (partial_distinct_gf m) := begin rw partial_distinct_gf, convert partial_gf_prop α n ((range m).map ⟨nat.succ, nat.succ_injective⟩) _ (λ _, {0, 1}) (λ _ _, or.inl rfl) using 2, { congrm card (filter (λ p, _ ∧ _) _), rw multiset.nodup_iff_count_le_one, congrm ∀ (i : ℕ), (_ : Prop), rcases multiset.count i p.parts with _|_|ms; simp }, { simp_rw [finset.prod_map, two_series], congrm finset.prod _ (λ i, indicator_series _ _), simp [set.image_pair] }, { simp only [mem_map, function.embedding.coe_fn_mk], rintro i ⟨_, _, rfl⟩, apply nat.succ_pos } end /-- If m is big enough, the partial product's coefficient counts the number of distinct partitions -/ theorem distinct_gf_prop [comm_semiring α] (n m : ℕ) (h : n < m + 1) : ((nat.partition.distincts n).card : α) = coeff α n (partial_distinct_gf m) := begin erw [← partial_distinct_gf_prop], congrm card (filter (λ p, _) _), apply (and_iff_left _).symm, intros i hi, have : i ≤ n, { simpa [p.parts_sum] using multiset.single_le_sum (λ _ _, nat.zero_le _) _ hi }, simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map], refine ⟨i-1, _, nat.succ_pred_eq_of_pos (p.parts_pos hi)⟩, rw tsub_lt_iff_right (nat.one_le_iff_ne_zero.mpr (p.parts_pos hi).ne'), exact lt_of_le_of_lt this h, end /-- The key proof idea for the partition theorem, showing that the generating functions for both sequences are ultimately the same (since the factor converges to 0 as m tends to infinity). It's enough to not take the limit though, and just consider large enough `m`. -/ lemma same_gf [field α] (m : ℕ) : partial_odd_gf m * (range m).prod (λ i, (1 - (X : power_series α)^(m+i+1))) = partial_distinct_gf m := begin rw [partial_odd_gf, partial_distinct_gf], induction m with m ih, { simp }, rw nat.succ_eq_add_one, set π₀ : power_series α := ∏ i in range m, (1 - X ^ (m + 1 + i + 1)) with hπ₀, set π₁ : power_series α := ∏ i in range m, (1 - X ^ (2 * i + 1))⁻¹ with hπ₁, set π₂ : power_series α := ∏ i in range m, (1 - X ^ (m + i + 1)) with hπ₂, set π₃ : power_series α := ∏ i in range m, (1 + X ^ (i + 1)) with hπ₃, rw ←hπ₃ at ih, have h : constant_coeff α (1 - X ^ (2 * m + 1)) ≠ 0, { rw [ring_hom.map_sub, ring_hom.map_pow, constant_coeff_one, constant_coeff_X, zero_pow (2 * m).succ_pos, sub_zero], exact one_ne_zero }, calc (∏ i in range (m + 1), (1 - X ^ (2 * i + 1))⁻¹) * ∏ i in range (m + 1), (1 - X ^ (m + 1 + i + 1)) = π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * (1 - X ^ (m + 1 + m + 1))) : by rw [prod_range_succ _ m, ←hπ₁, prod_range_succ _ m, ←hπ₀] ... = π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * ((1 + X ^ (m + 1)) * (1 - X ^ (m + 1)))) : by rw [←sq_sub_sq, one_pow, add_assoc _ m 1, ←two_mul (m + 1), pow_mul'] ... = π₀ * (1 - X ^ (m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by ring ... = (∏ i in range (m + 1), (1 - X ^ (m + 1 + i))) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by { rw [prod_range_succ', add_zero, hπ₀], simp_rw ←add_assoc } ... = π₂ * (1 - X ^ (m + 1 + m)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by { rw [add_right_comm, hπ₂, ←prod_range_succ], simp_rw [add_right_comm] } ... = π₂ * (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by rw [two_mul, add_right_comm _ m 1] ... = (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * π₂ * (π₁ * (1 + X ^ (m + 1))) : by ring ... = π₂ * (π₁ * (1 + X ^ (m + 1))) : by rw [power_series.mul_inv_cancel _ h, one_mul] ... = π₁ * π₂ * (1 + X ^ (m + 1)) : by ring ... = π₃ * (1 + X ^ (m + 1)) : by rw ih ... = _ : by rw prod_range_succ, end lemma same_coeffs [field α] (m n : ℕ) (h : n ≤ m) : coeff α n (partial_odd_gf m) = coeff α n (partial_distinct_gf m) := begin rw [← same_gf, coeff_mul_prod_one_sub_of_lt_order], rintros i -, rw order_X_pow, exact_mod_cast nat.lt_succ_of_le (le_add_right h), end theorem partition_theorem (n : ℕ) : (nat.partition.odds n).card = (nat.partition.distincts n).card := begin -- We need the counts to live in some field (which contains ℕ), so let's just use ℚ suffices : ((nat.partition.odds n).card : ℚ) = (nat.partition.distincts n).card, { exact_mod_cast this }, rw distinct_gf_prop n (n+1) (by linarith), rw odd_gf_prop n (n+1) (by linarith), apply same_coeffs (n+1) n n.le_succ, end
347dd014e2afc8a7436ec685810ff909f9c860d9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/cast_auto.lean
00afeaefca542f32e890be2011a91a14da4366a7
[]
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
11,683
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ordered_field import Mathlib.data.nat.basic import Mathlib.PostPort universes u_1 u_2 namespace Mathlib namespace nat /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast {α : Type u_1} [HasZero α] [HasOne α] [Add α] : ℕ → α := sorry /-- Computationally friendlier cast than `nat.cast`, using binary representation. -/ protected def bin_cast {α : Type u_1} [HasZero α] [HasOne α] [Add α] (n : ℕ) : α := binary_rec 0 (fun (odd : Bool) (k : ℕ) (a : α) => cond odd (a + a + 1) (a + a)) n /-- Coercions such as `nat.cast_coe` that go from a concrete structure such as `ℕ` to an arbitrary ring `α` should be set up as follows: ```lean @[priority 900] instance : has_coe_t ℕ α := ⟨...⟩ ``` It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`. The reduced priority is necessary so that it doesn't conflict with instances such as `has_coe_t α (option α)`. For this to work, we reduce the priority of the `coe_base` and `coe_trans` instances because we want the instances for `has_coe_t` to be tried in the following order: 1. `has_coe_t` instances declared in mathlib (such as `has_coe_t α (with_top α)`, etc.) 2. `coe_base`, which contains instances such as `has_coe (fin n) n` 3. `nat.cast_coe : has_coe_t ℕ α` etc. 4. `coe_trans` If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply. -/ -- see note [coercion into rings] protected instance cast_coe {α : Type u_1} [HasZero α] [HasOne α] [Add α] : has_coe_t ℕ α := has_coe_t.mk nat.cast @[simp] theorem cast_zero {α : Type u_1} [HasZero α] [HasOne α] [Add α] : ↑0 = 0 := rfl theorem cast_add_one {α : Type u_1} [HasZero α] [HasOne α] [Add α] (n : ℕ) : ↑(n + 1) = ↑n + 1 := rfl @[simp] theorem cast_succ {α : Type u_1} [HasZero α] [HasOne α] [Add α] (n : ℕ) : ↑(Nat.succ n) = ↑n + 1 := rfl @[simp] theorem cast_ite {α : Type u_1} [HasZero α] [HasOne α] [Add α] (P : Prop) [Decidable P] (m : ℕ) (n : ℕ) : ↑(ite P m n) = ite P ↑m ↑n := sorry @[simp] theorem cast_one {α : Type u_1} [add_monoid α] [HasOne α] : ↑1 = 1 := zero_add 1 @[simp] theorem cast_add {α : Type u_1} [add_monoid α] [HasOne α] (m : ℕ) (n : ℕ) : ↑(m + n) = ↑m + ↑n := sorry @[simp] theorem bin_cast_eq {α : Type u_1} [add_monoid α] [HasOne α] (n : ℕ) : nat.bin_cast n = ↑n := sorry /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type u_1) [add_monoid α] [HasOne α] : ℕ →+ α := add_monoid_hom.mk coe sorry cast_add @[simp] theorem coe_cast_add_monoid_hom {α : Type u_1} [add_monoid α] [HasOne α] : ⇑(cast_add_monoid_hom α) = coe := rfl @[simp] theorem cast_bit0 {α : Type u_1} [add_monoid α] [HasOne α] (n : ℕ) : ↑(bit0 n) = bit0 ↑n := cast_add n n @[simp] theorem cast_bit1 {α : Type u_1} [add_monoid α] [HasOne α] (n : ℕ) : ↑(bit1 n) = bit1 ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (↑(bit1 n) = bit1 ↑n)) (bit1.equations._eqn_1 n))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(bit0 n + 1) = bit1 ↑n)) (cast_add_one (bit0 n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(bit0 n) + 1 = bit1 ↑n)) (cast_bit0 n))) (Eq.refl (bit0 ↑n + 1)))) theorem cast_two {α : Type u_1} [add_monoid α] [HasOne α] : ↑(bit0 1) = bit0 1 := sorry @[simp] theorem cast_pred {α : Type u_1} [add_group α] [HasOne α] {n : ℕ} : 0 < n → ↑(n - 1) = ↑n - 1 := sorry @[simp] theorem cast_sub {α : Type u_1} [add_group α] [HasOne α] {m : ℕ} {n : ℕ} (h : m ≤ n) : ↑(n - m) = ↑n - ↑m := eq_sub_of_add_eq (eq.mpr (id (Eq._oldrec (Eq.refl (↑(n - m) + ↑m = ↑n)) (Eq.symm (cast_add (n - m) m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(n - m + m) = ↑n)) (nat.sub_add_cancel h))) (Eq.refl ↑n))) @[simp] theorem cast_mul {α : Type u_1} [semiring α] (m : ℕ) (n : ℕ) : ↑(m * n) = ↑m * ↑n := sorry @[simp] theorem cast_dvd {α : Type u_1} [field α] {m : ℕ} {n : ℕ} (n_dvd : n ∣ m) (n_nonzero : ↑n ≠ 0) : ↑(m / n) = ↑m / ↑n := sorry /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type u_1) [semiring α] : ℕ →+* α := ring_hom.mk coe sorry cast_mul sorry sorry @[simp] theorem coe_cast_ring_hom {α : Type u_1} [semiring α] : ⇑(cast_ring_hom α) = coe := rfl theorem cast_commute {α : Type u_1} [semiring α] (n : ℕ) (x : α) : commute (↑n) x := nat.rec_on n (commute.zero_left x) fun (n : ℕ) (ihn : commute (↑n) x) => commute.add_left ihn (commute.one_left x) theorem commute_cast {α : Type u_1} [semiring α] (x : α) (n : ℕ) : commute x ↑n := commute.symm (cast_commute n x) @[simp] theorem cast_nonneg {α : Type u_1} [ordered_semiring α] (n : ℕ) : 0 ≤ ↑n := sorry theorem mono_cast {α : Type u_1} [ordered_semiring α] : monotone coe := sorry theorem strict_mono_cast {α : Type u_1} [ordered_semiring α] [nontrivial α] : strict_mono coe := fun (m n : ℕ) (h : m < n) => le_induction (lt_add_of_pos_right (↑m) zero_lt_one) (fun (n : ℕ) (_x : Nat.succ m ≤ n) (h : ↑m < ↑n) => lt_add_of_lt_of_pos h zero_lt_one) n h @[simp] theorem cast_le {α : Type u_1} [ordered_semiring α] [nontrivial α] {m : ℕ} {n : ℕ} : ↑m ≤ ↑n ↔ m ≤ n := strict_mono.le_iff_le strict_mono_cast @[simp] theorem cast_lt {α : Type u_1} [ordered_semiring α] [nontrivial α] {m : ℕ} {n : ℕ} : ↑m < ↑n ↔ m < n := strict_mono.lt_iff_lt strict_mono_cast @[simp] theorem cast_pos {α : Type u_1} [ordered_semiring α] [nontrivial α] {n : ℕ} : 0 < ↑n ↔ 0 < n := eq.mpr (id (Eq._oldrec (Eq.refl (0 < ↑n ↔ 0 < n)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑0 < ↑n ↔ 0 < n)) (propext cast_lt))) (iff.refl (0 < n))) theorem cast_add_one_pos {α : Type u_1} [ordered_semiring α] [nontrivial α] (n : ℕ) : 0 < ↑n + 1 := add_pos_of_nonneg_of_pos (cast_nonneg n) zero_lt_one @[simp] theorem one_lt_cast {α : Type u_1} [ordered_semiring α] [nontrivial α] {n : ℕ} : 1 < ↑n ↔ 1 < n := eq.mpr (id (Eq._oldrec (Eq.refl (1 < ↑n ↔ 1 < n)) (Eq.symm cast_one))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑1 < ↑n ↔ 1 < n)) (propext cast_lt))) (iff.refl (1 < n))) @[simp] theorem one_le_cast {α : Type u_1} [ordered_semiring α] [nontrivial α] {n : ℕ} : 1 ≤ ↑n ↔ 1 ≤ n := eq.mpr (id (Eq._oldrec (Eq.refl (1 ≤ ↑n ↔ 1 ≤ n)) (Eq.symm cast_one))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑1 ≤ ↑n ↔ 1 ≤ n)) (propext cast_le))) (iff.refl (1 ≤ n))) @[simp] theorem cast_lt_one {α : Type u_1} [ordered_semiring α] [nontrivial α] {n : ℕ} : ↑n < 1 ↔ n = 0 := sorry @[simp] theorem cast_le_one {α : Type u_1} [ordered_semiring α] [nontrivial α] {n : ℕ} : ↑n ≤ 1 ↔ n ≤ 1 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n ≤ 1 ↔ n ≤ 1)) (Eq.symm cast_one))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n ≤ ↑1 ↔ n ≤ 1)) (propext cast_le))) (iff.refl (n ≤ 1))) @[simp] theorem cast_min {α : Type u_1} [linear_ordered_semiring α] {a : ℕ} {b : ℕ} : ↑(min a b) = min ↑a ↑b := sorry @[simp] theorem cast_max {α : Type u_1} [linear_ordered_semiring α] {a : ℕ} {b : ℕ} : ↑(max a b) = max ↑a ↑b := sorry @[simp] theorem abs_cast {α : Type u_1} [linear_ordered_ring α] (a : ℕ) : abs ↑a = ↑a := abs_of_nonneg (cast_nonneg a) theorem coe_nat_dvd {α : Type u_1} [comm_semiring α] {m : ℕ} {n : ℕ} (h : m ∣ n) : ↑m ∣ ↑n := ring_hom.map_dvd (cast_ring_hom α) h theorem Mathlib.has_dvd.dvd.nat_cast {α : Type u_1} [comm_semiring α] {m : ℕ} {n : ℕ} (h : m ∣ n) : ↑m ∣ ↑n := coe_nat_dvd theorem inv_pos_of_nat {α : Type u_1} [linear_ordered_field α] {n : ℕ} : 0 < (↑n + 1⁻¹) := iff.mpr inv_pos (add_pos_of_nonneg_of_pos (cast_nonneg n) zero_lt_one) theorem one_div_pos_of_nat {α : Type u_1} [linear_ordered_field α] {n : ℕ} : 0 < 1 / (↑n + 1) := eq.mpr (id (Eq._oldrec (Eq.refl (0 < 1 / (↑n + 1))) (one_div (↑n + 1)))) inv_pos_of_nat theorem one_div_le_one_div {α : Type u_1} [linear_ordered_field α] {n : ℕ} {m : ℕ} (h : n ≤ m) : 1 / (↑m + 1) ≤ 1 / (↑n + 1) := one_div_le_one_div_of_le (cast_add_one_pos n) (eq.mpr (id (Eq.trans (propext (add_le_add_iff_right 1)) (propext cast_le))) h) theorem one_div_lt_one_div {α : Type u_1} [linear_ordered_field α] {n : ℕ} {m : ℕ} (h : n < m) : 1 / (↑m + 1) < 1 / (↑n + 1) := one_div_lt_one_div_of_lt (cast_add_one_pos n) (eq.mpr (id (Eq.trans (propext (add_lt_add_iff_right 1)) (propext cast_lt))) h) end nat namespace add_monoid_hom theorem ext_nat {A : Type u_1} [add_monoid A] {f : ℕ →+ A} {g : ℕ →+ A} (h : coe_fn f 1 = coe_fn g 1) : f = g := sorry theorem eq_nat_cast {A : Type u_1} [add_monoid A] [HasOne A] (f : ℕ →+ A) (h1 : coe_fn f 1 = 1) (n : ℕ) : coe_fn f n = ↑n := congr_fun ((fun (this : f = nat.cast_add_monoid_hom A) => this) (ext_nat (Eq.trans h1 (Eq.symm nat.cast_one)))) theorem map_nat_cast {A : Type u_1} {B : Type u_2} [add_monoid A] [HasOne A] [add_monoid B] [HasOne B] (f : A →+ B) (h1 : coe_fn f 1 = 1) (n : ℕ) : coe_fn f ↑n = ↑n := sorry end add_monoid_hom namespace ring_hom @[simp] theorem eq_nat_cast {R : Type u_1} [semiring R] (f : ℕ →+* R) (n : ℕ) : coe_fn f n = ↑n := add_monoid_hom.eq_nat_cast (to_add_monoid_hom f) (map_one f) n @[simp] theorem map_nat_cast {R : Type u_1} {S : Type u_2} [semiring R] [semiring S] (f : R →+* S) (n : ℕ) : coe_fn f ↑n = ↑n := eq_nat_cast (comp f (nat.cast_ring_hom R)) n theorem ext_nat {R : Type u_1} [semiring R] (f : ℕ →+* R) (g : ℕ →+* R) : f = g := coe_add_monoid_hom_injective (add_monoid_hom.ext_nat (Eq.trans (map_one f) (Eq.symm (map_one g)))) end ring_hom @[simp] theorem nat.cast_id (n : ℕ) : ↑n = n := Eq.symm (ring_hom.eq_nat_cast (ring_hom.id ℕ) n) @[simp] theorem nat.cast_with_bot (n : ℕ) : ↑n = ↑n := sorry protected instance nat.subsingleton_ring_hom {R : Type u_1} [semiring R] : subsingleton (ℕ →+* R) := subsingleton.intro ring_hom.ext_nat namespace with_top @[simp] theorem coe_nat {α : Type u_1} [HasZero α] [HasOne α] [Add α] (n : ℕ) : ↑↑n = ↑n := sorry @[simp] theorem nat_ne_top {α : Type u_1} [HasZero α] [HasOne α] [Add α] (n : ℕ) : ↑n ≠ ⊤ := eq.mpr (id (Eq._oldrec (Eq.refl (↑n ≠ ⊤)) (Eq.symm (coe_nat n)))) coe_ne_top @[simp] theorem top_ne_nat {α : Type u_1} [HasZero α] [HasOne α] [Add α] (n : ℕ) : ⊤ ≠ ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (⊤ ≠ ↑n)) (Eq.symm (coe_nat n)))) top_ne_coe theorem add_one_le_of_lt {i : with_top ℕ} {n : with_top ℕ} (h : i < n) : i + 1 ≤ n := sorry theorem one_le_iff_pos {n : with_top ℕ} : 1 ≤ n ↔ 0 < n := sorry theorem nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ) (h0 : P 0) (hsuc : ∀ (n : ℕ), P ↑n → P ↑(Nat.succ n)) (htop : (∀ (n : ℕ), P ↑n) → P ⊤) : P a := option.cases_on a (htop fun (n : ℕ) => nat.rec_on n h0 hsuc) fun (a : ℕ) => (fun (n : ℕ) => nat.rec_on n h0 hsuc) a end Mathlib
1dec034e5531225bc4cfcc9edd240ab4f8b34045
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/abstract_ns1.lean
a4bee8c588a1bd3dc809edf4e6471ca0d50bb866
[ "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
170
lean
-- Companion file for the abstract_ns test. namespace ns1 def foo : fin 7 := ⟨3, dec_trivial⟩ def foo' : fin 7 := ⟨3, by abstract {exact dec_trivial}⟩ end ns1
f38f7e5770f0bfe1fd1dd62e66e1084f16872d06
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/calculus/fderiv_symmetric.lean
a4a4dab9b1e296bd486d2ce1fcea2d0ef033ef39
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
19,004
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv import analysis.calculus.mean_value import analysis.convex.topology /-! # Symmetry of the second derivative We show that, over the reals, the second derivative is symmetric. The most precise result is `convex.second_derivative_within_at_symmetric`. It asserts that, if a function is differentiable inside a convex set `s` with nonempty interior, and has a second derivative within `s` at a point `x`, then this second derivative at `x` is symmetric. Note that this result does not require continuity of the first derivative. The following particular cases of this statement are especially relevant: `second_derivative_symmetric_of_eventually` asserts that, if a function is differentiable on a neighborhood of `x`, and has a second derivative at `x`, then this second derivative is symmetric. `second_derivative_symmetric` asserts that, if a function is differentiable, and has a second derivative at `x`, then this second derivative is symmetric. ## Implementation note For the proof, we obtain an asymptotic expansion to order two of `f (x + v + w) - f (x + v)`, by using the mean value inequality applied to a suitable function along the segment `[x + v, x + v + w]`. This expansion involves `f'' ⬝ w` as we move along a segment directed by `w` (see `convex.taylor_approx_two_segment`). Consider the alternate sum `f (x + v + w) + f x - f (x + v) - f (x + w)`, corresponding to the values of `f` along a rectangle based at `x` with sides `v` and `w`. One can write it using the two sides directed by `w`, as `(f (x + v + w) - f (x + v)) - (f (x + w) - f x)`. Together with the previous asymptotic expansion, one deduces that it equals `f'' v w + o(1)` when `v, w` tends to `0`. Exchanging the roles of `v` and `w`, one instead gets an asymptotic expansion `f'' w v`, from which the equality `f'' v w = f'' w v` follows. In our most general statement, we only assume that `f` is differentiable inside a convex set `s`, so a few modifications have to be made. Since we don't assume continuity of `f` at `x`, we consider instead the rectangle based at `x + v + w` with sides `v` and `w`, in `convex.is_o_alternate_sum_square`, but the argument is essentially the same. It only works when `v` and `w` both point towards the interior of `s`, to make sure that all the sides of the rectangle are contained in `s` by convexity. The general case follows by linearity, though. -/ open asymptotics set open_locale topological_space variables {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {s : set E} (s_conv : convex ℝ s) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) include s_conv xs hx hf /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one can Taylor-expand to order two the function `f` on the segment `[x + h v, x + h (v + w)]`, giving a bilinear estimate for `f (x + hv + hw) - f (x + hv)` in terms of `f' w` and of `f'' ⬝ w`, up to `o(h^2)`. This is a technical statement used to show that the second derivative is symmetric. -/ lemma convex.taylor_approx_two_segment {v w : E} (hv : x + v ∈ interior s) (hw : x + v + w ∈ interior s) : (λ h : ℝ, f (x + h • v + h • w) - f (x + h • v) - h • f' x w - h^2 • f'' v w - (h^2/2) • f'' w w) =o[𝓝[>] 0] (λ h, h^2) := begin -- it suffices to check that the expression is bounded by `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2` for -- small enough `h`, for any positive `ε`. apply is_o.trans_is_O (is_o_iff.2 (λ ε εpos, _)) (is_O_const_mul_self ((∥v∥ + ∥w∥) * ∥w∥) _ _), -- consider a ball of radius `δ` around `x` in which the Taylor approximation for `f''` is -- good up to `δ`. rw [has_fderiv_within_at, has_fderiv_at_filter, is_o_iff] at hx, rcases metric.mem_nhds_within_iff.1 (hx εpos) with ⟨δ, δpos, sδ⟩, have E1 : ∀ᶠ h in 𝓝[>] (0:ℝ), h * (∥v∥ + ∥w∥) < δ, { have : filter.tendsto (λ h, h * (∥v∥ + ∥w∥)) (𝓝[>] (0:ℝ)) (𝓝 (0 * (∥v∥ + ∥w∥))) := (continuous_id.mul continuous_const).continuous_within_at, apply (tendsto_order.1 this).2 δ, simpa only [zero_mul] using δpos }, have E2 : ∀ᶠ h in 𝓝[>] (0:ℝ), (h : ℝ) < 1 := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(1 : ℝ), by simp only [mem_Ioi, zero_lt_one], λ x hx, hx.2⟩, filter_upwards [E1, E2, self_mem_nhds_within] with h hδ h_lt_1 hpos, -- we consider `h` small enough that all points under consideration belong to this ball, -- and also with `0 < h < 1`. replace hpos : 0 < h := hpos, have xt_mem : ∀ t ∈ Icc (0 : ℝ) 1, x + h • v + (t * h) • w ∈ interior s, { assume t ht, have : x + h • v ∈ interior s := s_conv.add_smul_mem_interior xs hv ⟨hpos, h_lt_1.le⟩, rw [← smul_smul], apply s_conv.interior.add_smul_mem this _ ht, rw add_assoc at hw, rw [add_assoc, ← smul_add], exact s_conv.add_smul_mem_interior xs hw ⟨hpos, h_lt_1.le⟩ }, -- define a function `g` on `[0,1]` (identified with `[v, v + w]`) such that `g 1 - g 0` is the -- quantity to be estimated. We will check that its derivative is given by an explicit -- expression `g'`, that we can bound. Then the desired bound for `g 1 - g 0` follows from the -- mean value inequality. let g := λ t, f (x + h • v + (t * h) • w) - (t * h) • f' x w - (t * h^2) • f'' v w - ((t * h)^2/2) • f'' w w, set g' := λ t, f' (x + h • v + (t * h) • w) (h • w) - h • f' x w - h^2 • f'' v w - (t * h^2) • f'' w w with hg', -- check that `g'` is the derivative of `g`, by a straightforward computation have g_deriv : ∀ t ∈ Icc (0 : ℝ) 1, has_deriv_within_at g (g' t) (Icc 0 1) t, { assume t ht, apply_rules [has_deriv_within_at.sub, has_deriv_within_at.add], { refine (hf _ _).comp_has_deriv_within_at _ _, { exact xt_mem t ht }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.const_add, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { suffices H : has_deriv_within_at (λ u, ((u * h) ^ 2 / 2) • f'' w w) (((((2 : ℕ) : ℝ) * (t * h) ^ (2 - 1) * (1 * h))/2) • f'' w w) (Icc 0 1) t, { convert H using 2, simp only [one_mul, nat.cast_bit0, pow_one, nat.cast_one], ring }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_id', has_deriv_at.pow, has_deriv_at.mul_const] } }, -- check that `g'` is uniformly bounded, with a suitable bound `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2`. have g'_bound : ∀ t ∈ Ico (0 : ℝ) 1, ∥g' t∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2, { assume t ht, have I : ∥h • v + (t * h) • w∥ ≤ h * (∥v∥ + ∥w∥) := calc ∥h • v + (t * h) • w∥ ≤ ∥h • v∥ + ∥(t * h) • w∥ : norm_add_le _ _ ... = h * ∥v∥ + t * (h * ∥w∥) : by simp only [norm_smul, real.norm_eq_abs, hpos.le, abs_of_nonneg, abs_mul, ht.left, mul_assoc] ... ≤ h * ∥v∥ + 1 * (h * ∥w∥) : add_le_add le_rfl (mul_le_mul_of_nonneg_right ht.2.le (mul_nonneg hpos.le (norm_nonneg _))) ... = h * (∥v∥ + ∥w∥) : by ring, calc ∥g' t∥ = ∥(f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)) (h • w)∥ : begin rw hg', have : h * (t * h) = t * (h * h), by ring, simp only [continuous_linear_map.coe_sub', continuous_linear_map.map_add, pow_two, continuous_linear_map.add_apply, pi.smul_apply, smul_sub, smul_add, smul_smul, ← sub_sub, continuous_linear_map.coe_smul', pi.sub_apply, continuous_linear_map.map_smul, this] end ... ≤ ∥f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)∥ * ∥h • w∥ : continuous_linear_map.le_op_norm _ _ ... ≤ (ε * ∥h • v + (t * h) • w∥) * (∥h • w∥) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), have H : x + h • v + (t * h) • w ∈ metric.ball x δ ∩ interior s, { refine ⟨_, xt_mem t ⟨ht.1, ht.2.le⟩⟩, rw [add_assoc, add_mem_ball_iff_norm], exact I.trans_lt hδ }, simpa only [mem_set_of_eq, add_assoc x, add_sub_cancel'] using sδ H, end ... ≤ (ε * (∥h • v∥ + ∥h • w∥)) * (∥h • w∥) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), apply mul_le_mul_of_nonneg_left _ (εpos.le), apply (norm_add_le _ _).trans, refine add_le_add le_rfl _, simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, ht.1, hpos.le, mul_assoc], exact mul_le_of_le_one_left (mul_nonneg hpos.le (norm_nonneg _)) ht.2.le, end ... = ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2 : by { simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, hpos.le], ring } }, -- conclude using the mean value inequality have I : ∥g 1 - g 0∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2, by simpa only [mul_one, sub_zero] using norm_image_sub_le_of_norm_deriv_le_segment' g_deriv g'_bound 1 (right_mem_Icc.2 zero_le_one), convert I using 1, { congr' 1, dsimp only [g], simp only [nat.one_ne_zero, add_zero, one_mul, zero_div, zero_mul, sub_zero, zero_smul, ne.def, not_false_iff, bit0_eq_zero, zero_pow'], abel }, { simp only [real.norm_eq_abs, abs_mul, add_nonneg (norm_nonneg v) (norm_nonneg w), abs_of_nonneg, mul_assoc, pow_bit0_abs, norm_nonneg, abs_pow] } end /-- One can get `f'' v w` as the limit of `h ^ (-2)` times the alternate sum of the values of `f` along the vertices of a quadrilateral with sides `h v` and `h w` based at `x`. In a setting where `f` is not guaranteed to be continuous at `f`, we can still get this if we use a quadrilateral based at `h v + h w`. -/ lemma convex.is_o_alternate_sum_square {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : (λ h : ℝ, f (x + h • (2 • v + 2 • w)) + f (x + h • (v + w)) - f (x + h • (2 • v + w)) - f (x + h • (v + 2 • w)) - h^2 • f'' v w) =o[𝓝[>] 0] (λ h, h^2) := begin have A : (1 : ℝ)/2 ∈ Ioc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have B : (1 : ℝ)/2 ∈ Icc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have C : ∀ (w : E), (2 : ℝ) • w = 2 • w := λ w, by simp only [two_smul], have h2v2w : x + (2 : ℝ) • v + (2 : ℝ) • w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h4v h4w B using 1, simp only [smul_sub, smul_smul, one_div, add_sub_add_left_eq_sub, mul_add, add_smul], norm_num, simp only [show (4 : ℝ) = (2 : ℝ) + (2 : ℝ), by norm_num, add_smul], abel }, have h2vww : x + (2 • v + w) + w ∈ interior s, { convert h2v2w using 1, simp only [two_smul], abel }, have h2v : x + (2 : ℝ) • v ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4v A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have h2w : x + (2 : ℝ) • w ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have hvw : x + (v + w) ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h2v2w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj, smul_add, smul_sub], norm_num, abel }, have h2vw : x + (2 • v + w) ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2v h2v2w B using 1, simp only [smul_add, smul_sub, smul_smul, ← C], norm_num, abel }, have hvww : x + (v + w) + w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2w h2v2w B using 1, simp only [one_div, add_sub_cancel', inv_smul_smul₀, add_sub_add_right_eq_sub, ne.def, not_false_iff, bit0_eq_zero, one_ne_zero], rw two_smul, abel }, have TA1 := s_conv.taylor_approx_two_segment hf xs hx h2vw h2vww, have TA2 := s_conv.taylor_approx_two_segment hf xs hx hvw hvww, convert TA1.sub TA2, ext h, simp only [two_smul, smul_add, ← add_assoc, continuous_linear_map.map_add, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', continuous_linear_map.map_smul], abel, end /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one has `f'' v w = f'' w v`. Superseded by `convex.second_derivative_within_at_symmetric`, which removes the assumption that `v` and `w` point inside `s`. -/ lemma convex.second_derivative_within_at_symmetric_of_mem_interior {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : f'' w v = f'' v w := begin have A : (λ h : ℝ, h^2 • (f'' w v- f'' v w)) =o[𝓝[>] 0] (λ h, h^2), { convert (s_conv.is_o_alternate_sum_square hf xs hx h4v h4w).sub (s_conv.is_o_alternate_sum_square hf xs hx h4w h4v), ext h, simp only [add_comm, smul_add, smul_sub], abel }, have B : (λ h : ℝ, f'' w v - f'' v w) =o[𝓝[>] 0] (λ h, (1 : ℝ)), { have : (λ h : ℝ, 1/h^2) =O[𝓝[>] 0] (λ h, 1/h^2) := is_O_refl _ _, have C := this.smul_is_o A, apply C.congr' _ _, { filter_upwards [self_mem_nhds_within], assume h hpos, rw [← one_smul ℝ (f'' w v - f'' v w), smul_smul, smul_smul], congr' 1, field_simp [has_lt.lt.ne' hpos] }, { filter_upwards [self_mem_nhds_within] with _ hpos, field_simp [has_lt.lt.ne' hpos, has_smul.smul], }, }, simpa only [sub_eq_zero] using is_o_const_const_iff.1 B, end omit s_conv xs hx hf /-- If a function is differentiable inside a convex set with nonempty interior, and has a second derivative at a point of this convex set, then this second derivative is symmetric. -/ theorem convex.second_derivative_within_at_symmetric {s : set E} (s_conv : convex ℝ s) (hne : (interior s).nonempty) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) (v w : E) : f'' v w = f'' w v := begin /- we work around a point `x + 4 z` in the interior of `s`. For any vector `m`, then `x + 4 (z + t m)` also belongs to the interior of `s` for small enough `t`. This means that we will be able to apply `second_derivative_within_at_symmetric_of_mem_interior` to show that `f''` is symmetric, after cancelling all the contributions due to `z`. -/ rcases hne with ⟨y, hy⟩, obtain ⟨z, hz⟩ : ∃ z, z = ((1:ℝ) / 4) • (y - x) := ⟨((1:ℝ) / 4) • (y - x), rfl⟩, have A : ∀ (m : E), filter.tendsto (λ (t : ℝ), x + (4 : ℝ) • (z + t • m)) (𝓝 0) (𝓝 y), { assume m, have : x + (4 : ℝ) • (z + (0 : ℝ) • m) = y, by simp [hz], rw ← this, refine tendsto_const_nhds.add _, refine tendsto_const_nhds.smul _, refine tendsto_const_nhds.add _, exact continuous_at_id.smul continuous_at_const }, have B : ∀ (m : E), ∀ᶠ t in 𝓝[>] (0 : ℝ), x + (4 : ℝ) • (z + t • m) ∈ interior s, { assume m, apply nhds_within_le_nhds, apply A m, rw [mem_interior_iff_mem_nhds] at hy, exact interior_mem_nhds.2 hy }, -- we choose `t m > 0` such that `x + 4 (z + (t m) m)` belongs to the interior of `s`, for any -- vector `m`. choose t ts tpos using λ m, ((B m).and self_mem_nhds_within).exists, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z` -- and `z + (t m) m`, we deduce that `f'' m z = f'' z m` for all `m`. have C : ∀ (m : E), f'' m z = f'' z m, { assume m, have : f'' (z + t m • m) (z + t 0 • 0) = f'' (z + t 0 • 0) (z + t m • m) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts 0) (ts m), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, add_right_inj, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', add_zero, continuous_linear_map.zero_apply, smul_zero, continuous_linear_map.map_zero] at this, exact smul_right_injective F (tpos m).ne' this }, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z + (t v) v` -- and `z + (t w) w`, we deduce that `f'' v w = f'' w v`. Cross terms involving `z` can be -- eliminated thanks to the fact proved above that `f'' m z = f'' z m`. have : f'' (z + t v • v) (z + t w • w) = f'' (z + t w • w) (z + t v • v) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts w) (ts v), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, smul_add, smul_smul, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', C] at this, rw ← sub_eq_zero at this, abel at this, simp only [one_zsmul, neg_smul, sub_eq_zero, mul_comm, ← sub_eq_add_neg] at this, apply smul_right_injective F _ this, simp [(tpos v).ne', (tpos w).ne'] end /-- If a function is differentiable around `x`, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric_of_eventually {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := begin rcases metric.mem_nhds_iff.1 hf with ⟨ε, εpos, hε⟩, have A : (interior (metric.ball x ε)).nonempty, by rwa [metric.is_open_ball.interior_eq, metric.nonempty_ball], exact convex.second_derivative_within_at_symmetric (convex_ball x ε) A (λ y hy, hε (interior_subset hy)) (metric.mem_ball_self εpos) hx.has_fderiv_within_at v w, end /-- If a function is differentiable, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ y, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := second_derivative_symmetric_of_eventually (filter.eventually_of_forall hf) hx v w
8dcec9b719402349ec6505e1facd50bdae87a986
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/asymptotics/specific_asymptotics.lean
5f4d69cbadd0be9bc28e11382df1e5947c9b9588
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,919
lean
/- Copyright (c) 2021 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.normed_space.ordered import analysis.asymptotics.asymptotics /-! # A collection of specific asymptotic results This file contains specific lemmas about asymptotics which don't have their place in the general theory developped in `analysis.asymptotics.asymptotics`. -/ open filter asymptotics open_locale topological_space section normed_field /-- If `f : 𝕜 → E` is bounded in a punctured neighborhood of `a`, then `f(x) = o((x - a)⁻¹)` as `x → a`, `x ≠ a`. -/ lemma filter.is_bounded_under.is_o_sub_self_inv {𝕜 E : Type*} [normed_field 𝕜] [has_norm E] {a : 𝕜} {f : 𝕜 → E} (h : is_bounded_under (≤) (𝓝[≠] a) (norm ∘ f)) : f =o[𝓝[≠] a] (λ x, (x - a)⁻¹) := begin refine (h.is_O_const (@one_ne_zero ℝ _ _)).trans_is_o (is_o_const_left.2 $ or.inr _), simp only [(∘), norm_inv], exact (tendsto_norm_sub_self_punctured_nhds a).inv_tendsto_zero end end normed_field section linear_ordered_field variables {𝕜 : Type*} [linear_ordered_field 𝕜] lemma pow_div_pow_eventually_eq_at_top {p q : ℕ} : (λ x : 𝕜, x^p / x^q) =ᶠ[at_top] (λ x, x^((p : ℤ) -q)) := begin apply ((eventually_gt_at_top (0 : 𝕜)).mono (λ x hx, _)), simp [zpow_sub₀ hx.ne'], end lemma pow_div_pow_eventually_eq_at_bot {p q : ℕ} : (λ x : 𝕜, x^p / x^q) =ᶠ[at_bot] (λ x, x^((p : ℤ) -q)) := begin apply ((eventually_lt_at_bot (0 : 𝕜)).mono (λ x hx, _)), simp [zpow_sub₀ hx.ne], end lemma tendsto_zpow_at_top_at_top {n : ℤ} (hn : 0 < n) : tendsto (λ x : 𝕜, x^n) at_top at_top := begin lift n to ℕ using hn.le, simp only [zpow_coe_nat], exact tendsto_pow_at_top (nat.cast_pos.mp hn).ne' end lemma tendsto_pow_div_pow_at_top_at_top {p q : ℕ} (hpq : q < p) : tendsto (λ x : 𝕜, x^p / x^q) at_top at_top := begin rw tendsto_congr' pow_div_pow_eventually_eq_at_top, apply tendsto_zpow_at_top_at_top, linarith end lemma tendsto_pow_div_pow_at_top_zero [topological_space 𝕜] [order_topology 𝕜] {p q : ℕ} (hpq : p < q) : tendsto (λ x : 𝕜, x^p / x^q) at_top (𝓝 0) := begin rw tendsto_congr' pow_div_pow_eventually_eq_at_top, apply tendsto_zpow_at_top_zero, linarith end end linear_ordered_field section normed_linear_ordered_field variables {𝕜 : Type*} [normed_linear_ordered_field 𝕜] lemma asymptotics.is_o_pow_pow_at_top_of_lt [order_topology 𝕜] {p q : ℕ} (hpq : p < q) : (λ x : 𝕜, x^p) =o[at_top] (λ x, x^q) := begin refine (is_o_iff_tendsto' _).mpr (tendsto_pow_div_pow_at_top_zero hpq), exact (eventually_gt_at_top 0).mono (λ x hx hxq, (pow_ne_zero q hx.ne' hxq).elim), end lemma asymptotics.is_O.trans_tendsto_norm_at_top {α : Type*} {u v : α → 𝕜} {l : filter α} (huv : u =O[l] v) (hu : tendsto (λ x, ∥u x∥) l at_top) : tendsto (λ x, ∥v x∥) l at_top := begin rcases huv.exists_pos with ⟨c, hc, hcuv⟩, rw is_O_with at hcuv, convert tendsto.at_top_div_const hc (tendsto_at_top_mono' l hcuv hu), ext x, rw mul_div_cancel_left _ hc.ne.symm, end end normed_linear_ordered_field section real open_locale big_operators open finset lemma asymptotics.is_o.sum_range {α : Type*} [normed_add_comm_group α] {f : ℕ → α} {g : ℕ → ℝ} (h : f =o[at_top] g) (hg : 0 ≤ g) (h'g : tendsto (λ n, ∑ i in range n, g i) at_top at_top) : (λ n, ∑ i in range n, f i) =o[at_top] (λ n, ∑ i in range n, g i) := begin have A : ∀ i, ∥g i∥ = g i := λ i, real.norm_of_nonneg (hg i), have B : ∀ n, ∥∑ i in range n, g i∥ = ∑ i in range n, g i, from λ n, by rwa [real.norm_eq_abs, abs_sum_of_nonneg'], apply is_o_iff.2 (λ ε εpos, _), obtain ⟨N, hN⟩ : ∃ (N : ℕ), ∀ (b : ℕ), N ≤ b → ∥f b∥ ≤ ε / 2 * g b, by simpa only [A, eventually_at_top] using is_o_iff.mp h (half_pos εpos), have : (λ (n : ℕ), ∑ i in range N, f i) =o[at_top] (λ (n : ℕ), ∑ i in range n, g i), { apply is_o_const_left.2, exact or.inr (h'g.congr (λ n, (B n).symm)) }, filter_upwards [is_o_iff.1 this (half_pos εpos), Ici_mem_at_top N] with n hn Nn, calc ∥∑ i in range n, f i∥ = ∥∑ i in range N, f i + ∑ i in Ico N n, f i∥ : by rw sum_range_add_sum_Ico _ Nn ... ≤ ∥∑ i in range N, f i∥ + ∥∑ i in Ico N n, f i∥ : norm_add_le _ _ ... ≤ ∥∑ i in range N, f i∥ + ∑ i in Ico N n, (ε / 2) * g i : add_le_add le_rfl (norm_sum_le_of_le _ (λ i hi, hN _ (mem_Ico.1 hi).1)) ... ≤ ∥∑ i in range N, f i∥ + ∑ i in range n, (ε / 2) * g i : begin refine add_le_add le_rfl _, apply sum_le_sum_of_subset_of_nonneg, { rw range_eq_Ico, exact Ico_subset_Ico (zero_le _) le_rfl }, { assume i hi hident, exact mul_nonneg (half_pos εpos).le (hg i) } end ... ≤ (ε / 2) * ∥∑ i in range n, g i∥ + (ε / 2) * (∑ i in range n, g i) : begin rw ← mul_sum, exact add_le_add hn (mul_le_mul_of_nonneg_left le_rfl (half_pos εpos).le), end ... = ε * ∥(∑ i in range n, g i)∥ : by { simp [B], ring } end lemma asymptotics.is_o_sum_range_of_tendsto_zero {α : Type*} [normed_add_comm_group α] {f : ℕ → α} (h : tendsto f at_top (𝓝 0)) : (λ n, ∑ i in range n, f i) =o[at_top] (λ n, (n : ℝ)) := begin have := ((is_o_one_iff ℝ).2 h).sum_range (λ i, zero_le_one), simp only [sum_const, card_range, nat.smul_one_eq_coe] at this, exact this tendsto_coe_nat_at_top_at_top end /-- The Cesaro average of a converging sequence converges to the same limit. -/ lemma filter.tendsto.cesaro_smul {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {u : ℕ → E} {l : E} (h : tendsto u at_top (𝓝 l)) : tendsto (λ (n : ℕ), (n ⁻¹ : ℝ) • (∑ i in range n, u i)) at_top (𝓝 l) := begin rw [← tendsto_sub_nhds_zero_iff, ← is_o_one_iff ℝ], have := asymptotics.is_o_sum_range_of_tendsto_zero (tendsto_sub_nhds_zero_iff.2 h), apply ((is_O_refl (λ (n : ℕ), (n : ℝ) ⁻¹) at_top).smul_is_o this).congr' _ _, { filter_upwards [Ici_mem_at_top 1] with n npos, have nposℝ : (0 : ℝ) < n := nat.cast_pos.2 npos, simp only [smul_sub, sum_sub_distrib, sum_const, card_range, sub_right_inj], rw [nsmul_eq_smul_cast ℝ, smul_smul, inv_mul_cancel nposℝ.ne', one_smul] }, { filter_upwards [Ici_mem_at_top 1] with n npos, have nposℝ : (0 : ℝ) < n := nat.cast_pos.2 npos, rw [algebra.id.smul_eq_mul, inv_mul_cancel nposℝ.ne'] } end /-- The Cesaro average of a converging sequence converges to the same limit. -/ lemma filter.tendsto.cesaro {u : ℕ → ℝ} {l : ℝ} (h : tendsto u at_top (𝓝 l)) : tendsto (λ (n : ℕ), (n ⁻¹ : ℝ) * (∑ i in range n, u i)) at_top (𝓝 l) := h.cesaro_smul end real
8d25bd6338c805cfec82a12bc1079ca7ddf6fb26
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/number_theory/dioph.lean
2a2c7761e2ec77f0b538c1f2803887f5ef0f2be0
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
36,351
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import number_theory.pell import data.pfun universe u open nat function namespace int lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n ↔ (x - n) * (x + n) = 0 := begin refine iff.trans _ mul_eq_zero.symm, refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm, exact ⟨λe, by rw ← e; apply nat_abs_eq, λo, by cases o; subst x; simp [nat_abs_of_nat]⟩ end end int /-- An alternate definition of `fin n` defined as an inductive type instead of a subtype of `nat`. This is useful for its induction principle and different definitional equalities. -/ inductive fin2 : ℕ → Type | fz {n} : fin2 (succ n) | fs {n} : fin2 n → fin2 (succ n) namespace fin2 @[elab_as_eliminator] protected def cases' {n} {C : fin2 (succ n) → Sort u} (H1 : C fz) (H2 : Π n, C (fs n)) : Π (i : fin2 (succ n)), C i | fz := H1 | (fs n) := H2 n def elim0 {C : fin2 0 → Sort u} : Π (i : fin2 0), C i. /-- convert a `fin2` into a `nat` -/ def to_nat : Π {n}, fin2 n → ℕ | ._ (@fz n) := 0 | ._ (@fs n i) := succ (to_nat i) /-- convert a `nat` into a `fin2` if it is in range -/ def opt_of_nat : Π {n} (k : ℕ), option (fin2 n) | 0 _ := none | (succ n) 0 := some fz | (succ n) (succ k) := fs <$> @opt_of_nat n k /-- `i + k : fin2 (n + k)` when `i : fin2 n` and `k : ℕ` -/ def add {n} (i : fin2 n) : Π k, fin2 (n + k) | 0 := i | (succ k) := fs (add k) /-- `left k` is the embedding `fin2 n → fin2 (k + n)` -/ def left (k) : Π {n}, fin2 n → fin2 (k + n) | ._ (@fz n) := fz | ._ (@fs n i) := fs (left i) /-- `insert_perm a` is a permutation of `fin2 n` with the following properties: * `insert_perm a i = i+1` if `i < a` * `insert_perm a a = 0` * `insert_perm a i = i` if `i > a` -/ def insert_perm : Π {n}, fin2 n → fin2 n → fin2 n | ._ (@fz n) (@fz ._) := fz | ._ (@fz n) (@fs ._ j) := fs j | ._ (@fs (succ n) i) (@fz ._) := fs fz | ._ (@fs (succ n) i) (@fs ._ j) := match insert_perm i j with fz := fz | fs k := fs (fs k) end /-- `remap_left f k : fin2 (m + k) → fin2 (n + k)` applies the function `f : fin2 m → fin2 n` to inputs less than `m`, and leaves the right part on the right (that is, `remap_left f k (m + i) = n + i`). -/ def remap_left {m n} (f : fin2 m → fin2 n) : Π k, fin2 (m + k) → fin2 (n + k) | 0 i := f i | (succ k) (@fz ._) := fz | (succ k) (@fs ._ i) := fs (remap_left _ i) /-- This is a simple type class inference prover for proof obligations of the form `m < n` where `m n : ℕ`. -/ class is_lt (m n : ℕ) := (h : m < n) instance is_lt.zero (n) : is_lt 0 (succ n) := ⟨succ_pos _⟩ instance is_lt.succ (m n) [l : is_lt m n] : is_lt (succ m) (succ n) := ⟨succ_lt_succ l.h⟩ /-- Use type class inference to infer the boundedness proof, so that we can directly convert a `nat` into a `fin2 n`. This supports notation like `&1 : fin 3`. -/ def of_nat' : Π {n} m [is_lt m n], fin2 n | 0 m ⟨h⟩ := absurd h (not_lt_zero _) | (succ n) 0 ⟨h⟩ := fz | (succ n) (succ m) ⟨h⟩ := fs (@of_nat' n m ⟨lt_of_succ_lt_succ h⟩) local prefix `&`:max := of_nat' end fin2 open fin2 /-- Alternate definition of `vector` based on `fin2`. -/ def vector3 (α : Type u) (n : ℕ) : Type u := fin2 n → α namespace vector3 /-- The empty vector -/ @[pattern] def nil {α} : vector3 α 0. /-- The vector cons operation -/ @[pattern] def cons {α} {n} (a : α) (v : vector3 α n) : vector3 α (succ n) := λi, by {refine i.cases' _ _, exact a, exact v} /- We do not want to make the following notation global, because then these expressions will be overloaded, and only the expected type will be able to disambiguate the meaning. Worse: Lean will try to insert a coercion from `vector3 α _` to `list α`, if a list is expected. -/ localized "notation `[` l:(foldr `, ` (h t, vector3.cons h t) nil `]`) := l" in vector3 notation a :: b := cons a b @[simp] theorem cons_fz {α} {n} (a : α) (v : vector3 α n) : (a :: v) fz = a := rfl @[simp] theorem cons_fs {α} {n} (a : α) (v : vector3 α n) (i) : (a :: v) (fs i) = v i := rfl /-- Get the `i`th element of a vector -/ @[reducible] def nth {α} {n} (i : fin2 n) (v : vector3 α n) : α := v i /-- Construct a vector from a function on `fin2`. -/ @[reducible] def of_fn {α} {n} (f : fin2 n → α) : vector3 α n := f /-- Get the head of a nonempty vector. -/ def head {α} {n} (v : vector3 α (succ n)) : α := v fz /-- Get the tail of a nonempty vector. -/ def tail {α} {n} (v : vector3 α (succ n)) : vector3 α n := λi, v (fs i) theorem eq_nil {α} (v : vector3 α 0) : v = [] := funext $ λi, match i with end theorem cons_head_tail {α} {n} (v : vector3 α (succ n)) : head v :: tail v = v := funext $ λi, fin2.cases' rfl (λ_, rfl) i def nil_elim {α} {C : vector3 α 0 → Sort u} (H : C []) (v : vector3 α 0) : C v := by rw eq_nil v; apply H def cons_elim {α n} {C : vector3 α (succ n) → Sort u} (H : Π (a : α) (t : vector3 α n), C (a :: t)) (v : vector3 α (succ n)) : C v := by rw ← (cons_head_tail v); apply H @[simp] theorem cons_elim_cons {α n C H a t} : @cons_elim α n C H (a :: t) = H a t := rfl @[elab_as_eliminator] protected def rec_on {α} {C : Π {n}, vector3 α n → Sort u} {n} (v : vector3 α n) (H0 : C []) (Hs : Π {n} (a) (w : vector3 α n), C w → C (a :: w)) : C v := nat.rec_on n (λv, v.nil_elim H0) (λn IH v, v.cons_elim (λa t, Hs _ _ (IH _))) v @[simp] theorem rec_on_nil {α C H0 Hs} : @vector3.rec_on α @C 0 [] H0 @Hs = H0 := rfl @[simp] theorem rec_on_cons {α C H0 Hs n a v} : @vector3.rec_on α @C (succ n) (a :: v) H0 @Hs = Hs a v (@vector3.rec_on α @C n v H0 @Hs) := rfl /-- Append two vectors -/ def append {α} {m} (v : vector3 α m) {n} (w : vector3 α n) : vector3 α (n+m) := nat.rec_on m (λ_, w) (λm IH v, v.cons_elim $ λa t, @fin2.cases' (n+m) (λ_, α) a (IH t)) v local infix ` +-+ `:65 := vector3.append @[simp] theorem append_nil {α} {n} (w : vector3 α n) : [] +-+ w = w := rfl @[simp] theorem append_cons {α} (a : α) {m} (v : vector3 α m) {n} (w : vector3 α n) : (a::v) +-+ w = a :: (v +-+ w) := rfl @[simp] theorem append_left {α} : ∀ {m} (i : fin2 m) (v : vector3 α m) {n} (w : vector3 α n), (v +-+ w) (left n i) = v i | ._ (@fz m) v n w := v.cons_elim (λa t, by simp [*, left]) | ._ (@fs m i) v n w := v.cons_elim (λa t, by simp [*, left]) @[simp] theorem append_add {α} : ∀ {m} (v : vector3 α m) {n} (w : vector3 α n) (i : fin2 n), (v +-+ w) (add i m) = w i | 0 v n w i := rfl | (succ m) v n w i := v.cons_elim (λa t, by simp [*, add]) /-- Insert `a` into `v` at index `i`. -/ def insert {α} (a : α) {n} (v : vector3 α n) (i : fin2 (succ n)) : vector3 α (succ n) := λj, (a :: v) (insert_perm i j) @[simp] theorem insert_fz {α} (a : α) {n} (v : vector3 α n) : insert a v fz = a :: v := by refine funext (λj, j.cases' _ _); intros; refl @[simp] theorem insert_fs {α} (a : α) {n} (b : α) (v : vector3 α n) (i : fin2 (succ n)) : insert a (b :: v) (fs i) = b :: insert a v i := funext $ λj, by { refine j.cases' _ (λj, _); simp [insert, insert_perm], refine fin2.cases' _ _ (insert_perm i j); simp [insert_perm] } theorem append_insert {α} (a : α) {k} (t : vector3 α k) {n} (v : vector3 α n) (i : fin2 (succ n)) (e : succ n + k = succ (n + k)) : insert a (t +-+ v) (eq.rec_on e (i.add k)) = eq.rec_on e (t +-+ insert a v i) := begin refine vector3.rec_on t (λe, _) (λk b t IH e, _) e, refl, have e' := succ_add n k, change insert a (b :: (t +-+ v)) (eq.rec_on (congr_arg succ e') (fs (add i k))) = eq.rec_on (congr_arg succ e') (b :: (t +-+ insert a v i)), rw ← (eq.drec_on e' rfl : fs (eq.rec_on e' (i.add k) : fin2 (succ (n + k))) = eq.rec_on (congr_arg succ e') (fs (i.add k))), simp, rw IH, exact eq.drec_on e' rfl end end vector3 section vector3 open vector3 open_locale vector3 /-- "Curried" exists, i.e. ∃ x1 ... xn, f [x1, ..., xn] -/ def vector_ex {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∃x : α, vector_ex k (λv, f (x :: v)) /-- "Curried" forall, i.e. ∀ x1 ... xn, f [x1, ..., xn] -/ def vector_all {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∀x : α, vector_all k (λv, f (x :: v)) theorem exists_vector_zero {α} (f : vector3 α 0 → Prop) : Exists f ↔ f [] := ⟨λ⟨v, fv⟩, by rw ← (eq_nil v); exact fv, λf0, ⟨[], f0⟩⟩ theorem exists_vector_succ {α n} (f : vector3 α (succ n) → Prop) : Exists f ↔ ∃x v, f (x :: v) := ⟨λ⟨v, fv⟩, ⟨_, _, by rw cons_head_tail v; exact fv⟩, λ⟨x, v, fxv⟩, ⟨_, fxv⟩⟩ theorem vector_ex_iff_exists {α} : ∀ {n} (f : vector3 α n → Prop), vector_ex n f ↔ Exists f | 0 f := (exists_vector_zero f).symm | (succ n) f := iff.trans (exists_congr (λx, vector_ex_iff_exists _)) (exists_vector_succ f).symm theorem vector_all_iff_forall {α} : ∀ {n} (f : vector3 α n → Prop), vector_all n f ↔ ∀ v, f v | 0 f := ⟨λf0 v, v.nil_elim f0, λal, al []⟩ | (succ n) f := (forall_congr (λx, vector_all_iff_forall (λv, f (x :: v)))).trans ⟨λal v, v.cons_elim al, λal x v, al (x::v)⟩ /-- `vector_allp p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction, i.e. `vector_allp p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ def vector_allp {α} (p : α → Prop) {n} (v : vector3 α n) : Prop := vector3.rec_on v true (λn a v IH, @vector3.rec_on _ (λn v, Prop) _ v (p a) (λn b v' _, p a ∧ IH)) @[simp] theorem vector_allp_nil {α} (p : α → Prop) : vector_allp p [] = true := rfl @[simp] theorem vector_allp_singleton {α} (p : α → Prop) (x : α) : vector_allp p [x] = p x := rfl @[simp] theorem vector_allp_cons {α} (p : α → Prop) {n} (x : α) (v : vector3 α n) : vector_allp p (x :: v) ↔ p x ∧ vector_allp p v := vector3.rec_on v (and_true _).symm (λn a v IH, iff.rfl) theorem vector_allp_iff_forall {α} (p : α → Prop) {n} (v : vector3 α n) : vector_allp p v ↔ ∀ i, p (v i) := begin refine v.rec_on _ _, { exact ⟨λ_, fin2.elim0, λ_, trivial⟩ }, { simp, refine λn a v IH, (and_congr_right (λ_, IH)).trans ⟨λ⟨pa, h⟩ i, by {refine i.cases' _ _, exacts [pa, h]}, λh, ⟨_, λi, _⟩⟩, { have h0 := h fz, simp at h0, exact h0 }, { have hs := h (fs i), simp at hs, exact hs } } end theorem vector_allp.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) {n} {v : vector3 α n} (al : vector_allp p v) : vector_allp q v := (vector_allp_iff_forall _ _).2 (λi, h _ $ (vector_allp_iff_forall _ _).1 al _) end vector3 /-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def list_all {α} (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ list_all l @[simp] theorem list_all_cons {α} (p : α → Prop) (x : α) : ∀ (l : list α), list_all p (x :: l) ↔ p x ∧ list_all p l | [] := (and_true _).symm | (x :: l) := iff.rfl theorem list_all_iff_forall {α} (p : α → Prop) : ∀ (l : list α), list_all p l ↔ ∀ x ∈ l, p x | [] := (iff_true_intro $ list.ball_nil _).symm | (x :: l) := by rw [list.ball_cons, ← list_all_iff_forall l]; simp theorem list_all.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) : ∀ {l : list α}, list_all p l → list_all q l | [] := id | (x :: l) := by simpa using and.imp (h x) list_all.imp @[simp] theorem list_all_map {α β} {p : β → Prop} (f : α → β) {l : list α} : list_all p (l.map f) ↔ list_all (p ∘ f) l := by induction l; simp * theorem list_all_congr {α} {p q : α → Prop} (h : ∀ x, p x ↔ q x) {l : list α} : list_all p l ↔ list_all q l := ⟨list_all.imp (λx, (h x).1), list_all.imp (λx, (h x).2)⟩ instance decidable_list_all {α} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (list_all p l) := decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm /- poly -/ /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly {α} : ((α → ℕ) → ℤ) → Prop | proj : ∀ i, is_poly (λx : α → ℕ, x i) | const : Π (n : ℤ), is_poly (λx : α → ℕ, n) | sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x - g x) | mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x * g x) /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f} namespace poly section parameter {α : Type u} instance : has_coe_to_fun (poly α) := ⟨_, λ f, f.1⟩ /-- The underlying function of a `poly` is a polynomial -/ lemma isp (f : poly α) : is_poly f := f.2 /-- Extensionality for `poly α` -/ lemma ext {f g : poly α} (e : ∀x, f x = g x) : f = g := subtype.eq (funext e) /-- Construct a `poly` given an extensionally equivalent `poly`. -/ def subst (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀x, f x = g x) : poly α := ⟨g, by rw ← (funext e : coe_fn f = g); exact f.isp⟩ @[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl /-- The `i`th projection function, `x_i`. -/ def proj (i) : poly α := ⟨_, is_poly.proj i⟩ @[simp] theorem proj_eval (i x) : proj i x = x i := rfl /-- The constant function with value `n : ℤ`. -/ def const (n) : poly α := ⟨_, is_poly.const n⟩ @[simp] theorem const_eval (n x) : const n x = n := rfl /-- The zero polynomial -/ def zero : poly α := const 0 instance : has_zero (poly α) := ⟨poly.zero⟩ @[simp] theorem zero_eval (x) : (0 : poly α) x = 0 := rfl /-- The zero polynomial -/ def one : poly α := const 1 instance : has_one (poly α) := ⟨poly.one⟩ @[simp] theorem one_eval (x) : (1 : poly α) x = 1 := rfl /-- Subtraction of polynomials -/ def sub : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.sub pf pg⟩ instance : has_sub (poly α) := ⟨poly.sub⟩ @[simp] theorem sub_eval : Π (f g x), (f - g : poly α) x = f x - g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Negation of a polynomial -/ def neg (f : poly α) : poly α := 0 - f instance : has_neg (poly α) := ⟨poly.neg⟩ @[simp] theorem neg_eval (f x) : (-f : poly α) x = -f x := show (0-f) x = _, by simp /-- Addition of polynomials -/ def add : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := subst (⟨f, pf⟩ - -⟨g, pg⟩) _ (λx, show f x - (0 - g x) = f x + g x, by simp) instance : has_add (poly α) := ⟨poly.add⟩ @[simp] theorem add_eval : Π (f g x), (f + g : poly α) x = f x + g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Multiplication of polynomials -/ def mul : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.mul pf pg⟩ instance : has_mul (poly α) := ⟨poly.mul⟩ @[simp] theorem mul_eval : Π (f g x), (f * g : poly α) x = f x * g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl instance : comm_ring (poly α) := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, .. }; {intros, exact ext (λx, by simp [mul_add, mul_left_comm, mul_comm, add_comm, add_assoc])} lemma induction {C : poly α → Prop} (H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n)) (H3 : ∀f g, C f → C g → C (f - g)) (H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f := begin cases f with f pf, induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg, apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg end /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq : list (poly α) → poly α | [] := 0 | (p::ps) := p*p + sumsq ps theorem sumsq_nonneg (x) : ∀ l, 0 ≤ sumsq l x | [] := le_refl 0 | (p::ps) := by rw sumsq; simp [-add_comm]; exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps) theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ list_all (λa : poly α, a x = 0) l | [] := eq_self_iff_true _ | (p::ps) := by rw [list_all_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact ⟨λ(h : p x * p x + sumsq ps x = 0), have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm (by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t) (mul_self_nonneg _), ⟨this, by simp [this] at h; exact h⟩, λ⟨h1, h2⟩, by rw [h1, h2]; refl⟩ end /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def remap {α β} (f : α → β) (g : poly α) : poly β := ⟨λv, g $ v ∘ f, g.induction (λi, by simp; apply is_poly.proj) (λn, by simp; apply is_poly.const) (λf g pf pg, by simp; apply is_poly.sub pf pg) (λf g pf pg, by simp; apply is_poly.mul pf pg)⟩ @[simp] theorem remap_eval {α β} (f : α → β) (g : poly α) (v) : remap f g v = g (v ∘ f) := rfl end poly namespace sum /-- combine two functions into a function on the disjoint union -/ def join {α β γ} (f : α → γ) (g : β → γ) : α ⊕ β → γ := by {refine sum.rec _ _, exacts [f, g]} end sum local infixr ` ⊗ `:65 := sum.join open sum namespace option /-- Functions from `option` can be combined similarly to `vector.cons` -/ def cons {α β} (a : β) (v : α → β) : option α → β := by {refine option.rec _ _, exacts [a, v]} notation a :: b := cons a b @[simp] theorem cons_head_tail {α β} (v : option α → β) : v none :: v ∘ some = v := funext $ λo, by cases o; refl end option /- dioph -/ /-- A set `S ⊆ ℕ^α` is diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) : Prop := ∃ {β : Type u} (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0 namespace dioph section variables {α β γ : Type u} theorem ext {S S' : set (α → ℕ)} (d : dioph S) (H : ∀v, S v ↔ S' v) : dioph S' := eq.rec d $ show S = S', from set.ext H theorem of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ p v = 0) : dioph S := ⟨ulift empty, p.remap inl, λv, (h v).trans ⟨λh, ⟨λt, empty.rec _ t.down, by simp; rw [ show (v ⊗ λt:ulift empty, empty.rec _ t.down) ∘ inl = v, from rfl, h]⟩, λ⟨t, ht⟩, by simp at ht; rwa [show (v ⊗ t) ∘ inl = v, from rfl] at ht⟩⟩ lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃t, p (v ⊗ t) = 0) ↔ (∃t, p.remap (inl ⊗ (inr ∘ f)) (v ⊗ t) = 0) := begin simp, refine ⟨λt, _, λt, _⟩; cases t with t ht, { have : (v ⊗ (0 :: t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t := funext (λs, by cases s with a b; dsimp [join, (∘)]; try {rw inv}; refl), exact ⟨(0 :: t) ∘ g, by rwa this⟩ }, { have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext (λs, by cases s with a b; refl), exact ⟨t ∘ f, by rwa this⟩ } end theorem inject_dummies {S : set (α → ℕ)} (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0) : ∃ q : poly (α ⊕ γ), ∀ (v : α → ℕ), S v ↔ ∃t, q (v ⊗ t) = 0 := ⟨p.remap (inl ⊗ (inr ∘ f)), λv, (h v).trans $ inject_dummies_lem f g inv _ _⟩ theorem reindex_dioph {S : set (α → ℕ)} : Π (d : dioph S) (f : α → β), dioph (λv, S (v ∘ f)) | ⟨γ, p, pe⟩ f := ⟨γ, p.remap ((inl ∘ f) ⊗ inr), λv, (pe _).trans $ exists_congr $ λt, suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this], funext $ λs, by cases s with a b; refl⟩ theorem dioph_list_all (l) (d : list_all dioph l) : dioph (λv, list_all (λS : set (α → ℕ), S v) l) := suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list_all (λS : set _, S v) l ↔ ∃t, list_all (λp : poly (α ⊕ β), p (v ⊗ t) = 0) pl, from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λv, (h v).trans $ exists_congr $ λt, (poly.sumsq_eq_zero _ _).symm⟩, begin induction l with S l IH, exact ⟨ulift empty, [], λv, by simp; exact ⟨λ⟨t⟩, empty.rec _ t, trivial⟩⟩, simp at d, exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) :: pl.map (λq, q.remap (inl ⊗ (inr ∘ inr))), λv, by simp; exact iff.trans (and_congr (pe v) (ple v)) ⟨λ⟨⟨m, hm⟩, ⟨n, hn⟩⟩, ⟨m ⊗ n, by rw [ show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m, from funext $ λs, by cases s with a b; refl]; exact hm, by { refine list_all.imp (λq hq, _) hn, dsimp [(∘)], rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n, from funext $ λs, by cases s with a b; refl]; exact hq }⟩, λ⟨t, hl, hr⟩, ⟨⟨t ∘ inl, by rwa [ show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl, from funext $ λs, by cases s with a b; refl] at hl⟩, ⟨t ∘ inr, by { refine list_all.imp (λq hq, _) hr, dsimp [(∘)] at hq, rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr, from funext $ λs, by cases s with a b; refl] at hq }⟩⟩⟩⟩ end theorem and_dioph {S S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph (λv, S v ∧ S' v) := dioph_list_all [S, S'] ⟨d, d'⟩ theorem or_dioph {S S' : set (α → ℕ)} : ∀ (d : dioph S) (d' : dioph S'), dioph (λv, S v ∨ S' v) | ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) * q.remap (inl ⊗ inr ∘ inr), λv, begin refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λt, (@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)), exact inject_dummies_lem _ (some ⊗ (λ_, none)) (λx, rfl) _ _, exact inject_dummies_lem _ ((λ_, none) ⊗ some) (λx, rfl) _ _, end⟩ /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun (f : (α → ℕ) →. ℕ) := dioph (λv : option α → ℕ, f.graph (v ∘ some, v none)) /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn (f : (α → ℕ) → ℕ) := dioph (λv : option α → ℕ, f (v ∘ some) = v none) theorem reindex_dioph_fn {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn (λv, f (v ∘ g)) := reindex_dioph d (functor.map g) theorem ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph (λv, ∃x, S (v ⊗ x)) | ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.remap ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [ show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [ show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph (λv, ∃x, S (x :: v)) | ⟨β, p, pe⟩ := ⟨option β, p.remap (inr none :: inl ⊗ inr ∘ some), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x :: t, by simp; rw [ show (v ⊗ x :: t) ∘ (inr none :: inl ⊗ inr ∘ some) = x :: v ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [ show (v ⊗ t) ∘ (inr none :: inl ⊗ inr ∘ some) = t none :: v ⊗ t ∘ some, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom := cast (congr_arg dioph $ set.ext $ λv, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d) theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f := by refine congr_arg dioph (set.ext $ λv, _); exact pfun.lift_graph.symm theorem abs_poly_dioph (p : poly α) : dioph_fn (λv, (p v).nat_abs) := by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (λv, _); apply int.eq_nat_abs_iff_mul theorem proj_dioph (i : α) : dioph_fn (λv, v i) := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) : dioph (λv : α → ℕ, ∃ h : f.dom v, S (f.fn v h :: v)) := ext (ex1_dioph (and_dioph d df)) $ λv, ⟨λ⟨x, hS, (h: Exists _)⟩, by rw [show (x :: v) ∘ some = v, from funext $ λs, rfl] at h; cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS, λ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _, by rw [show (f.fn v x :: v) ∘ some = v, from funext $ λs, rfl]; exact ⟨x, rfl⟩⟩⟩ theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph (λv : α → ℕ, S (f v :: v)) := ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ λv, ⟨λ⟨_, h⟩, h, λh, ⟨trivial, h⟩⟩ end section variables {α β γ : Type} open vector3 open_locale vector3 theorem dioph_fn_vec_comp1 {n} {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : (vector3 ℕ n) → ℕ} (df : dioph_fn f) : dioph (λv : vector3 ℕ n, S (cons (f v) v)) := ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ λv, by rw [ show option.cons (f v) v ∘ (cons none some) = f v :: v, from funext $ λs, by cases s with a b; refl] theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph (λv : vector3 ℕ n, ∃x, S (x :: v)) := ext (ex1_dioph $ reindex_dioph d (none :: some)) $ λv, exists_congr $ λx, by rw [ show (option.cons x v) ∘ (cons none some) = x :: v, from funext $ λs, by cases s with a b; refl] theorem dioph_fn_vec {n} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph (λv : vector3 ℕ (succ n), f (v ∘ fs) = v fz) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_pfun_vec {n} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph (λv : vector3 ℕ (succ n), f.graph (v ∘ fs, v fz)) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_fn_compn {α : Type} : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f), dioph (λv : α → ℕ, S (v ⊗ λi, f i v)) | 0 S d f := λdf, ext (reindex_dioph d (id ⊗ fin2.elim0)) $ λv, by refine eq.to_iff (congr_arg S $ funext $ λs, _); {cases s with a b, refl, cases b} | (succ n) S d f := f.cons_elim $ λf fl, by simp; exact λ df dfl, have dioph (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)), from ext (dioph_fn_comp1 (reindex_dioph d (some ∘ inl ⊗ none :: some ∘ inr)) (reindex_dioph_fn df inl)) $ λv, by {refine eq.to_iff (congr_arg S $ funext $ λs, _); cases s with a b, refl, cases b; refl}, have dioph (λv, S (v ⊗ f v :: λ (i : fin2 n), fl i v)), from @dioph_fn_compn n (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl, ext this $ λv, by rw [ show cons (f v) (λ (i : fin2 n), fl i v) = λ (i : fin2 (succ n)), (f :: fl) i v, from funext $ λs, by cases s with a b; refl] theorem dioph_comp {n} {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph (λv, S (λi, f i v)) := dioph_fn_compn (reindex_dioph d inr) df theorem dioph_fn_comp {n} {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λv, f (λi, g i v)) := dioph_comp ((dioph_fn_vec _).1 df) ((λv, v none) :: λi v, g i (v ∘ some)) $ by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λi, reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _⟩ localized "notation x ` D∧ `:35 y := dioph.and_dioph x y" in dioph localized "notation x ` D∨ `:35 y := dioph.or_dioph x y" in dioph localized "notation `D∃`:30 := dioph.vec_ex1_dioph" in dioph localized "prefix `&`:max := of_nat'" in dioph theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λv : vector3 ℕ n, v &m) := proj_dioph &m localized "prefix `D&`:100 := dioph.proj_dioph_of_nat" in dioph theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) := abs_poly_dioph (poly.const n) localized "prefix `D.`:100 := dioph.const_dioph" in dioph variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) include df dg theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λv:vector3 ℕ 2, S (v &0) (v &1))) : dioph (λv, S (f v) (g v)) := dioph_comp d [f, g] (by exact ⟨df, dg⟩) theorem dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λv:vector3 ℕ 2, h (v &0) (v &1))) : dioph_fn (λv, h (f v) (g v)) := dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩) theorem eq_dioph : dioph (λv, f v = g v) := dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1) (λv, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩) localized "infix ` D= `:50 := dioph.eq_dioph" in dioph theorem add_dioph : dioph_fn (λv, f v + g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1) localized "infix ` D+ `:80 := dioph.add_dioph" in dioph theorem mul_dioph : dioph_fn (λv, f v * g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1) localized "infix ` D* `:90 := dioph.mul_dioph" in dioph theorem le_dioph : dioph (λv, f v ≤ g v) := dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λv, ⟨λ⟨x, hx⟩, le.intro hx, le.dest⟩) localized "infix ` D≤ `:50 := dioph.le_dioph" in dioph theorem lt_dioph : dioph (λv, f v < g v) := df D+ (D. 1) D≤ dg localized "infix ` D< `:50 := dioph.lt_dioph" in dioph theorem ne_dioph : dioph (λv, f v ≠ g v) := ext (df D< dg D∨ dg D< df) $ λv, ne_iff_lt_or_gt.symm localized "infix ` D≠ `:50 := dioph.ne_dioph" in dioph theorem sub_dioph : dioph_fn (λv, f v - g v) := dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z, show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from ⟨λo, begin rcases o with ae | ⟨yz, x0⟩, { rw [ae, nat.add_sub_cancel] }, { rw [x0, nat.sub_eq_zero_of_le yz] } end, λh, begin subst x, cases le_total y z with yz zy, { exact or.inr ⟨yz, nat.sub_eq_zero_of_le yz⟩ }, { exact or.inl (nat.sub_add_cancel zy).symm }, end⟩ localized "infix ` D- `:80 := dioph.sub_dioph" in dioph theorem dvd_dioph : dioph (λv, f v ∣ g v) := dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩) localized "infix ` D∣ `:50 := dioph.dvd_dioph" in dioph theorem mod_dioph : dioph_fn (λv, f v % g v) := have dioph (λv : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1), from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from ⟨λ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end, λe, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λh, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩ localized "infix ` D% `:80 := dioph.mod_dioph" in dioph theorem modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λv, f v ≡ g v [MOD h v]) := df D% dh D= dg D% dh localized "notation `D≡` := dioph.modeq_dioph" in dioph theorem div_dioph : dioph_fn (λv, f v / g v) := have dioph (λv : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2), from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2, dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z, by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim (λy0, by rw [y0, nat.div_zero]; exact ⟨λo, (o.resolve_right $ λ⟨_, h2⟩, not_lt_zero _ h2).right, λz0, or.inl ⟨rfl, z0⟩⟩) (λypos, iff.trans ⟨λo, o.resolve_left $ λ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩ (le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $ iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm) localized "infix ` D/ `:80 := dioph.div_dioph" in dioph omit df dg open pell theorem pell_dioph : dioph (λv:vector3 ℕ 4, ∃ h : 1 < v &0, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) := have dioph {v : vector3 ℕ 4 | 1 < v &0 ∧ v &1 ≤ v &3 ∧ (v &2 = 1 ∧ v &3 = 0 ∨ ∃ (u w s t b : ℕ), v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧ u * u - (v &0 * v &0 - 1) * w * w = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧ 0 < w ∧ v &3 * v &3 ∣ w ∧ (s ≡ v &2 [MOD u]) ∧ (t ≡ v &1 [MOD 4 * v &3]))}, from D.1 D< D&0 D∧ D&1 D≤ D&3 D∧ ((D&2 D= D.1 D∧ D&3 D= D.0) D∨ (D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧ D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧ D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧ D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧ D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧ (D≡ (D&2) (D&7) D&4) D∧ (D≡ (D&1) (D&6) (D.4 D* D&8)))), dioph.ext this $ λv, matiyasevic.symm theorem xn_dioph : dioph_pfun (λv:vector3 ℕ 2, ⟨1 < v &0, λh, xn h (v &1)⟩) := have dioph (λv:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in D∃3 D_pell, (dioph_pfun_vec _).2 $ dioph.ext this $ λv, ⟨λ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩ include df dg theorem pow_dioph : dioph_fn (λv, f v ^ g v) := have dioph {v : vector3 ℕ 3 | v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧ (v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧ ∃ (w a t z x y : ℕ), (∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧ (x ≡ y * (a - v &1) + v &0 [MOD t]) ∧ 2 * a * v &1 = t + (v &1 * v &1 + 1) ∧ v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in (D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧ ((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧ (D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧ (D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧ D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧ D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧ D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λv, iff.symm $ eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $ ⟨λ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩, λ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩ end end dioph
3d0f81d59b6d6bed110df9cffb869516aa53bb2e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/real/hyperreal.lean
f43704a948f86ee7a3049e826186d1557df3a17c
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,909
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir -/ import order.filter.filter_product import analysis.specific_limits /-! # Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ open filter filter.germ open_locale topological_space classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ @[derive [linear_ordered_field, inhabited]] def hyperreal : Type := germ (hyperfilter ℕ : filter ℕ) ℝ namespace hyperreal notation `ℝ*` := hyperreal noncomputable instance : has_coe_t ℝ ℝ* := ⟨λ x, (↑x : germ _ _)⟩ @[simp, norm_cast] lemma coe_eq_coe {x y : ℝ} : (x : ℝ*) = y ↔ x = y := germ.const_inj @[simp, norm_cast] lemma coe_eq_zero {x : ℝ} : (x : ℝ*) = 0 ↔ x = 0 := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one {x : ℝ} : (x : ℝ*) = 1 ↔ x = 1 := coe_eq_coe @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ) = (1 : ℝ*) := rfl @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ) = (0 : ℝ*) := rfl @[simp, norm_cast] lemma coe_inv (x : ℝ) : ↑(x⁻¹) = (x⁻¹ : ℝ*) := rfl @[simp, norm_cast] lemma coe_neg (x : ℝ) : ↑(-x) = (-x : ℝ*) := rfl @[simp, norm_cast] lemma coe_add (x y : ℝ) : ↑(x + y) = (x + y : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit0 (x : ℝ) : ↑(bit0 x) = (bit0 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit1 (x : ℝ) : ↑(bit1 x) = (bit1 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ↑(x * y) = (x * y : ℝ*) := rfl @[simp, norm_cast] lemma coe_div (x y : ℝ) : ↑(x / y) = (x / y : ℝ*) := rfl @[simp, norm_cast] lemma coe_sub (x y : ℝ) : ↑(x - y) = (x - y : ℝ*) := rfl @[simp, norm_cast] lemma coe_lt_coe {x y : ℝ} : (x : ℝ*) < y ↔ x < y := germ.const_lt @[simp, norm_cast] lemma coe_pos {x : ℝ} : 0 < (x : ℝ*) ↔ 0 < x := coe_lt_coe @[simp, norm_cast] lemma coe_le_coe {x y : ℝ} : (x : ℝ*) ≤ y ↔ x ≤ y := germ.const_le_iff @[simp, norm_cast] lemma coe_abs (x : ℝ) : ((|x| : ℝ) : ℝ*) = |x| := begin convert const_abs x, apply lattice_of_linear_order_eq_filter_germ_lattice, end @[simp, norm_cast] lemma coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max x y := germ.const_max _ _ @[simp, norm_cast] lemma coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min x y := germ.const_min _ _ /-- Construct a hyperreal number from a sequence of real numbers. -/ noncomputable def of_seq (f : ℕ → ℝ) : ℝ* := (↑f : germ (hyperfilter ℕ : filter ℕ) ℝ) /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := of_seq $ λ n, n⁻¹ /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := of_seq coe localized "notation `ε` := hyperreal.epsilon" in hyperreal localized "notation `ω` := hyperreal.omega" in hyperreal lemma epsilon_eq_inv_omega : ε = ω⁻¹ := rfl lemma inv_epsilon_eq_omega : ε⁻¹ = ω := @inv_inv₀ _ _ ω lemma epsilon_pos : 0 < ε := suffices ∀ᶠ i in hyperfilter ℕ, (0 : ℝ) < (i : ℕ)⁻¹, by rwa lt_def, have h0' : {n : ℕ | ¬ 0 < n} = {0} := by simp only [not_lt, (set.set_of_eq_eq_singleton).symm]; ext; exact nat.le_zero_iff, begin simp only [inv_pos, nat.cast_pos], exact mem_hyperfilter_of_finite_compl (by convert set.finite_singleton _), end lemma epsilon_ne_zero : ε ≠ 0 := ne_of_gt epsilon_pos lemma omega_pos : 0 < ω := by rw ←inv_epsilon_eq_omega; exact inv_pos.2 epsilon_pos lemma omega_ne_zero : ω ≠ 0 := ne_of_gt omega_pos theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero lemma lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → of_seq f < (r : ℝ*) := begin simp only [metric.tendsto_at_top, dist_zero_right, norm, lt_def] at hf ⊢, intros r hr, cases hf r hr with N hf', have hs : {i : ℕ | f i < r}ᶜ ⊆ {i : ℕ | i ≤ N} := λ i hi1, le_of_lt (by simp only [lt_iff_not_ge]; exact λ hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N), exact mem_hyperfilter_of_finite_compl ((set.finite_le_nat N).subset hs) end lemma neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → (-r : ℝ*) < of_seq f := λ r hr, have hg : _ := hf.neg, neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) lemma gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < of_seq f := λ r hr, by rw [←neg_neg r, coe_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) lemma epsilon_lt_pos (x : ℝ) : 0 < x → ε < x := lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat /-- Standard part predicate -/ def is_st (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, 0 < δ → (r - δ : ℝ*) < x ∧ x < r + δ /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := λ x, if h : ∃ r, is_st x r then classical.some h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def infinitesimal (x : ℝ*) := is_st x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def infinite_pos (x : ℝ*) := ∀ r : ℝ, ↑r < x /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def infinite_neg (x : ℝ*) := ∀ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def infinite (x : ℝ*) := infinite_pos x ∨ infinite_neg x /-! ### Some facts about `st` -/ private lemma is_st_unique' (x : ℝ*) (r s : ℝ) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) : false := have hrs' : _ := half_pos $ sub_pos_of_lt hrs, have hr' : _ := (hr _ hrs').2, have hs' : _ := (hs _ hrs').1, have h : s - ((s - r) / 2) = r + (s - r) / 2 := by linarith, begin norm_cast at *, rw h at hs', exact not_lt_of_lt hs' hr' end theorem is_st_unique {x : ℝ*} {r s : ℝ} (hr : is_st x r) (hs : is_st x s) : r = s := begin rcases lt_trichotomy r s with h | h | h, { exact false.elim (is_st_unique' x r s hr hs h) }, { exact h }, { exact false.elim (is_st_unique' x s r hs hr h) } end theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, is_st x r) → ¬ infinite x := λ he hi, Exists.dcases_on he $ λ r hr, hi.elim (λ hip, not_lt_of_lt (hr 2 zero_lt_two).2 (hip $ r + 2)) (λ hin, not_lt_of_lt (hr 2 zero_lt_two).1 (hin $ r - 2)) theorem is_st_Sup {x : ℝ*} (hni : ¬ infinite x) : is_st x (Sup {y : ℝ | (y : ℝ*) < x}) := let S : set ℝ := {y : ℝ | (y : ℝ*) < x} in let R : _ := Sup S in have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1, have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2, Exists.dcases_on hnile $ Exists.dcases_on hnige $ λ r₁ hr₁ r₂ hr₂, have HR₁ : S.nonempty := ⟨r₁ - 1, lt_of_lt_of_le (coe_lt_coe.2 $ sub_one_lt _) (not_lt.mp hr₁) ⟩, have HR₂ : bdd_above S := ⟨ r₂, λ y hy, le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hr₂))) ⟩, λ δ hδ, ⟨ lt_of_not_ge' $ λ c, have hc : ∀ y ∈ S, y ≤ R - δ := λ y hy, coe_le_coe.1 $ le_of_lt $ lt_of_lt_of_le hy c, not_lt_of_le (cSup_le HR₁ hc) $ sub_lt_self R hδ, lt_of_not_ge' $ λ c, have hc : ↑(R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hδ)) R) c, not_lt_of_le (le_cSup HR₂ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬ infinite x) : ∃ r : ℝ, is_st x r := ⟨Sup {y : ℝ | (y : ℝ*) < x}, is_st_Sup hni⟩ theorem st_eq_Sup {x : ℝ*} : st x = Sup {y : ℝ | (y : ℝ*) < x} := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) }, { cases not_imp_comm.mp exists_st_of_not_infinite h with H H, { rw (set.ext (λ i, ⟨λ hi, set.mem_univ i, λ hi, H i⟩) : {y : ℝ | (y : ℝ*) < x} = set.univ), exact real.Sup_univ.symm }, { rw (set.ext (λ i, ⟨λ hi, false.elim (not_lt_of_lt (H i) hi), λ hi, false.elim (set.not_mem_empty i hi)⟩) : {y : ℝ | (y : ℝ*) < x} = ∅), exact real.Sup_empty.symm } } end theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, is_st x r) ↔ ¬ infinite x := ⟨ not_infinite_of_exists_st, exists_st_of_not_infinite ⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : infinite x ↔ ¬ ∃ r : ℝ, is_st x r := iff_not_comm.mp exists_st_iff_not_infinite theorem st_infinite {x : ℝ*} (hi : infinite x) : st x = 0 := begin unfold st, split_ifs, { exact false.elim ((infinite_iff_not_exists_st.mp hi) h) }, { refl } end lemma st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : st x = r := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) hxr }, { exact false.elim (h ⟨r, hxr⟩) } end lemma is_st_st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st x (st x) := by rwa [st_of_is_st hxr] lemma is_st_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, is_st x r) : is_st x (st x) := Exists.dcases_on hx (λ r, is_st_st_of_is_st) lemma is_st_st {x : ℝ*} (hx : st x ≠ 0) : is_st x (st x) := begin unfold st, split_ifs, { exact classical.some_spec h }, { exact false.elim (hx (by unfold st; split_ifs; refl)) } end lemma is_st_st' {x : ℝ*} (hx : ¬ infinite x) : is_st x (st x) := is_st_st_of_exists_st $ exists_st_of_not_infinite hx lemma is_st_refl_real (r : ℝ) : is_st r r := λ δ hδ, ⟨ sub_lt_self _ (coe_lt_coe.2 hδ), (lt_add_of_pos_right _ (coe_lt_coe.2 hδ)) ⟩ lemma st_id_real (r : ℝ) : st r = r := st_of_is_st (is_st_refl_real r) lemma eq_of_is_st_real {r s : ℝ} : is_st r s → r = s := is_st_unique (is_st_refl_real r) lemma is_st_real_iff_eq {r s : ℝ} : is_st r s ↔ r = s := ⟨eq_of_is_st_real, λ hrs, by rw [hrs]; exact is_st_refl_real s⟩ lemma is_st_symm_real {r s : ℝ} : is_st r s ↔ is_st s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] lemma is_st_trans_real {r s t : ℝ} : is_st r s → is_st s t → is_st r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans lemma is_st_inj_real {r₁ r₂ s : ℝ} (h1 : is_st r₁ s) (h2 : is_st r₂ s) : r₁ = r₂ := eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm lemma is_st_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : is_st x r ↔ ∀ (δ : ℝ), 0 < δ → |x - r| < δ := by simp only [abs_sub_lt_iff, sub_lt_iff_lt_add, is_st, and_comm, add_comm] lemma is_st_add {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x + y) (r + s) := λ hxr hys d hd, have hxr' : _ := hxr (d / 2) (half_pos hd), have hys' : _ := hys (d / 2) (half_pos hd), ⟨by convert add_lt_add hxr'.1 hys'.1 using 1; norm_cast; linarith, by convert add_lt_add hxr'.2 hys'.2 using 1; norm_cast; linarith⟩ lemma is_st_neg {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st (-x) (-r) := λ d hd, show -(r : ℝ*) - d < -x ∧ -x < -r + d, by cases (hxr d hd); split; linarith lemma is_st_sub {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x - y) (r - s) := λ hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys) /- (st x < st y) → (x < y) → (x ≤ y) → (st x ≤ st y) -/ lemma lt_of_is_st_lt {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : r < s → x < y := λ hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs), have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1, have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith, have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith, begin norm_cast at *, rw H1 at hxr', rw H2 at hys', exact lt_trans hxr' hys' end lemma is_st_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : is_st x r) (hsy : is_st y s) : x ≤ y → r ≤ s := by rw [←not_lt, ←not_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx lemma st_le_of_le {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : x ≤ y → st x ≤ st y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, is_st_le_of_le hx' hy' lemma lt_of_st_lt {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : st x < st y → x < y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, lt_of_is_st_lt hx' hy' /-! ### Basic lemmas about infinite -/ lemma infinite_pos_def {x : ℝ*} : infinite_pos x ↔ ∀ r : ℝ, ↑r < x := by rw iff_eq_eq; refl lemma infinite_neg_def {x : ℝ*} : infinite_neg x ↔ ∀ r : ℝ, x < r := by rw iff_eq_eq; refl lemma ne_zero_of_infinite {x : ℝ*} : infinite x → x ≠ 0 := λ hI h0, or.cases_on hI (λ hip, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_pos 0) 0)) (λ hin, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_neg 0) 0)) lemma not_infinite_zero : ¬ infinite 0 := λ hI, ne_zero_of_infinite hI rfl lemma pos_of_infinite_pos {x : ℝ*} : infinite_pos x → 0 < x := λ hip, hip 0 lemma neg_of_infinite_neg {x : ℝ*} : infinite_neg x → x < 0 := λ hin, hin 0 lemma not_infinite_pos_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinite_pos x := λ hn hp, not_lt_of_lt (hn 1) (hp 1) lemma not_infinite_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinite_neg x := imp_not_comm.mp not_infinite_pos_of_infinite_neg lemma infinite_neg_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → infinite_neg (-x) := λ hp r, neg_lt.mp (hp (-r)) lemma infinite_pos_neg_of_infinite_neg {x : ℝ*} : infinite_neg x → infinite_pos (-x) := λ hp r, lt_neg.mp (hp (-r)) lemma infinite_pos_iff_infinite_neg_neg {x : ℝ*} : infinite_pos x ↔ infinite_neg (-x) := ⟨ infinite_neg_neg_of_infinite_pos, λ hin, neg_neg x ▸ infinite_pos_neg_of_infinite_neg hin ⟩ lemma infinite_neg_iff_infinite_pos_neg {x : ℝ*} : infinite_neg x ↔ infinite_pos (-x) := ⟨ infinite_pos_neg_of_infinite_neg, λ hin, neg_neg x ▸ infinite_neg_neg_of_infinite_pos hin ⟩ lemma infinite_iff_infinite_neg {x : ℝ*} : infinite x ↔ infinite (-x) := ⟨ λ hi, or.cases_on hi (λ hip, or.inr (infinite_neg_neg_of_infinite_pos hip)) (λ hin, or.inl (infinite_pos_neg_of_infinite_neg hin)), λ hi, or.cases_on hi (λ hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn)) (λ hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))⟩ lemma not_infinite_of_infinitesimal {x : ℝ*} : infinitesimal x → ¬ infinite x := λ hi hI, have hi' : _ := (hi 2 zero_lt_two), or.dcases_on hI (λ hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm)) (λ hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm)) lemma not_infinitesimal_of_infinite {x : ℝ*} : infinite x → ¬ infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal lemma not_infinitesimal_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinitesimal x := λ hp, not_infinitesimal_of_infinite (or.inl hp) lemma not_infinitesimal_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinitesimal x := λ hn, not_infinitesimal_of_infinite (or.inr hn) lemma infinite_pos_iff_infinite_and_pos {x : ℝ*} : infinite_pos x ↔ (infinite x ∧ 0 < x) := ⟨ λ hip, ⟨or.inl hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hip, hip) (λ hin, false.elim (not_lt_of_lt hp (hin 0))) ⟩ lemma infinite_neg_iff_infinite_and_neg {x : ℝ*} : infinite_neg x ↔ (infinite x ∧ x < 0) := ⟨ λ hip, ⟨or.inr hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hin, false.elim (not_lt_of_lt hp (hin 0))) (λ hip, hip) ⟩ lemma infinite_pos_iff_infinite_of_pos {x : ℝ*} (hp : 0 < x) : infinite_pos x ↔ infinite x := by rw [infinite_pos_iff_infinite_and_pos]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hp⟩⟩ lemma infinite_pos_iff_infinite_of_nonneg {x : ℝ*} (hp : 0 ≤ x) : infinite_pos x ↔ infinite x := or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos) (λ h, by rw h.symm; exact ⟨λ hIP, false.elim (not_infinite_zero (or.inl hIP)), λ hI, false.elim (not_infinite_zero hI)⟩) lemma infinite_neg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : infinite_neg x ↔ infinite x := by rw [infinite_neg_iff_infinite_and_neg]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hn⟩⟩ lemma infinite_pos_abs_iff_infinite_abs {x : ℝ*} : infinite_pos (|x|) ↔ infinite (|x|) := infinite_pos_iff_infinite_of_nonneg (abs_nonneg _) lemma infinite_iff_infinite_pos_abs {x : ℝ*} : infinite x ↔ infinite_pos (|x|) := ⟨ λ hi d, or.cases_on hi (λ hip, by rw [abs_of_pos (hip 0)]; exact hip d) (λ hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))), λ hipa, by { rcases (lt_trichotomy x 0) with h | h | h, { exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) }, { exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) }, { exact or.inl (by rwa abs_of_pos h at hipa) } } ⟩ lemma infinite_iff_infinite_abs {x : ℝ*} : infinite x ↔ infinite (|x|) := by rw [←infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] lemma infinite_iff_abs_lt_abs {x : ℝ*} : infinite x ↔ ∀ r : ℝ, (|r| : ℝ*) < |x| := ⟨ λ hI r, (coe_abs r) ▸ infinite_iff_infinite_pos_abs.mp hI (|r|), λ hR, or.cases_on (max_choice x (-x)) (λ h, or.inl $ λ r, lt_of_le_of_lt (le_abs_self _) (h ▸ (hR r))) (λ h, or.inr $ λ r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h ▸ (hR r)))⟩ lemma infinite_pos_add_not_infinite_neg {x y : ℝ*} : infinite_pos x → ¬ infinite_neg y → infinite_pos (x + y) := begin intros hip hnin r, cases not_forall.mp hnin with r₂ hr₂, convert add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂) using 1, simp end lemma not_infinite_neg_add_infinite_pos {x y : ℝ*} : ¬ infinite_neg x → infinite_pos y → infinite_pos (x + y) := λ hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx lemma infinite_neg_add_not_infinite_pos {x y : ℝ*} : infinite_neg x → ¬ infinite_pos y → infinite_neg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add]; exact infinite_pos_add_not_infinite_neg lemma not_infinite_pos_add_infinite_neg {x y : ℝ*} : ¬ infinite_pos x → infinite_neg y → infinite_neg (x + y) := λ hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx lemma infinite_pos_add_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy) lemma infinite_neg_add_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy) lemma infinite_pos_add_not_infinite {x y : ℝ*} : infinite_pos x → ¬ infinite y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2 lemma infinite_neg_add_not_infinite {x y : ℝ*} : infinite_neg x → ¬ infinite y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1 theorem infinite_pos_of_tendsto_top {f : ℕ → ℝ} (hf : tendsto f at_top at_top) : infinite_pos (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_top.mp hf, Exists.cases_on (hf' (r + 1)) $ λ i hi, have hi' : ∀ (a : ℕ), f a < (r + 1) → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | r < f a}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS theorem infinite_neg_of_tendsto_bot {f : ℕ → ℝ} (hf : tendsto f at_top at_bot) : infinite_neg (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_bot.mp hf, Exists.cases_on (hf' (r - 1)) $ λ i hi, have hi' : ∀ (a : ℕ), r - 1 < f a → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | f a < r}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS lemma not_infinite_neg {x : ℝ*} : ¬ infinite x → ¬ infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr lemma not_infinite_add {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x + y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s + r, is_st_add hs hr⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬ infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨ λ hni, Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $ Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ λ r hr s hs, by rw [not_lt] at hr hs; exact ⟨r - 1, s + 1, ⟨ lt_of_lt_of_le (by rw sub_eq_add_neg; norm_num) hr, lt_of_le_of_lt hs (by norm_num)⟩ ⟩, λ hrs, Exists.dcases_on hrs $ λ r hr, Exists.dcases_on hr $ λ s hs, not_or_distrib.mpr ⟨not_forall.mpr ⟨s, lt_asymm (hs.2)⟩, not_forall.mpr ⟨r, lt_asymm (hs.1) ⟩⟩⟩ theorem not_infinite_real (r : ℝ) : ¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact ⟨ r - 1, r + 1, coe_lt_coe.2 $ sub_one_lt r, coe_lt_coe.2 $ lt_add_one r⟩ theorem not_real_of_infinite {x : ℝ*} : infinite x → ∀ r : ℝ, x ≠ r := λ hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi /-! ### Facts about `st` that require some infinite machinery -/ private lemma is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) (hs : s ≠ 0) : is_st (x * y) (r * s) := have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys, have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, is_st_iff_abs_sub_lt_delta.mpr $ λ d hd, calc |x * y - r * s| = |x * (y - s) + (x - r) * s| : by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] ... ≤ |x * (y - s)| + |(x - r) * s| : abs_add _ _ ... ≤ |x| * |y - s| + |x - r| * |s| : by simp only [abs_mul] ... ≤ |x| * ((d / t) / 2 : ℝ) + ((d / |s|) / 2 : ℝ) * |s| : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $ coe_pos.1 $ lt_of_le_of_lt (abs_nonneg x) ht) $ abs_nonneg _) (mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $ abs_pos.2 hs) $ abs_nonneg _) ... = (d / 2 * (|x| / t) + d / 2 : ℝ*) : by { push_cast [-filter.germ.const_div], -- TODO: Why wasn't `hyperreal.coe_div` used? have : (|s| : ℝ*) ≠ 0, by simpa, have : (2 : ℝ*) ≠ 0 := two_ne_zero, field_simp [*, add_mul, mul_add, mul_assoc, mul_comm, mul_left_comm] } ... < (d / 2 * 1 + d / 2 : ℝ*) : add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $ half_pos $ coe_pos.2 hd) _ ... = (d : ℝ*) : by rw [mul_one, add_halves] lemma is_st_mul {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : is_st (x * y) (r * s) := have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, begin by_cases hs : s = 0, { apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd (coe_pos.1 (lt_of_le_of_lt (abs_nonneg x) ht))), rw [hs, coe_zero, sub_zero] at hys', rw [hs, mul_zero, coe_zero, sub_zero, abs_mul, mul_comm, ←div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ←coe_div], exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) }, exact is_st_mul' hxr hys hs, end --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY lemma not_infinite_mul {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x * y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s * r, is_st_mul hs hr⟩ --- lemma st_add {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x + y) = st x + st y := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_add hx hy), have hxy' : _ := is_st_add hx' hy', is_st_unique hxy hxy' lemma st_neg (x : ℝ*) : st (-x) = - st x := if h : infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h)) lemma st_mul {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x * y) = (st x) * (st y) := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_mul hx hy), have hxy' : _ := is_st_mul hx' hy', is_st_unique hxy hxy' /-! ### Basic lemmas about infinitesimal -/ theorem infinitesimal_def {x : ℝ*} : infinitesimal x ↔ (∀ r : ℝ, 0 < r → -(r : ℝ*) < x ∧ x < r) := ⟨ λ hi r hr, by { convert (hi r hr); simp }, λ hi d hd, by { convert (hi d hd); simp } ⟩ theorem lt_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → x < r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → -↑r < x := λ hi r hr, ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r < 0 → ↑r < x := λ hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1; exact (neg_neg ↑r).symm theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → |x| < |r| := ⟨ λ hi r hr, abs_lt.mpr (by rw ←coe_abs; exact infinitesimal_def.mp hi (|r|) (abs_pos.2 hr)), λ hR, infinitesimal_def.mpr $ λ r hr, abs_lt.mp $ (abs_of_pos $ coe_pos.2 hr) ▸ hR r $ ne_of_gt hr ⟩ lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0 lemma zero_of_infinitesimal_real {r : ℝ} : infinitesimal r → r = 0 := eq_of_is_st_real lemma zero_iff_infinitesimal_real {r : ℝ} : infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, λ hr, by rw hr; exact infinitesimal_zero⟩ lemma infinitesimal_add {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x + y) := by simpa only [add_zero] using is_st_add hx hy lemma infinitesimal_neg {x : ℝ*} (hx : infinitesimal x) : infinitesimal (-x) := by simpa only [neg_zero] using is_st_neg hx lemma infinitesimal_neg_iff {x : ℝ*} : infinitesimal x ↔ infinitesimal (-x) := ⟨infinitesimal_neg, λ h, (neg_neg x) ▸ @infinitesimal_neg (-x) h⟩ lemma infinitesimal_mul {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x * y) := by simpa only [mul_zero] using is_st_mul hx hy theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} : tendsto f at_top (𝓝 0) → infinitesimal (of_seq f) := λ hf d hd, by rw [sub_eq_add_neg, ←coe_neg, ←coe_add, ←coe_add, zero_add, zero_add]; exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ theorem infinitesimal_epsilon : infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat lemma not_real_of_infinitesimal_ne_zero (x : ℝ*) : infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ r := λ hi hx r hr, hx $ hr.trans $ coe_eq_zero.2 $ is_st_unique (hr.symm ▸ is_st_refl_real r : is_st x r) hi theorem infinitesimal_sub_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : infinitesimal (x - r) := show is_st (x - r) 0, by { rw [sub_eq_add_neg, ← add_neg_self r], exact is_st_add hxr (is_st_refl_real (-r)) } theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬infinite x) : infinitesimal (x - st x) := infinitesimal_sub_is_st $ is_st_st' hx lemma infinite_pos_iff_infinitesimal_inv_pos {x : ℝ*} : infinite_pos x ↔ (infinitesimal x⁻¹ ∧ 0 < x⁻¹) := ⟨ λ hip, ⟨ infinitesimal_def.mpr $ λ r hr, ⟨ lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip r⁻¹) ⟩, inv_pos.2 $ hip 0 ⟩, λ ⟨hi, hp⟩ r, @classical.by_cases (r = 0) (↑r < x) (λ h, eq.substr h (inv_pos.mp hp)) $ λ h, lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos.2 h))).mp ((infinitesimal_def.mp hi) ((|r|)⁻¹) (inv_pos.2 (abs_pos.2 h))).2) ⟩ lemma infinite_neg_iff_infinitesimal_inv_neg {x : ℝ*} : infinite_neg x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ < 0) := ⟨ λ hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp (infinite_pos_neg_of_infinite_neg hin), by rwa [infinitesimal_neg_iff, ←neg_pos, neg_inv], λ hin, by rwa [←neg_pos, infinitesimal_neg_iff, neg_inv, ←infinite_pos_iff_infinitesimal_inv_pos, ←infinite_neg_iff_infinite_pos_neg] at hin ⟩ theorem infinitesimal_inv_of_infinite {x : ℝ*} : infinite x → infinitesimal x⁻¹ := λ hi, or.cases_on hi (λ hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1) (λ hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1) theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : infinitesimal x⁻¹ ) : infinite x := begin cases (lt_or_gt_of_ne h0) with hn hp, { exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) }, { exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) } end theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : infinite x ↔ infinitesimal x⁻¹ := ⟨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 ⟩ lemma infinitesimal_pos_iff_infinite_pos_inv {x : ℝ*} : infinite_pos x⁻¹ ↔ (infinitesimal x ∧ 0 < x) := by convert infinite_pos_iff_infinitesimal_inv_pos; simp only [inv_inv₀] lemma infinitesimal_neg_iff_infinite_neg_inv {x : ℝ*} : infinite_neg x⁻¹ ↔ (infinitesimal x ∧ x < 0) := by convert infinite_neg_iff_infinitesimal_inv_neg; simp only [inv_inv₀] theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : infinitesimal x ↔ infinite x⁻¹ := by convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm; simp only [inv_inv₀] /-! ### `st` stuff that requires infinitesimal machinery -/ theorem is_st_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : tendsto f at_top (𝓝 r)) : is_st (of_seq f) r := have hg : tendsto (λ n, f n - r) at_top (𝓝 0) := (sub_self r) ▸ (hf.sub tendsto_const_nhds), by rw [←(zero_add r), ←(sub_add_cancel f (λ n, r))]; exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) lemma is_st_inv {x : ℝ*} {r : ℝ} (hi : ¬ infinitesimal x) : is_st x r → is_st x⁻¹ r⁻¹ := λ hxr, have h : x ≠ 0 := (λ h, hi (h.symm ▸ infinitesimal_zero)), have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi, Exists.cases_on H $ λ s hs, have H' : is_st 1 (r * s) := mul_inv_cancel h ▸ is_st_mul hxr hs, have H'' : s = r⁻¹ := one_div r ▸ eq_one_div_of_mul_eq_one (eq_of_is_st_real H').symm, H'' ▸ hs lemma st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := begin by_cases h0 : x = 0, rw [h0, inv_zero, ←coe_zero, st_id_real, inv_zero], by_cases h1 : infinitesimal x, rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero], by_cases h2 : infinite x, rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero], exact st_of_is_st (is_st_inv h1 (is_st_st' h2)), end /-! ### Infinite stuff that requires infinitesimal machinery -/ lemma infinite_pos_omega : infinite_pos ω := infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ lemma infinite_omega : infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → 0 < y → infinite_pos (x * y) := λ hx hy₁ hy₂ r, have hy₁' : _ := not_forall.mp (by rw infinitesimal_def at hy₁; exact hy₁), Exists.dcases_on hy₁' $ λ r₁ hy₁'', have hyr : _ := by rw [not_imp, ←abs_lt, not_lt, abs_of_pos hy₂] at hy₁''; exact hy₁'', by rw [←div_mul_cancel r (ne_of_gt hyr.1), coe_mul]; exact mul_lt_mul (hx (r / r₁)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0)) lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_pos y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → y < 0 → infinite_pos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, ←neg_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_neg y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y < 0 → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_pos y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → 0 < y → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_neg y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_neg_mul_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_pos_mul_infinite_neg {x y : ℝ*} : infinite_pos x → infinite_neg y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_neg_mul_infinite_pos {x y : ℝ*} : infinite_neg x → infinite_pos y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : infinite x → ¬ infinitesimal y → infinite (x * y) := λ hx hy, have h0 : y < 0 ∨ 0 < y := lt_or_gt_of_ne (λ H0, hy (eq.substr H0 (is_st_refl_real 0))), or.dcases_on hx (or.dcases_on h0 (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0))) (or.dcases_on h0 (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0))) lemma infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬ infinitesimal x → infinite y → infinite (x * y) := λ hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx lemma infinite_mul_infinite {x y : ℝ*} : infinite x → infinite y → infinite (x * y) := λ hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) end hyperreal
be7daab3844a93ea63fa3887f1a6bbdc81fc82d1
7b02c598aa57070b4cf4fbfe2416d0479220187f
/algebra/arrow_group.hlean
eb8001f107187042c1dfe1c976a4ec3159983561
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,182
hlean
/- various groups of maps. Most importantly we define a group structure on trunc 0 (A →* Ω B), which is used in the definition of cohomology -/ --author: Floris van Doorn import algebra.group_theory ..pointed ..pointed_pi eq2 open pi pointed algebra group eq equiv is_trunc trunc susp namespace group /- We first define the group structure on A →* Ω B (except for truncatedness). Instead of Ω B, we could also choose any infinity group. However, we need various 2-coherences, so it's easier to just do it for the loop space. -/ definition pmap_mul [constructor] {A B : Type*} (f g : A →* Ω B) : A →* Ω B := pmap.mk (λa, f a ⬝ g a) (respect_pt f ◾ respect_pt g ⬝ !idp_con) definition pmap_inv [constructor] {A B : Type*} (f : A →* Ω B) : A →* Ω B := pmap.mk (λa, (f a)⁻¹ᵖ) (respect_pt f)⁻² /- we prove some coherences of the multiplication. We don't need them for the group structure, but they are used to show that cohomology satisfies the Eilenberg-Steenrod axioms -/ definition ap1_pmap_mul {X Y : Type*} (f g : X →* Ω Y) : Ω→ (pmap_mul f g) ~* pmap_mul (Ω→ f) (Ω→ g) := begin fconstructor, { intro p, esimp, refine ap1_gen_con_left (respect_pt f) (respect_pt f) (respect_pt g) (respect_pt g) p ⬝ _, refine !whisker_right_idp ◾ !whisker_left_idp2, }, { refine !con.assoc ⬝ _, refine _ ◾ idp ⬝ _, rotate 1, rexact ap1_gen_con_left_idp (respect_pt f) (respect_pt g), esimp, refine !con.assoc ⬝ _, apply whisker_left, apply inv_con_eq_idp, refine !con2_con_con2 ⬝ ap011 concat2 _ _: refine eq_of_square (!natural_square ⬝hp !ap_id) ⬝ !con_idp } end definition pmap_mul_pcompose {A B C : Type*} (g h : B →* Ω C) (f : A →* B) : pmap_mul g h ∘* f ~* pmap_mul (g ∘* f) (h ∘* f) := begin fconstructor, { intro p, reflexivity }, { esimp, refine !idp_con ⬝ _, refine !con2_con_con2⁻¹ ⬝ whisker_right _ _, refine !ap_eq_ap011⁻¹ } end definition pcompose_pmap_mul {A B C : Type*} (h : B →* C) (f g : A →* Ω B) : Ω→ h ∘* pmap_mul f g ~* pmap_mul (Ω→ h ∘* f) (Ω→ h ∘* g) := begin fconstructor, { intro p, exact ap1_con h (f p) (g p) }, { refine whisker_left _ !con2_con_con2⁻¹ ⬝ _, refine !con.assoc⁻¹ ⬝ _, refine whisker_right _ (eq_of_square !ap1_gen_con_natural) ⬝ _, refine !con.assoc ⬝ whisker_left _ _, apply ap1_gen_con_idp } end definition loop_psusp_intro_pmap_mul {X Y : Type*} (f g : psusp X →* Ω Y) : loop_psusp_intro (pmap_mul f g) ~* pmap_mul (loop_psusp_intro f) (loop_psusp_intro g) := pwhisker_right _ !ap1_pmap_mul ⬝* !pmap_mul_pcompose definition inf_group_pmap [constructor] [instance] (A B : Type*) : inf_group (A →* Ω B) := begin fapply inf_group.mk, { exact pmap_mul }, { intro f g h, fapply pmap_eq, { intro a, exact con.assoc (f a) (g a) (h a) }, { rexact eq_of_square (con2_assoc (respect_pt f) (respect_pt g) (respect_pt h)) }}, { apply pconst }, { intros f, fapply pmap_eq, { intro a, exact one_mul (f a) }, { esimp, apply eq_of_square, refine _ ⬝vp !ap_id, apply natural_square_tr }}, { intros f, fapply pmap_eq, { intro a, exact mul_one (f a) }, { reflexivity }}, { exact pmap_inv }, { intro f, fapply pmap_eq, { intro a, exact con.left_inv (f a) }, { exact !con_left_inv_idp⁻¹ }}, end definition group_trunc_pmap [constructor] [instance] (A B : Type*) : group (trunc 0 (A →* Ω B)) := !trunc_group definition Group_trunc_pmap [reducible] [constructor] (A B : Type*) : Group := Group.mk (trunc 0 (A →* Ω B)) _ definition Group_trunc_pmap_homomorphism [constructor] {A A' B : Type*} (f : A' →* A) : Group_trunc_pmap A B →g Group_trunc_pmap A' B := begin fapply homomorphism.mk, { apply trunc_functor, intro g, exact g ∘* f}, { intro g h, induction g with g, induction h with h, apply ap tr, fapply pmap_eq, { intro a, reflexivity }, { refine _ ⬝ !idp_con⁻¹, refine whisker_right _ !ap_con_fn ⬝ _, apply con2_con_con2 }} end definition Group_trunc_pmap_isomorphism [constructor] {A A' B : Type*} (f : A' ≃* A) : Group_trunc_pmap A B ≃g Group_trunc_pmap A' B := begin apply isomorphism.mk (Group_trunc_pmap_homomorphism f), apply @is_equiv_trunc_functor, exact to_is_equiv (pequiv_ppcompose_right f), end definition Group_trunc_pmap_isomorphism_refl (A B : Type*) (x : Group_trunc_pmap A B) : Group_trunc_pmap_isomorphism (pequiv.refl A) x = x := begin induction x, apply ap tr, apply eq_of_phomotopy, apply pcompose_pid end definition Group_trunc_pmap_pid [constructor] {A B : Type*} (f : Group_trunc_pmap A B) : Group_trunc_pmap_homomorphism (pid A) f = f := begin induction f with f, apply ap tr, apply eq_of_phomotopy, apply pcompose_pid end definition Group_trunc_pmap_pconst [constructor] {A A' B : Type*} (f : Group_trunc_pmap A B) : Group_trunc_pmap_homomorphism (pconst A' A) f = 1 := begin induction f with f, apply ap tr, apply eq_of_phomotopy, apply pcompose_pconst end definition Group_trunc_pmap_pcompose [constructor] {A A' A'' B : Type*} (f : A' →* A) (f' : A'' →* A') (g : Group_trunc_pmap A B) : Group_trunc_pmap_homomorphism (f ∘* f') g = Group_trunc_pmap_homomorphism f' (Group_trunc_pmap_homomorphism f g) := begin induction g with g, apply ap tr, apply eq_of_phomotopy, exact !passoc⁻¹* end definition Group_trunc_pmap_phomotopy [constructor] {A A' B : Type*} {f f' : A' →* A} (p : f ~* f') : @Group_trunc_pmap_homomorphism _ _ B f ~ Group_trunc_pmap_homomorphism f' := begin intro g, induction g, exact ap tr (eq_of_phomotopy (pwhisker_left a p)) end definition Group_trunc_pmap_phomotopy_refl {A A' B : Type*} (f : A' →* A) (x : Group_trunc_pmap A B) : Group_trunc_pmap_phomotopy (phomotopy.refl f) x = idp := begin induction x, refine ap02 tr _, refine ap eq_of_phomotopy _ ⬝ !eq_of_phomotopy_refl, apply pwhisker_left_refl end definition ab_inf_group_pmap [constructor] [instance] (A B : Type*) : ab_inf_group (A →* Ω (Ω B)) := ⦃ab_inf_group, inf_group_pmap A (Ω B), mul_comm := begin intro f g, fapply pmap_eq, { intro a, exact eckmann_hilton (f a) (g a) }, { rexact eq_of_square (eckmann_hilton_con2 (respect_pt f) (respect_pt g)) } end⦄ definition ab_group_trunc_pmap [constructor] [instance] (A B : Type*) : ab_group (trunc 0 (A →* Ω (Ω B))) := !trunc_ab_group definition AbGroup_trunc_pmap [reducible] [constructor] (A B : Type*) : AbGroup := AbGroup.mk (trunc 0 (A →* Ω (Ω B))) _ /- Group of dependent functions whose codomain is a group -/ definition group_pi [instance] [constructor] {A : Type} (P : A → Type) [Πa, group (P a)] : group (Πa, P a) := begin fapply group.mk, { apply is_trunc_pi }, { intro f g a, exact f a * g a }, { intros, apply eq_of_homotopy, intro a, apply mul.assoc }, { intro a, exact 1 }, { intros, apply eq_of_homotopy, intro a, apply one_mul }, { intros, apply eq_of_homotopy, intro a, apply mul_one }, { intro f a, exact (f a)⁻¹ }, { intros, apply eq_of_homotopy, intro a, apply mul.left_inv } end definition Group_pi [constructor] {A : Type} (P : A → Group) : Group := Group.mk (Πa, P a) _ /- we use superscript in the following notation, because otherwise we can never write something like `Πg h : G, _` anymore -/ notation `Πᵍ` binders `, ` r:(scoped P, Group_pi P) := r definition Group_pi_intro [constructor] {A : Type} {G : Group} {P : A → Group} (f : Πa, G →g P a) : G →g Πᵍ a, P a := begin fconstructor, { intro g a, exact f a g }, { intro g h, apply eq_of_homotopy, intro a, exact respect_mul (f a) g h } end /- Group of dependent functions into a loop space -/ definition ppi_mul [constructor] {A : Type*} {B : A → Type*} (f g : Π*a, Ω (B a)) : Π*a, Ω (B a) := proof ppi.mk (λa, f a ⬝ g a) (ppi_resp_pt f ◾ ppi_resp_pt g ⬝ !idp_con) qed definition ppi_inv [constructor] {A : Type*} {B : A → Type*} (f : Π*a, Ω (B a)) : Π*a, Ω (B a) := proof ppi.mk (λa, (f a)⁻¹ᵖ) (ppi_resp_pt f)⁻² qed definition inf_group_ppi [constructor] [instance] {A : Type*} (B : A → Type*) : inf_group (Π*a, Ω (B a)) := begin fapply inf_group.mk, { exact ppi_mul }, { intro f g h, fapply ppi_eq, { intro a, exact con.assoc (f a) (g a) (h a) }, { rexact eq_of_square (con2_assoc (ppi_resp_pt f) (ppi_resp_pt g) (ppi_resp_pt h)) }}, { apply ppi_const }, { intros f, fapply ppi_eq, { intro a, exact one_mul (f a) }, { esimp, apply eq_of_square, refine _ ⬝vp !ap_id, apply natural_square_tr }}, { intros f, fapply ppi_eq, { intro a, exact mul_one (f a) }, { reflexivity }}, { exact ppi_inv }, { intro f, fapply ppi_eq, { intro a, exact con.left_inv (f a) }, { exact !con_left_inv_idp⁻¹ }}, end definition group_trunc_ppi [constructor] [instance] {A : Type*} (B : A → Type*) : group (trunc 0 (Π*a, Ω (B a))) := !trunc_group definition Group_trunc_ppi [reducible] [constructor] {A : Type*} (B : A → Type*) : Group := Group.mk (trunc 0 (Π*a, Ω (B a))) _ definition ab_inf_group_ppi [constructor] [instance] {A : Type*} (B : A → Type*) : ab_inf_group (Π*a, Ω (Ω (B a))) := ⦃ab_inf_group, inf_group_ppi (λa, Ω (B a)), mul_comm := begin intro f g, fapply ppi_eq, { intro a, exact eckmann_hilton (f a) (g a) }, { rexact eq_of_square (eckmann_hilton_con2 (ppi_resp_pt f) (ppi_resp_pt g)) } end⦄ definition ab_group_trunc_ppi [constructor] [instance] {A : Type*} (B : A → Type*) : ab_group (trunc 0 (Π*a, Ω (Ω (B a)))) := !trunc_ab_group definition AbGroup_trunc_ppi [reducible] [constructor] {A : Type*} (B : A → Type*) : AbGroup := AbGroup.mk (trunc 0 (Π*a, Ω (Ω (B a)))) _ end group
8bcc6e1a99af1ccecf2e51a2f6329006cb8595e0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/free_abelian_group_finsupp.lean
440e270201d19d405dc90ee7620f90ffaa2f7491
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,492
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import group_theory.free_abelian_group import data.finsupp.basic /-! # Isomorphism between `free_abelian_group X` and `X →₀ ℤ` In this file we construct the canonical isomorphism between `free_abelian_group X` and `X →₀ ℤ`. We use this to transport the notion of `support` from `finsupp` to `free_abelian_group`. ## Main declarations - `free_abelian_group.equiv_finsupp`: group isomorphism between `free_abelian_group X` and `X →₀ ℤ` - `free_abelian_group.coeff`: the multiplicity of `x : X` in `a : free_abelian_group X` - `free_abelian_group.support`: the finset of `x : X` that occur in `a : free_abelian_group X` -/ noncomputable theory open_locale big_operators variables {X : Type*} /-- The group homomorphism `free_abelian_group X →+ (X →₀ ℤ)`. -/ def free_abelian_group.to_finsupp : free_abelian_group X →+ (X →₀ ℤ) := free_abelian_group.lift $ λ x, finsupp.single x (1 : ℤ) /-- The group homomorphism `(X →₀ ℤ) →+ free_abelian_group X`. -/ def finsupp.to_free_abelian_group : (X →₀ ℤ) →+ free_abelian_group X := finsupp.lift_add_hom $ λ x, (smul_add_hom ℤ (free_abelian_group X)).flip (free_abelian_group.of x) open finsupp free_abelian_group @[simp] lemma finsupp.to_free_abelian_group_comp_single_add_hom (x : X) : finsupp.to_free_abelian_group.comp (finsupp.single_add_hom x) = (smul_add_hom ℤ (free_abelian_group X)).flip (of x) := begin ext, simp only [add_monoid_hom.coe_comp, finsupp.single_add_hom_apply, function.comp_app, one_smul, to_free_abelian_group, finsupp.lift_add_hom_apply_single] end @[simp] lemma free_abelian_group.to_finsupp_comp_to_free_abelian_group : to_finsupp.comp to_free_abelian_group = add_monoid_hom.id (X →₀ ℤ) := begin ext x y, simp only [add_monoid_hom.id_comp], rw [add_monoid_hom.comp_assoc, finsupp.to_free_abelian_group_comp_single_add_hom], simp only [to_finsupp, add_monoid_hom.coe_comp, finsupp.single_add_hom_apply, function.comp_app, one_smul, lift.of, add_monoid_hom.flip_apply, smul_add_hom_one, add_monoid_hom.id_apply], end @[simp] lemma finsupp.to_free_abelian_group_comp_to_finsupp : to_free_abelian_group.comp to_finsupp = add_monoid_hom.id (free_abelian_group X) := begin ext, simp only [to_free_abelian_group, to_finsupp, finsupp.lift_add_hom_apply_single, add_monoid_hom.coe_comp, function.comp_app, one_smul, add_monoid_hom.id_apply, lift.of, add_monoid_hom.flip_apply, smul_add_hom_one], end @[simp] lemma finsupp.to_free_abelian_group_to_finsupp {X} (x : free_abelian_group X) : x.to_finsupp.to_free_abelian_group = x := by rw [← add_monoid_hom.comp_apply, finsupp.to_free_abelian_group_comp_to_finsupp, add_monoid_hom.id_apply] namespace free_abelian_group open finsupp variable {X} @[simp] lemma to_finsupp_of (x : X) : to_finsupp (of x) = finsupp.single x 1 := by simp only [to_finsupp, lift.of] @[simp] lemma to_finsupp_to_free_abelian_group (f : X →₀ ℤ) : f.to_free_abelian_group.to_finsupp = f := by rw [← add_monoid_hom.comp_apply, to_finsupp_comp_to_free_abelian_group, add_monoid_hom.id_apply] variable (X) /-- The additive equivalence between `free_abelian_group X` and `(X →₀ ℤ)`. -/ @[simps] def equiv_finsupp : free_abelian_group X ≃+ (X →₀ ℤ) := { to_fun := to_finsupp, inv_fun := to_free_abelian_group, left_inv := to_free_abelian_group_to_finsupp, right_inv := to_finsupp_to_free_abelian_group, map_add' := to_finsupp.map_add } variable {X} /-- `coeff x` is the additive group homomorphism `free_abelian_group X →+ ℤ` that sends `a` to the multiplicity of `x : X` in `a`. -/ def coeff (x : X) : free_abelian_group X →+ ℤ := (finsupp.apply_add_hom x).comp to_finsupp /-- `support a` for `a : free_abelian_group X` is the finite set of `x : X` that occur in the formal sum `a`. -/ def support (a : free_abelian_group X) : finset X := a.to_finsupp.support lemma mem_support_iff (x : X) (a : free_abelian_group X) : x ∈ a.support ↔ coeff x a ≠ 0 := by { rw [support, finsupp.mem_support_iff], exact iff.rfl } lemma not_mem_support_iff (x : X) (a : free_abelian_group X) : x ∉ a.support ↔ coeff x a = 0 := by { rw [support, finsupp.not_mem_support_iff], exact iff.rfl } @[simp] lemma support_zero : support (0 : free_abelian_group X) = ∅ := by simp only [support, finsupp.support_zero, add_monoid_hom.map_zero] @[simp] lemma support_of (x : X) : support (of x) = {x} := by simp only [support, to_finsupp_of, finsupp.support_single_ne_zero (one_ne_zero)] @[simp] lemma support_neg (a : free_abelian_group X) : support (-a) = support a := by simp only [support, add_monoid_hom.map_neg, finsupp.support_neg] @[simp] lemma support_gsmul (k : ℤ) (h : k ≠ 0) (a : free_abelian_group X) : support (k • a) = support a := begin ext x, simp only [mem_support_iff, add_monoid_hom.map_gsmul], simp only [h, gsmul_int_int, false_or, ne.def, mul_eq_zero] end @[simp] lemma support_nsmul (k : ℕ) (h : k ≠ 0) (a : free_abelian_group X) : support (k • a) = support a := by { apply support_gsmul k _ a, exact_mod_cast h } open_locale classical lemma support_add (a b : free_abelian_group X) : (support (a + b)) ⊆ a.support ∪ b.support := begin simp only [support, add_monoid_hom.map_add], apply finsupp.support_add end end free_abelian_group
8f47f32021578001d97b6f57b3b41764bd2328b0
ddf69e0b8ad10bfd251aa1fb492bd92f064768ec
/src/algebra/gcd_monoid.lean
e6579519c9b60f88737925398533dc8eb0f253d0
[ "Apache-2.0" ]
permissive
MaboroshiChan/mathlib
db1c1982df384a2604b19a5e1f5c6464c7c76de1
7f74e6b35f6bac86b9218250e83441ac3e17264c
refs/heads/master
1,671,993,587,476
1,601,911,102,000
1,601,911,102,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,077
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker TODO: Provide a GCD monoid instance for `ℕ`, port GCD facts about nats TODO: Generalize normalization monoids commutative (cancellative) monoids with or without zero TODO: Generalize GCD monoid to not require normalization in all cases -/ import algebra.associated import data.nat.basic import data.int.gcd /-! # Monoids with normalization functions, `gcd`, and `lcm` This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `integral_domain`s. ## Main Definitions * `normalization_monoid` * `gcd_monoid` ## Implementation Notes * `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This definition as currently implemented does casework on `0`. * `gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids without zero. ## TODO * Provide a GCD monoid instance for `ℕ`, port GCD facts about nats, definition of coprime * Generalize normalization monoids to commutative (cancellative) monoids with or without zero * Generalize GCD monoid to not require normalization in all cases ## Tags divisibility, gcd, lcm, normalize -/ variables {α : Type*} set_option old_structure_cmd true /-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_monoid (α : Type*) [nontrivial α] [comm_cancel_monoid_with_zero α] := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 /-- Chooses an element of each associate class, by multiplying by `norm_unit` -/ def normalize : α →* α := { to_fun := λ x, x * norm_unit x, map_one' := by rw [norm_unit_one, units.coe_one, mul_one], map_mul' := λ x y, classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy, by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], } theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm lemma associates.mk_normalize {x : α} : associates.mk (normalize x) = associates.mk x := associates.mk_eq_mk_iff_associated.2 normalize_associated @[simp] lemma normalize_apply {x : α} : normalize x = x * norm_unit x := rfl @[simp] lemma normalize_zero : normalize (0 : α) = 0 := by simp @[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by simp lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ @[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba --can be proven by simp lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := units.dvd_mul_right --can be proven by simp lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := units.mul_right_dvd end normalization_monoid namespace associates variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] local attribute [instance] associated.setoid /-- Maps an element of `associates` back to the normalized element of its associate class -/ protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates /-- GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] extends normalization_monoid α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_monoid.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_monoid.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize.map_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) theorem gcd_eq_of_associated_left {m n : α} (h : associated m n) (k : α) : gcd m k = gcd n k := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd (dvd_of_associated h) (dvd_refl _)) (gcd_dvd_gcd (dvd_of_associated h.symm) (dvd_refl _)) theorem gcd_eq_of_associated_right {m n : α} (h : associated m n) (k : α) : gcd k m = gcd k n := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd (dvd_refl _) (dvd_of_associated h)) (gcd_dvd_gcd (dvd_refl _) (dvd_of_associated h.symm)) end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize.map_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize.map_mul, normalize_gcd, one_mul, mul_right_inj' h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd units.coe_dvd (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize.map_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) theorem lcm_eq_of_associated_left {m n : α} (h : associated m n) (k : α) : lcm m k = lcm n k := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm (dvd_of_associated h) (dvd_refl _)) (lcm_dvd_lcm (dvd_of_associated h.symm) (dvd_refl _)) theorem lcm_eq_of_associated_right {m n : α} (h : associated m n) (k : α) : lcm k m = lcm k n := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm (dvd_refl _) (dvd_of_associated h)) (lcm_dvd_lcm (dvd_refl _) (dvd_of_associated h.symm)) end lcm namespace gcd_monoid theorem prime_of_irreducible {x : α} (hi: irreducible x) : prime x := ⟨hi.ne_zero, ⟨hi.1, λ a b h, begin cases gcd_dvd_left x a with y hy, cases hi.2 _ _ hy with hu hu; cases hu with u hu, { right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h, rw gcd_mul_right, rw ← hu, apply dvd_of_associated, transitivity (normalize b), symmetry, use u, apply mul_comm, apply normalize_associated, }, { left, rw [hy, ← hu], transitivity, {apply dvd_of_associated, symmetry, use u}, apply gcd_dvd_right, } end ⟩⟩ theorem irreducible_iff_prime {p : α} : irreducible p ↔ prime p := ⟨prime_of_irreducible, irreducible_of_prime⟩ end gcd_monoid end gcd_monoid namespace int section normalization_monoid instance : normalization_monoid ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos (le_refl _), norm_unit_mul := assume a b hna hnb, begin cases hna.lt_or_lt with ha ha; cases hnb.lt_or_lt with hb hb; simp [mul_nonneg_iff, ha.le, ha.not_le, hb.le, hb.not_le] end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by simp [@neg_lt ℤ _ 1 0])), } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end end normalization_monoid /-- ℤ specific version of least common multiple. -/ def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j) theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl section gcd_monoid theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _ theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _ theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) := by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul] instance : gcd_monoid ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, normalize_gcd := assume a b, normalize_coe_nat _, gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _, .. int.normalization_monoid } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_monoid.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_monoid.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_monoid.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_monoid.lcm i j) = int.lcm i j := rfl end gcd_monoid theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd] @[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _ @[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _ theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero) theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero) theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := by rw [← int.coe_nat_eq_coe_nat_iff, int.coe_nat_zero, coe_gcd, gcd_eq_zero_iff] theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / nat_abs k := by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2]; exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2) theorem gcd_div_gcd_div_gcd {i j : ℤ} (H : 0 < gcd i j) : gcd (i / gcd i j) (j / gcd i j) = 1 := begin rw [gcd_div (gcd_dvd_left i j) (gcd_dvd_right i j)], rw [nat_abs_of_nat, nat.div_self H] end theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j) theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i := nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _) (by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j := by rw [gcd_comm, gcd_eq_left H] theorem ne_zero_of_gcd {x y : ℤ} (hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 := begin contrapose! hc, rw [hc.left, hc.right, gcd_zero_right, nat_abs_zero] end theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) : ∃ (m' n' : ℤ), gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, gcd_div_gcd_div_gcd H, (int.div_mul_cancel (gcd_dvd_left m n)).symm, (int.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) : ∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_gcd_one H in ⟨_, m', n', H, h⟩ theorem pow_dvd_pow_iff {m n : ℤ} {k : ℕ} (k0 : 0 < k) : m ^ k ∣ n ^ k ↔ m ∣ n := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, apply int.nat_abs_dvd_abs_iff.mp, apply (nat.pow_dvd_pow_iff k0).mp, rw [← int.nat_abs_pow, ← int.nat_abs_pow], exact int.nat_abs_dvd_abs_iff.mpr h end /- lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_comm] theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_assoc] @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_left _ _ theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_right _ _ theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := by rw [coe_lcm]; exact lcm_dvd end int theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) := ⟨λ hp, ⟨nat.pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one, λ a b, hp.dvd_mul.1⟩, λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩, λ a h, let ⟨b, hab⟩ := h in (hp.2.2 a b (hab ▸ dvd_refl _)).elim (λ ha, or.inr (nat.dvd_antisymm h ha)) (λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb (hab.symm ▸ dvd_mul_left _ _), (nat.mul_right_inj (show 0 < p, from nat.pos_of_ne_zero hp.1)).1 $ by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩ lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt is_unit_int.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ /-- Maps an associate class of integers consisting of `-n, n` to `n : ℕ` -/ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { intro n, dsimp, rw [associates.out_mk ↑n, ← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs := begin apply (nat.prime.dvd_mul hp).mp, rw ← int.nat_abs_mul, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n := begin rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left], exact int.prime.dvd_mul hp h end lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m := begin cases int.prime.dvd_mul hp h with hp2 hpp, { apply or.intro_left, exact le_antisymm (nat.le_of_dvd zero_lt_two hp2) (nat.prime.two_le hp) }, { apply or.intro_right, rw [pow_two, int.nat_abs_mul] at hpp, exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)} end section unique_unit instance nat.unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } variables [comm_cancel_monoid_with_zero α] [unique (units α)] lemma units_eq_one (u : units α) : u = 1 := subsingleton.elim u 1 variable [nontrivial α] @[priority 100] -- see Note [lower instance priority] instance normalization_monoid_of_unique_units : normalization_monoid α := { norm_unit := λ x, 1, norm_unit_zero := rfl, norm_unit_mul := λ x y hx hy, (mul_one 1).symm, norm_unit_coe_units := λ u, subsingleton.elim _ _ } @[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl @[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x end unique_unit section integral_domain variables [integral_domain α] [gcd_monoid α] lemma gcd_eq_of_dvd_sub_right {a b c : α} (h : a ∣ b - c) : gcd a b = gcd a c := begin apply dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _); rw dvd_gcd_iff; refine ⟨gcd_dvd_left _ _, _⟩, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a b with ⟨e, he⟩, rcases gcd_dvd_left a b with ⟨f, hf⟩, use e - f * d, rw [mul_sub, ← he, ← mul_assoc, ← hf, ← hd, sub_sub_cancel] }, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a c with ⟨e, he⟩, rcases gcd_dvd_left a c with ⟨f, hf⟩, use e + f * d, rw [mul_add, ← he, ← mul_assoc, ← hf, ← hd, ← add_sub_assoc, add_comm c b, add_sub_cancel] } end lemma gcd_eq_of_dvd_sub_left {a b c : α} (h : a ∣ b - c) : gcd b a = gcd c a := by rw [gcd_comm _ a, gcd_comm _ a, gcd_eq_of_dvd_sub_right h] end integral_domain
6f75ef17cfddd6bdf31d203b6aae329b5b79f516
63abd62053d479eae5abf4951554e1064a4c45b4
/src/field_theory/minimal_polynomial.lean
69bc6a414c5ed58b96e2cfe07e4ff8e8885ffeae
[ "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
8,745
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import ring_theory.integral_closure import data.polynomial.field_division /-! # Minimal polynomials This file defines the minimal polynomial of an element x of an A-algebra B, under the assumption that x is integral over A. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ universes u v w open_locale classical open polynomial set function variables {α : Type u} {β : Type v} section min_poly_def variables [comm_ring α] [ring β] [algebra α β] /-- Let `B` be an `A`-algebra, and `x` an element of `B` that is integral over `A` so we have some term `hx : is_integral A x`. The minimal polynomial `minimal_polynomial hx` of `x` is a monic polynomial of smallest degree that has `x` as its root. For instance, if `V` is a `K`-vector space for some field `K`, and `f : V →ₗ[K] V` then the minimal polynomial of `f` is `minimal_polynomial f.is_integral`. -/ noncomputable def minimal_polynomial {x : β} (hx : is_integral α x) : polynomial α := well_founded.min degree_lt_wf _ hx end min_poly_def namespace minimal_polynomial section ring variables [comm_ring α] [ring β] [algebra α β] variables {x : β} (hx : is_integral α x) /--A minimal polynomial is monic.-/ lemma monic : monic (minimal_polynomial hx) := (well_founded.min_mem degree_lt_wf _ hx).1 /--An element is a root of its minimal polynomial.-/ @[simp] lemma aeval : aeval x (minimal_polynomial hx) = 0 := (well_founded.min_mem degree_lt_wf _ hx).2 /--The defining property of the minimal polynomial of an element x: it is the monic polynomial with smallest degree that has x as its root.-/ lemma min {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minimal_polynomial hx) ≤ degree p := le_of_not_lt $ well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩ end ring section field variables [field α] section ring variables [ring β] [algebra α β] variables {x : β} (hx : is_integral α x) /--A minimal polynomial is nonzero.-/ lemma ne_zero : (minimal_polynomial hx) ≠ 0 := ne_zero_of_monic (monic hx) /--If an element x is a root of a nonzero polynomial p, then the degree of p is at least the degree of the minimal polynomial of x.-/ lemma degree_le_of_ne_zero {p : polynomial α} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) : degree (minimal_polynomial hx) ≤ degree p := calc degree (minimal_polynomial hx) ≤ degree (p * C (leading_coeff p)⁻¹) : min _ (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz /--The minimal polynomial of an element x is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has x as a root, then this polynomial is equal to the minimal polynomial of x.-/ lemma unique {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) (pmin : ∀ q : polynomial α, q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minimal_polynomial hx := begin symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero hx hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min hx pmonic hp) (pmin (minimal_polynomial hx) (monic hx) (aeval hx)) }, end /--If an element x is a root of a polynomial p, then the minimal polynomial of x divides p.-/ lemma dvd {p : polynomial α} (hp : polynomial.aeval x p = 0) : minimal_polynomial hx ∣ p := begin rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero hx hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end lemma dvd_map_of_is_scalar_tower {α γ : Type*} (β : Type*) [comm_ring α] [field β] [comm_ring γ] [algebra α β] [algebra α γ] [algebra β γ] [is_scalar_tower α β γ] {x : γ} (hx : is_integral α x) : minimal_polynomial (is_integral_of_is_scalar_tower x hx) ∣ (minimal_polynomial hx).map (algebra_map α β) := by { apply minimal_polynomial.dvd, rw [← is_scalar_tower.aeval_apply, minimal_polynomial.aeval] } variables [nontrivial β] /--The degree of a minimal polynomial is nonzero.-/ lemma degree_ne_zero : degree (minimal_polynomial hx) ≠ 0 := begin assume deg_eq_zero, have ndeg_eq_zero : nat_degree (minimal_polynomial hx) = 0, { simpa using congr_arg nat_degree (eq_C_of_degree_eq_zero deg_eq_zero) }, have eq_one : minimal_polynomial hx = 1, { rw eq_C_of_degree_eq_zero deg_eq_zero, convert C_1, simpa [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa [eq_one, aeval_def] using aeval hx end /--A minimal polynomial is not a unit.-/ lemma not_is_unit : ¬ is_unit (minimal_polynomial hx) := assume H, degree_ne_zero hx $ degree_eq_zero_of_is_unit H /--The degree of a minimal polynomial is positive.-/ lemma degree_pos : 0 < degree (minimal_polynomial hx) := degree_pos_of_ne_zero_of_nonunit (ne_zero hx) (not_is_unit hx) theorem unique' {p : polynomial α} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) : p = minimal_polynomial hx := let ⟨q, hq⟩ := dvd hx hp2 in eq_of_monic_of_associated hp3 (monic hx) $ mul_one (minimal_polynomial hx) ▸ hq.symm ▸ associated_mul_mul (associated.refl _) $ associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit hx /--If L/K is a field extension, and x is an element of L in the image of K, then the minimal polynomial of x is X - C x.-/ @[simp] protected lemma algebra_map (a : α) (ha : is_integral α (algebra_map α β a)) : minimal_polynomial ha = X - C a := eq.symm $ unique' ha (irreducible_X_sub_C a) (by rw [alg_hom.map_sub, aeval_X, aeval_C, sub_self]) (monic_X_sub_C a) variable (β) /--If L/K is a field extension, and x is an element of L in the image of K, then the minimal polynomial of x is X - C x.-/ lemma algebra_map' (a : α) : minimal_polynomial (@is_integral_algebra_map α β _ _ _ a) = X - C a := minimal_polynomial.algebra_map _ _ variable {β} /--The minimal polynomial of 0 is X.-/ @[simp] lemma zero {h₀ : is_integral α (0:β)} : minimal_polynomial h₀ = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero] using algebra_map' β (0:α) /--The minimal polynomial of 1 is X - 1.-/ @[simp] lemma one {h₁ : is_integral α (1:β)} : minimal_polynomial h₁ = X - 1 := by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using algebra_map' β (1:α) end ring section domain variables [domain β] [algebra α β] variables {x : β} (hx : is_integral α x) /--A minimal polynomial is prime.-/ lemma prime : prime (minimal_polynomial hx) := begin refine ⟨ne_zero hx, not_is_unit hx, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval hx], replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa, exact or.imp (dvd hx) (dvd hx) this end /--A minimal polynomial is irreducible.-/ lemma irreducible : irreducible (minimal_polynomial hx) := irreducible_of_prime (prime hx) /--If L/K is a field extension and an element y of K is a root of the minimal polynomial of an element x ∈ L, then y maps to x under the field embedding.-/ lemma root {x : β} (hx : is_integral α x) {y : α} (h : is_root (minimal_polynomial hx) y) : algebra_map α β y = x := have key : minimal_polynomial hx = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd (dvd_symm_of_irreducible (irreducible_X_sub_C y) (irreducible hx) (dvd_iff_is_root.2 h)) (dvd_iff_is_root.2 h)), by { have := aeval hx, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this } /--The constant coefficient of the minimal polynomial of x is 0 if and only if x = 0.-/ @[simp] lemma coeff_zero_eq_zero : coeff (minimal_polynomial hx) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact ring_hom.map_zero _ }, { rintro rfl, simp } end /--The minimal polynomial of a nonzero element has nonzero constant coefficient.-/ lemma coeff_zero_ne_zero (h : x ≠ 0) : coeff (minimal_polynomial hx) 0 ≠ 0 := by { contrapose! h, simpa using h } end domain end field end minimal_polynomial
d3af59573a9d560db3db08a7ca6ecb5bc7f8f781
82e44445c70db0f03e30d7be725775f122d72f3e
/src/tactic/simps.lean
17e14004b02608c77bbb344b95976bad023b8a7c
[ "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
42,679
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.group.to_additive import tactic.protected import data.sum /-! # simps attribute This file defines the `@[simps]` attribute, to automatically generate `simp` lemmas reducing a definition when projections are applied to it. ## Implementation Notes There are three attributes being defined here * `@[simps]` is the attribute for objects of a structure or instances of a class. It will automatically generate simplification lemmas for each projection of the object/instance that contains data. See the doc strings for `simps_attr` and `simps_cfg` for more details and configuration options. * `@[_simps_str]` is automatically added to structures that have been used in `@[simps]` at least once. This attribute contains the data of the projections used for this structure by all following invocations of `@[simps]`. * `@[notation_class]` should be added to all classes that define notation, like `has_mul` and `has_zero`. This specifies that the projections that `@[simps]` used are the projections from these notation classes instead of the projections of the superclasses. Example: if `has_mul` is tagged with `@[notation_class]` then the projection used for `semigroup` will be `λ α hα, @has_mul.mul α (@semigroup.to_has_mul α hα)` instead of `@semigroup.mul`. ## Tags structures, projections, simp, simplifier, generates declarations -/ open tactic expr option sum setup_tactic_parser declare_trace simps.verbose declare_trace simps.debug /-- Projection data for a single projection of a structure, consisting of the following fields: - the name used in the generated `simp` lemmas - an expression used by simps for the projection. It must be definitionally equal to an original projection (or a composition of multiple projections). These expressions can contain the universe parameters specified in the first argument of `simps_str_attr`. - a list of natural numbers, which is the projection number(s) that have to be applied to the expression. For example the list `[0, 1]` corresponds to applying the first projection of the structure, and then the second projection of the resulting structure (this assumes that the target of the first projection is a structure with at least two projections). The composition of these projections is required to be definitionally equal to the provided expression. - A boolean specifying whether `simp` lemmas are generated for this projection by default. - A boolean specifying whether this projection is written as prefix. -/ @[protect_proj, derive [has_reflect, inhabited]] meta structure projection_data := (name : name) (expr : expr) (proj_nrs : list ℕ) (is_default : bool) (is_prefix : bool) /-- Temporary projection data parsed from `initialize_simps_projections` before the expression matching this projection has been found. Only used internally in `simps_get_raw_projections`. -/ meta structure parsed_projection_data := (orig_name : name) -- name for this projection used in the structure definition (new_name : name) -- name for this projection used in the generated `simp` lemmas (is_default : bool) (is_prefix : bool) section open format meta instance : has_to_tactic_format projection_data := ⟨λ ⟨a, b, c, d, e⟩, (λ x, group $ nest 1 $ to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ x ++ to_fmt "," ++ line ++ to_fmt c ++ to_fmt "," ++ line ++ to_fmt d ++ to_fmt "," ++ line ++ to_fmt e ++ to_fmt "⟩") <$> pp b⟩ meta instance : has_to_format parsed_projection_data := ⟨λ ⟨a, b, c, d⟩, group $ nest 1 $ to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt "," ++ line ++ to_fmt c ++ to_fmt "," ++ line ++ to_fmt d ++ to_fmt "⟩"⟩ end /-- The type of rules that specify how metadata for projections in changes. See `initialize_simps_projection`. -/ abbreviation projection_rule := (name × name ⊕ name) × bool /-- The `@[_simps_str]` attribute specifies the preferred projections of the given structure, used by the `@[simps]` attribute. - This will usually be tagged by the `@[simps]` tactic. - You can also generate this with the command `initialize_simps_projections`. - To change the default value, see Note [custom simps projection]. - You are strongly discouraged to add this attribute manually. - The first argument is the list of names of the universe variables used in the structure - The second argument is a list that consists of the projection data for each projection. -/ @[user_attribute] meta def simps_str_attr : user_attribute unit (list name × list projection_data) := { name := `_simps_str, descr := "An attribute specifying the projection of the given structure.", parser := do e ← texpr, eval_pexpr _ e } /-- The `@[notation_class]` attribute specifies that this is a notation class, and this notation should be used instead of projections by @[simps]. * The first argument `tt` for notation classes and `ff` for classes applied to the structure, like `has_coe_to_sort` and `has_coe_to_fun` * The second argument is the name of the projection (by default it is the first projection of the structure) -/ @[user_attribute] meta def notation_class_attr : user_attribute unit (bool × option name) := { name := `notation_class, descr := "An attribute specifying that this is a notation class. Used by @[simps].", parser := prod.mk <$> (option.is_none <$> (tk "*")?) <*> ident? } attribute [notation_class] has_zero has_one has_add has_mul has_inv has_neg has_sub has_div has_dvd has_mod has_le has_lt has_append has_andthen has_union has_inter has_sdiff has_equiv has_subset has_ssubset has_emptyc has_insert has_singleton has_sep has_mem has_pow attribute [notation_class* coe_sort] has_coe_to_sort attribute [notation_class* coe_fn] has_coe_to_fun /-- Returns the projection information of a structure. -/ meta def projections_info (l : list projection_data) (pref : string) (str : name) : tactic format := do ⟨defaults, nondefaults⟩ ← return $ l.partition_map $ λ s, if s.is_default then inl s else inr s, to_print ← defaults.mmap $ λ s, to_string <$> let prefix_str := if s.is_prefix then "(prefix) " else "" in pformat!"Projection {prefix_str}{s.name}: {s.expr}", let print2 := string.join $ (nondefaults.map (λ nm : projection_data, to_string nm.1)).intersperse ", ", let to_print := to_print ++ if nondefaults.length = 0 then [] else ["No lemmas are generated for the projections: " ++ print2 ++ "."], let to_print := string.join $ to_print.intersperse "\n > ", return format!"[simps] > {pref} {str}:\n > {to_print}" /-- Auxiliary function of `get_composite_of_projections`. -/ meta def get_composite_of_projections_aux : Π (str : name) (proj : string) (x : expr) (pos : list ℕ) (args : list expr), tactic (expr × list ℕ) | str proj x pos args := do e ← get_env, projs ← e.structure_fields str, let proj_info := projs.map_with_index $ λ n p, (λ x, (x, n, p)) <$> proj.get_rest ("_" ++ p.last), when (proj_info.filter_map id = []) $ fail!"Failed to find constructor {proj.popn 1} in structure {str}.", (proj_rest, index, proj_nm) ← return (proj_info.filter_map id).ilast, str_d ← e.get str, let proj_e : expr := const (str ++ proj_nm) str_d.univ_levels, proj_d ← e.get (str ++ proj_nm), type ← infer_type x, let params := get_app_args type, let univs := proj_d.univ_params.zip type.get_app_fn.univ_levels, let new_x := (proj_e.instantiate_univ_params univs).mk_app $ params ++ [x], let new_pos := pos ++ [index], if proj_rest.is_empty then return (new_x.lambdas args, new_pos) else do type ← infer_type new_x, (type_args, tgt) ← open_pis_whnf type, let new_str := tgt.get_app_fn.const_name, get_composite_of_projections_aux new_str proj_rest (new_x.mk_app type_args) new_pos (args ++ type_args) /-- Given a structure `str` and a projection `proj`, that could be multiple nested projections (separated by `_`), returns an expression that is the composition of these projections and a list of natural numbers, that are the projection numbers of the applied projections. -/ meta def get_composite_of_projections (str : name) (proj : string) : tactic (expr × list ℕ) := do e ← get_env, str_d ← e.get str, let str_e : expr := const str str_d.univ_levels, type ← infer_type str_e, (type_args, tgt) ← open_pis_whnf type, let str_ap := str_e.mk_app type_args, x ← mk_local' `x binder_info.default str_ap, get_composite_of_projections_aux str ("_" ++ proj) x [] $ type_args ++ [x] /-- Get the projections used by `simps` associated to a given structure `str`. The returned information is also stored in a parameter of the attribute `@[_simps_str]`, which is given to `str`. If `str` already has this attribute, the information is read from this attribute instead. See the documentation for this attribute for the data this tactic returns. The returned universe levels are the universe levels of the structure. For the projections there are three cases * If the declaration `{structure_name}.simps.{projection_name}` has been declared, then the value of this declaration is used (after checking that it is definitionally equal to the actual projection. If you rename the projection name, the declaration should have the *new* projection name. * You can also declare a custom projection that is a composite of multiple projections. * Otherwise, for every class with the `notation_class` attribute, and the structure has an instance of that notation class, then the projection of that notation class is used for the projection that is definitionally equal to it (if there is such a projection). This means in practice that coercions to function types and sorts will be used instead of a projection, if this coercion is definitionally equal to a projection. Furthermore, for notation classes like `has_mul` and `has_zero` those projections are used instead of the corresponding projection. Projections for coercions and notation classes are not automatically generated if they are composites of multiple projections (for example when you use `extend` without the `old_structure_cmd`). * Otherwise, the projection of the structure is chosen. For example: ``simps_get_raw_projections env `prod`` gives the default projections ``` ([u, v], [prod.fst.{u v}, prod.snd.{u v}]) ``` while ``simps_get_raw_projections env `equiv`` gives ``` ([u_1, u_2], [λ α β, coe_fn, λ {α β} (e : α ≃ β), ⇑(e.symm), left_inv, right_inv]) ``` after declaring the coercion from `equiv` to function and adding the declaration ``` def equiv.simps.inv_fun {α β} (e : α ≃ β) : β → α := e.symm ``` Optionally, this command accepts three optional arguments: * If `trace_if_exists` the command will always generate a trace message when the structure already has the attribute `@[_simps_str]`. * The `rules` argument accepts a list of pairs `sum.inl (old_name, new_name)`. This is used to change the projection name `old_name` to the custom projection name `new_name`. Example: for the structure `equiv` the projection `to_fun` could be renamed `apply`. This name will be used for parsing and generating projection names. This argument is ignored if the structure already has an existing attribute. If an element of `rules` is of the form `sum.inr name`, this means that the projection `name` will not be applied by default. * if `trc` is true, this tactic will trace information. -/ -- if performance becomes a problem, possible heuristic: use the names of the projections to -- skip all classes that don't have the corresponding field. meta def simps_get_raw_projections (e : environment) (str : name) (trace_if_exists : bool := ff) (rules : list projection_rule := []) (trc := ff) : tactic (list name × list projection_data) := do let trc := trc || is_trace_enabled_for `simps.verbose, has_attr ← has_attribute' `_simps_str str, if has_attr then do data ← simps_str_attr.get_param str, -- We always print the projections when they already exists and are called by -- `initialize_simps_projections`. when (trace_if_exists || is_trace_enabled_for `simps.verbose) $ projections_info data.2 "Already found projection information for structure" str >>= trace, return data else do when trc trace!"[simps] > generating projection information for structure {str}.", when_tracing `simps.debug trace!"[simps] > Applying the rules {rules}.", d_str ← e.get str, let raw_univs := d_str.univ_params, let raw_levels := level.param <$> raw_univs, /- Figure out projections, including renamings. The information for a projection is (before we figure out the `expr` of the projection: `(original name, given name, is default, is prefix)`. The first projections are always the actual projections of the structure, but `rules` could specify custom projections that are compositions of multiple projections. -/ projs ← e.structure_fields str, let projs : list parsed_projection_data := projs.map $ λ nm, ⟨nm, nm, tt, ff⟩, let projs : list parsed_projection_data := rules.foldl (λ projs rule, match rule with | (inl (old_nm, new_nm), is_prefix) := if old_nm ∈ projs.map (λ x, x.new_name) then projs.map $ λ proj, if proj.new_name = old_nm then { new_name := new_nm, is_prefix := is_prefix, ..proj } else proj else projs ++ [⟨old_nm, new_nm, tt, is_prefix⟩] | (inr nm, is_prefix) := if nm ∈ projs.map (λ x, x.new_name) then projs.map $ λ proj, if proj.new_name = nm then { is_default := ff, is_prefix := is_prefix, ..proj } else proj else projs ++ [⟨nm, nm, ff, is_prefix⟩] end) projs, when_tracing `simps.debug trace!"[simps] > Projection info after applying the rules: {projs}.", when ¬ (projs.map $ λ x, x.new_name : list name).nodup $ fail $ "Invalid projection names. Two projections have the same name. This is likely because a custom composition of projections was given the same name as an " ++ "existing projection. Solution: rename the existing projection (before renaming the custom " ++ "projection).", /- Define the raw expressions for the projections, by default as the projections (as an expression), but this can be overriden by the user. -/ raw_exprs_and_nrs ← projs.mmap $ λ ⟨orig_nm, new_nm, _, _⟩, do { (raw_expr, nrs) ← get_composite_of_projections str orig_nm.last, custom_proj ← do { decl ← e.get (str ++ `simps ++ new_nm.last), let custom_proj := decl.value.instantiate_univ_params $ decl.univ_params.zip raw_levels, when trc trace! "[simps] > found custom projection for {new_nm}:\n > {custom_proj}", return custom_proj } <|> return raw_expr, is_def_eq custom_proj raw_expr <|> -- if the type of the expression is different, we show a different error message, because -- that is more likely going to be helpful. do { custom_proj_type ← infer_type custom_proj, raw_expr_type ← infer_type raw_expr, b ← succeeds (is_def_eq custom_proj_type raw_expr_type), if b then fail!"Invalid custom projection:\n {custom_proj} Expression is not definitionally equal to\n {raw_expr}" else fail!"Invalid custom projection:\n {custom_proj} Expression has different type than {str ++ orig_nm}. Given type:\n {custom_proj_type} Expected type:\n {raw_expr_type}" }, return (custom_proj, nrs) }, let raw_exprs := raw_exprs_and_nrs.map prod.fst, /- Check for other coercions and type-class arguments to use as projections instead. -/ (args, _) ← open_pis d_str.type, let e_str := (expr.const str raw_levels).mk_app args, automatic_projs ← attribute.get_instances `notation_class, raw_exprs ← automatic_projs.mfoldl (λ (raw_exprs : list expr) class_nm, do { (is_class, proj_nm) ← notation_class_attr.get_param class_nm, proj_nm ← proj_nm <|> (e.structure_fields_full class_nm).map list.head, /- For this class, find the projection. `raw_expr` is the projection found applied to `args`, and `lambda_raw_expr` has the arguments `args` abstracted. -/ (raw_expr, lambda_raw_expr) ← if is_class then (do guard $ args.length = 1, let e_inst_type := (const class_nm raw_levels).mk_app args, (hyp, e_inst) ← try_for 1000 (mk_conditional_instance e_str e_inst_type), raw_expr ← mk_mapp proj_nm [args.head, e_inst], clear hyp, -- Note: `expr.bind_lambda` doesn't give the correct type raw_expr_lambda ← lambdas [hyp] raw_expr, return (raw_expr, raw_expr_lambda.lambdas args)) else (do e_inst_type ← to_expr ((const class_nm []).app (pexpr.of_expr e_str)), e_inst ← try_for 1000 (mk_instance e_inst_type), raw_expr ← mk_mapp proj_nm [e_str, e_inst], return (raw_expr, raw_expr.lambdas args)), raw_expr_whnf ← whnf raw_expr, let relevant_proj := raw_expr_whnf.binding_body.get_app_fn.const_name, /- Use this as projection, if the function reduces to a projection, and this projection has not been overrriden by the user. -/ guard $ projs.any $ λ x, x.1 = relevant_proj.last ∧ ¬ e.contains (str ++ `simps ++ x.new_name.last), let pos := projs.find_index (λ x, x.1 = relevant_proj.last), when trc trace! " > using {proj_nm} instead of the default projection {relevant_proj.last}.", when_tracing `simps.debug trace!"[simps] > The raw projection is:\n {lambda_raw_expr}", return $ raw_exprs.update_nth pos lambda_raw_expr } <|> return raw_exprs) raw_exprs, let positions := raw_exprs_and_nrs.map prod.snd, let proj_names := projs.map (λ x, x.new_name), let defaults := projs.map (λ x, x.is_default), let prefixes := projs.map (λ x, x.is_prefix), let projs := proj_names.zip_with5 projection_data.mk raw_exprs positions defaults prefixes, /- make all proof non-default. -/ projs ← projs.mmap $ λ proj, is_proof proj.expr >>= λ b, return $ if b then { is_default := ff, .. proj } else proj, when trc $ projections_info projs "generated projections for" str >>= trace, simps_str_attr.set str (raw_univs, projs) tt, when_tracing `simps.debug trace! "[simps] > Generated raw projection data: \n{(raw_univs, projs)}", return (raw_univs, projs) /-- Parse a rule for `initialize_simps_projections`. It is either `<name>→<name>` or `-<name>`, possibly following by `as_prefix`.-/ meta def simps_parse_rule : parser projection_rule := prod.mk <$> ((λ x y, inl (x, y)) <$> ident <*> (tk "->" >> ident) <|> inr <$> (tk "-" >> ident)) <*> is_some <$> (tk "as_prefix")? /-- You can specify custom projections for the `@[simps]` attribute. To do this for the projection `my_structure.original_projection` by adding a declaration `my_structure.simps.my_projection` that is definitionally equal to `my_structure.original_projection` but has the projection in the desired (simp-normal) form. Then you can call ``` initialize_simps_projections (original_projection → my_projection, ...) ``` to register this projection. Running `initialize_simps_projections` without arguments is not necessary, it has the same effect if you just add `@[simps]` to a declaration. If you do anything to change the default projections, make sure to call either `@[simps]` or `initialize_simps_projections` in the same file as the structure declaration. Otherwise, you might have a file that imports the structure, but not your custom projections. -/ library_note "custom simps projection" /-- Specify simps projections, see Note [custom simps projection]. * You can specify custom names by writing e.g. `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`. * You can disable a projection by default by running `initialize_simps_projections equiv (-inv_fun)` This will ensure that no simp lemmas are generated for this projection, unless this projection is explicitly specified by the user. * If you want the projection name added as a prefix in the generated lemma name, you can add the `as_prefix` modifier: `initialize_simps_projections equiv (to_fun → coe as_prefix)` Note that this does not influence the parsing of projection names: if you have a declaration `foo` and you want to apply the projections `snd`, `coe` (which is a prefix) and `fst`, in that order you can run `@[simps snd_coe_fst] def foo ...` and this will generate a lemma with the name `coe_foo_snd_fst`. * Run `initialize_simps_projections?` (or set `trace.simps.verbose`) to see the generated projections. -/ @[user_command] meta def initialize_simps_projections_cmd (_ : parse $ tk "initialize_simps_projections") : parser unit := do env ← get_env, trc ← is_some <$> (tk "?")?, ns ← (prod.mk <$> ident <*> (tk "(" >> sep_by (tk ",") simps_parse_rule <* tk ")")?)*, ns.mmap' $ λ data, do nm ← resolve_constant data.1, simps_get_raw_projections env nm tt (data.2.get_or_else []) trc /-- Configuration options for the `@[simps]` attribute. * `attrs` specifies the list of attributes given to the generated lemmas. Default: ``[`simp]``. The attributes can be either basic attributes, or user attributes without parameters. There are two attributes which `simps` might add itself: * If ``[`simp]`` is in the list, then ``[`_refl_lemma]`` is added automatically if appropriate. * If the definition is marked with `@[to_additive ...]` then all generated lemmas are marked with `@[to_additive]`. This is governed by the `add_additive` configuration option. * if `simp_rhs` is `tt` then the right-hand-side of the generated lemmas will be put in simp-normal form. More precisely: `dsimp, simp` will be called on all these expressions. See note [dsimp, simp]. * `type_md` specifies how aggressively definitions are unfolded in the type of expressions for the purposes of finding out whether the type is a function type. Default: `instances`. This will unfold coercion instances (so that a coercion to a function type is recognized as a function type), but not declarations like `set`. * `rhs_md` specifies how aggressively definition in the declaration are unfolded for the purposes of finding out whether it is a constructor. Default: `none` Exception: `@[simps]` will automatically add the options `{rhs_md := semireducible, simp_rhs := tt}` if the given definition is not a constructor with the given reducibility setting for `rhs_md`. * If `fully_applied` is `ff` then the generated `simp` lemmas will be between non-fully applied terms, i.e. equalities between functions. This does not restrict the recursive behavior of `@[simps]`, so only the "final" projection will be non-fully applied. However, it can be used in combination with explicit field names, to get a partially applied intermediate projection. * The option `not_recursive` contains the list of names of types for which `@[simps]` doesn't recursively apply projections. For example, given an equivalence `α × β ≃ β × α` one usually wants to only apply the projections for `equiv`, and not also those for `×`. This option is only relevant if no explicit projection names are given as argument to `@[simps]`. * The option `trace` is set to `tt` when you write `@[simps?]`. In this case, the attribute will print all generated lemmas. It is almost the same as setting the option `trace.simps.verbose`, except that it doesn't print information about the found projections. * if `add_additive` is `some nm` then `@[to_additive]` is added to the generated lemma. This option is automatically set to `tt` when the original declaration was tagged with `@[to_additive, simps]` (in that order), where `nm` is the additive name of the original declaration. -/ @[derive [has_reflect, inhabited]] structure simps_cfg := (attrs := [`simp]) (simp_rhs := ff) (type_md := transparency.instances) (rhs_md := transparency.none) (fully_applied := tt) (not_recursive := [`prod, `pprod]) (trace := ff) (add_additive := @none name) /-- A common configuration for `@[simps]`: generate equalities between functions instead equalities between fully applied expressions. -/ def as_fn : simps_cfg := {fully_applied := ff} /-- A common configuration for `@[simps]`: don't tag the generated lemmas with `@[simp]`. -/ def lemmas_only : simps_cfg := {attrs := []} /-- Get the projections of a structure used by `@[simps]` applied to the appropriate arguments. Returns a list of tuples ``` (corresponding right-hand-side, given projection name, projection expression, projection numbers, used by default, is prefix) ``` (where all fields except the first are packed in a `projection_data` structure) one for each projection. The given projection name is the name for the projection used by the user used to generate (and parse) projection names. For example, in the structure Example 1: ``simps_get_projection_exprs env `(α × β) `(⟨x, y⟩)`` will give the output ``` [(`(x), `fst, `(@prod.fst.{u v} α β), [0], tt, ff), (`(y), `snd, `(@prod.snd.{u v} α β), [1], tt, ff)] ``` Example 2: ``simps_get_projection_exprs env `(α ≃ α) `(⟨id, id, λ _, rfl, λ _, rfl⟩)`` will give the output ``` [(`(id), `apply, `(coe), [0], tt, ff), (`(id), `symm_apply, `(λ f, ⇑f.symm), [1], tt, ff), ..., ...] ``` -/ meta def simps_get_projection_exprs (e : environment) (tgt : expr) (rhs : expr) (cfg : simps_cfg) : tactic $ list $ expr × projection_data := do let params := get_app_args tgt, -- the parameters of the structure (params.zip $ (get_app_args rhs).take params.length).mmap' (λ ⟨a, b⟩, is_def_eq a b) <|> fail "unreachable code (1)", let str := tgt.get_app_fn.const_name, let rhs_args := (get_app_args rhs).drop params.length, -- the fields of the object (raw_univs, proj_data) ← simps_get_raw_projections e str ff [] cfg.trace, let univs := raw_univs.zip tgt.get_app_fn.univ_levels, let new_proj_data : list $ expr × projection_data := proj_data.map $ λ proj, (rhs_args.inth proj.proj_nrs.head, { expr := (proj.expr.instantiate_univ_params univs).instantiate_lambdas_or_apps params, proj_nrs := proj.proj_nrs.tail, .. proj }), return new_proj_data /-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`, `args` is the list of local constants occurring, and `univs` is the list of universe variables. -/ meta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr) (univs : list name) (cfg : simps_cfg) : tactic unit := do when_tracing `simps.debug trace! "[simps] > Planning to add the equality\n > {lhs} = ({rhs} : {type})", lvl ← get_univ_level type, -- simplify `rhs` if `cfg.simp_rhs` is true (rhs, prf) ← do { guard cfg.simp_rhs, rhs' ← rhs.dsimp {fail_if_unchanged := ff}, when_tracing `simps.debug $ when (rhs ≠ rhs') trace! "[simps] > `dsimp` simplified rhs to\n > {rhs'}", (rhsprf1, rhsprf2, ns) ← rhs'.simp {fail_if_unchanged := ff}, when_tracing `simps.debug $ when (rhs' ≠ rhsprf1) trace! "[simps] > `simp` simplified rhs to\n > {rhsprf1}", return (prod.mk rhsprf1 rhsprf2) } <|> return (rhs, const `eq.refl [lvl] type lhs), let eq_ap := const `eq [lvl] type lhs rhs, decl_name ← get_unused_decl_name nm, let decl_type := eq_ap.pis args, let decl_value := prf.lambdas args, let decl := declaration.thm decl_name univs decl_type (pure decl_value), when cfg.trace trace! "[simps] > adding projection {decl_name}:\n > {decl_type}", decorate_error ("Failed to add projection lemma " ++ decl_name.to_string ++ ". Nested error:") $ add_decl decl, b ← succeeds $ is_def_eq lhs rhs, when (b ∧ `simp ∈ cfg.attrs) (set_basic_attribute `_refl_lemma decl_name tt), cfg.attrs.mmap' $ λ nm, set_attribute nm decl_name tt, when cfg.add_additive.is_some $ to_additive.attr.set decl_name ⟨ff, cfg.trace, cfg.add_additive.iget, none, tt⟩ tt /-- Derive lemmas specifying the projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. `to_apply` is non-empty after a custom projection that is a composition of multiple projections was just used. In that case we need to apply these projections before we continue changing lhs. -/ meta def simps_add_projections : Π (e : environment) (nm : name) (type lhs rhs : expr) (args : list expr) (univs : list name) (must_be_str : bool) (cfg : simps_cfg) (todo : list string) (to_apply : list ℕ), tactic unit | e nm type lhs rhs args univs must_be_str cfg todo to_apply := do -- we don't want to unfold non-reducible definitions (like `set`) to apply more arguments when_tracing `simps.debug trace! "[simps] > Type of the expression before normalizing: {type}", (type_args, tgt) ← open_pis_whnf type cfg.type_md, when_tracing `simps.debug trace!"[simps] > Type after removing pi's: {tgt}", tgt ← whnf tgt, when_tracing `simps.debug trace!"[simps] > Type after reduction: {tgt}", let new_args := args ++ type_args, let lhs_ap := lhs.instantiate_lambdas_or_apps type_args, let rhs_ap := rhs.instantiate_lambdas_or_apps type_args, let str := tgt.get_app_fn.const_name, /- We want to generate the current projection if it is in `todo` -/ let todo_next := todo.filter (≠ ""), /- Don't recursively continue if `str` is not a structure or if the structure is in `not_recursive`. -/ if e.is_structure str ∧ ¬(todo = [] ∧ str ∈ cfg.not_recursive ∧ ¬must_be_str) then do [intro] ← return $ e.constructors_of str | fail "unreachable code (3)", rhs_whnf ← whnf rhs_ap cfg.rhs_md, (rhs_ap, todo_now) ← -- `todo_now` means that we still have to generate the current simp lemma if ¬ is_constant_of rhs_ap.get_app_fn intro ∧ is_constant_of rhs_whnf.get_app_fn intro then /- If this was a desired projection, we want to apply it before taking the whnf. However, if the current field is an eta-expansion (see below), we first want to eta-reduce it and only then construct the projection. This makes the flow of this function messy. -/ when ("" ∈ todo ∧ to_apply = []) (if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg) >> return (rhs_whnf, ff) else return (rhs_ap, "" ∈ todo ∧ to_apply = []), if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application proj_info ← simps_get_projection_exprs e tgt rhs_ap cfg, when_tracing `simps.debug trace!"[simps] > Raw projection information:\n {proj_info}", eta ← rhs_ap.is_eta_expansion, -- check whether `rhs_ap` is an eta-expansion let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap` /- As a special case, we want to automatically generate the current projection if `rhs_ap` was an eta-expansion. Also, when this was a desired projection, we need to generate the current projection if we haven't done it above. -/ when (todo_now ∨ (todo = [] ∧ eta.is_some ∧ to_apply = [])) $ if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg, /- If we are in the middle of a composite projection. -/ when (to_apply ≠ []) $ do { ⟨new_rhs, proj, proj_expr, proj_nrs, is_default, is_prefix⟩ ← return $ proj_info.inth to_apply.head, new_type ← infer_type new_rhs, when_tracing `simps.debug trace!"[simps] > Applying a custom composite projection. Current lhs: > {lhs_ap}", simps_add_projections e nm new_type lhs_ap new_rhs new_args univs ff cfg todo to_apply.tail }, /- We stop if no further projection is specified or if we just reduced an eta-expansion and we automatically choose projections -/ when ¬(to_apply ≠ [] ∨ todo = [""] ∨ (eta.is_some ∧ todo = [])) $ do let projs : list name := proj_info.map $ λ x, x.snd.name, let todo := if to_apply = [] then todo_next else todo, -- check whether all elements in `todo` have a projection as prefix guard (todo.all $ λ x, projs.any $ λ proj, ("_" ++ proj.last).is_prefix_of x) <|> let x := (todo.find $ λ x, projs.all $ λ proj, ¬ ("_" ++ proj.last).is_prefix_of x).iget, simp_lemma := nm.append_suffix x, needed_proj := (x.split_on '_').tail.head in fail! "Invalid simp lemma {simp_lemma}. Structure {str} does not have projection {needed_proj}. The known projections are: {projs} You can also see this information by running `initialize_simps_projections? {str}`. Note: these projection names might not correspond to the projection names of the structure.", proj_info.mmap_with_index' $ λ proj_nr ⟨new_rhs, proj, proj_expr, proj_nrs, is_default, is_prefix⟩, do new_type ← infer_type new_rhs, let new_todo := todo.filter_map $ λ x, x.get_rest ("_" ++ proj.last), -- we only continue with this field if it is non-propositional or mentioned in todo when ((is_default ∧ todo = []) ∨ new_todo ≠ []) $ do let new_lhs := proj_expr.instantiate_lambdas_or_apps [lhs_ap], let new_nm := nm.append_to_last proj.last is_prefix, let new_cfg := { add_additive := cfg.add_additive.map $ λ nm, nm.append_to_last (to_additive.guess_name proj.last) is_prefix, ..cfg }, when_tracing `simps.debug trace!"[simps] > Recursively add projections for: > {new_lhs}", simps_add_projections e new_nm new_type new_lhs new_rhs new_args univs ff new_cfg new_todo proj_nrs -- if I'm about to run into an error, try to set the transparency for `rhs_md` higher. else if cfg.rhs_md = transparency.none ∧ (must_be_str ∨ todo_next ≠ [] ∨ to_apply ≠ []) then do when cfg.trace trace! "[simps] > The given definition is not a constructor application: > {rhs_ap} > Retrying with the options {{ rhs_md := semireducible, simp_rhs := tt}.", simps_add_projections e nm type lhs rhs args univs must_be_str { rhs_md := semireducible, simp_rhs := tt, ..cfg} todo to_apply else do when (to_apply ≠ []) $ fail!"Invalid simp lemma {nm}. The given definition is not a constructor application:\n {rhs_ap}", when must_be_str $ fail!"Invalid `simps` attribute. The body is not a constructor application:\n {rhs_ap}", when (todo_next ≠ []) $ fail!"Invalid simp lemma {nm.append_suffix todo_next.head}. The given definition is not a constructor application:\n {rhs_ap}", if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg else do when must_be_str $ fail!"Invalid `simps` attribute. Target {str} is not a structure", when (todo_next ≠ [] ∧ str ∉ cfg.not_recursive) $ let first_todo := todo_next.head in fail!"Invalid simp lemma {nm.append_suffix first_todo}. Projection {(first_todo.split_on '_').tail.head} doesn't exist, because target is not a structure.", if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg /-- `simps_tac` derives `simp` lemmas for all (nested) non-Prop projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. If `short_nm` is true, the generated names will only use the last projection name. If `trc` is true, trace as if `trace.simps.verbose` is true. -/ meta def simps_tac (nm : name) (cfg : simps_cfg := {}) (todo : list string := []) (trc := ff) : tactic unit := do e ← get_env, d ← e.get nm, let lhs : expr := const d.to_name d.univ_levels, let todo := todo.erase_dup.map $ λ proj, "_" ++ proj, let cfg := { trace := cfg.trace || is_trace_enabled_for `simps.verbose || trc, ..cfg }, b ← has_attribute' `to_additive nm, cfg ← if b then do { dict ← to_additive.aux_attr.get_cache, when cfg.trace trace!"[simps] > @[to_additive] will be added to all generated lemmas.", return { add_additive := dict.find nm, ..cfg } } else return cfg, simps_add_projections e nm d.type lhs d.value [] d.univ_params tt cfg todo [] /-- The parser for the `@[simps]` attribute. -/ meta def simps_parser : parser (bool × list string × simps_cfg) := do /- note: we don't check whether the user has written a nonsense namespace in an argument. -/ prod.mk <$> is_some <$> (tk "?")? <*> (prod.mk <$> many (name.last <$> ident) <*> (do some e ← parser.pexpr? | return {}, eval_pexpr simps_cfg e)) /-- The `@[simps]` attribute automatically derives lemmas specifying the projections of this declaration. Example: ```lean @[simps] def foo : ℕ × ℤ := (1, 2) ``` derives two `simp` lemmas: ```lean @[simp] lemma foo_fst : foo.fst = 1 @[simp] lemma foo_snd : foo.snd = 2 ``` * It does not derive `simp` lemmas for the prop-valued projections. * It will automatically reduce newly created beta-redexes, but will not unfold any definitions. * If the structure has a coercion to either sorts or functions, and this is defined to be one of the projections, then this coercion will be used instead of the projection. * If the structure is a class that has an instance to a notation class, like `has_mul`, then this notation is used instead of the corresponding projection. * You can specify custom projections, by giving a declaration with name `{structure_name}.simps.{projection_name}`. See Note [custom simps projection]. Example: ```lean def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm @[simps] def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ ``` generates ``` @[simp] lemma equiv.trans_to_fun : ∀ {α β γ} (e₁ e₂) (a : α), ⇑(e₁.trans e₂) a = (⇑e₂ ∘ ⇑e₁) a @[simp] lemma equiv.trans_inv_fun : ∀ {α β γ} (e₁ e₂) (a : γ), ⇑((e₁.trans e₂).symm) a = (⇑(e₁.symm) ∘ ⇑(e₂.symm)) a ``` * You can specify custom projection names, by specifying the new projection names using `initialize_simps_projections`. Example: `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`. * If one of the fields itself is a structure, this command will recursively create `simp` lemmas for all fields in that structure. * Exception: by default it will not recursively create `simp` lemmas for fields in the structures `prod` and `pprod`. Give explicit projection names to override this behavior. Example: ```lean structure my_prod (α β : Type*) := (fst : α) (snd : β) @[simps] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_snd_fst : foo.snd.fst = 3 @[simp] lemma foo_snd_snd : foo.snd.snd = 4 ``` * You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified projections. * Recursive projection names can be specified using `proj1_proj2_proj3`. This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`. Example: ```lean structure my_prod (α β : Type*) := (fst : α) (snd : β) @[simps fst fst_fst snd] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_fst_fst : foo.fst.fst = 1 @[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4} ``` * If one of the values is an eta-expanded structure, we will eta-reduce this structure. Example: ```lean structure equiv_plus_data (α β) extends α ≃ β := (data : bool) @[simps] def bar {α} : equiv_plus_data α α := { data := tt, ..equiv.refl α } ``` generates the following, even though Lean inserts an eta-expanded version of `equiv.refl α` in the definition of `bar`: ```lean @[simp] lemma bar_to_equiv : ∀ {α : Sort u_1}, bar.to_equiv = equiv.refl α @[simp] lemma bar_data : ∀ {α : Sort u_1}, bar.data = tt ``` * For configuration options, see the doc string of `simps_cfg`. * The precise syntax is `('simps' ident* e)`, where `e` is an expression of type `simps_cfg`. * `@[simps]` reduces let-expressions where necessary. * If one of the fields is a partially applied constructor, we will eta-expand it (this likely never happens). * When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the lemmas it generates. The same can be achieved by using `@[simps?]`, except that in this case it will not print projection information. * Use `@[to_additive, simps]` to apply both `to_additive` and `simps` to a definition, making sure that `simps` comes after `to_additive`. This will also generate the additive versions of all `simp` lemmas. -/ @[user_attribute] meta def simps_attr : user_attribute unit (bool × list string × simps_cfg) := { name := `simps, descr := "Automatically derive lemmas specifying the projections of this declaration.", parser := simps_parser, after_set := some $ λ n _ persistent, do guard persistent <|> fail "`simps` currently cannot be used as a local attribute", (trc, todo, cfg) ← simps_attr.get_param n, simps_tac n cfg todo trc } add_tactic_doc { name := "simps", category := doc_category.attr, decl_names := [`simps_attr], tags := ["simplification"] }
d2de58d5bcbe18ddd5e1e7c9908c6ccc0586cfc3
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/priority.lean
ea309e247df978feeda4721acebf6e77b5fd2b63
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
121
lean
import data.num namespace priority definition default : num := 1000 definition max : num := 4294967295 end priority
5e2e7b0247c077181191c5792ed328aeb1b00a57
b392eb79fb36952401156496daa60628ccb07438
/MathPort/Path.lean
fdd1c5cfdd9699a6beaf775775245f5cf8eb25d2
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
2,739
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam Lean3 structure: - ./lean3/library/init/data/nat/basic.tlean - ./mathlib/src/data/nat/basic.tlean Lean4 structure: - lib4/auto/Lean3Lib/data/nat/basic.olean - lib4/auto/Mathlib/data/nat/basic.olean -/ import Lean open Lean namespace MathPort -- Example: data.nat.basic structure DotPath where path : String deriving Inhabited, Repr -- Example: data/nat/basic structure ModRelPath where path : String deriving Inhabited, Repr def DotPath.toModRelPath (p : DotPath) : ModRelPath := ⟨System.mkFilePath $ p.path.splitOn "."⟩ def ModRelPath.toDotPath (p : ModRelPath) : DotPath := ⟨".".intercalate $ p.path.splitOn "/"⟩ def ModRelPath.toUnderscorePath (p : ModRelPath) : String := ".".intercalate $ p.path.splitOn "_" -- Example: Mathlib mathlib/src structure ModuleInfo where l4name : String l3path : String deriving Inhabited, Repr structure Path34 where modInfo : ModuleInfo mrpath : ModRelPath deriving Inhabited, Repr ------------------------------- -- START CONFIG -- TODO: config file? ------------------------------- def MODULES : Array ModuleInfo := #[ -- TEMP ModuleInfo.mk "Mathlib" "../mathport/mathlib/src", ModuleInfo.mk "Lean3Lib" "../mathport/lean3/library", ModuleInfo.mk "Lean3Pkg" "../mathport/lean3/leanpkg" ] def Lib4Path : String := "Lib4" -- TEMP def Lean4LibPath : String := "../mathport/lean4/build/release/stage1/lib/lean" ------------------------------- -- END CONFIG ------------------------------- def Path34.toLean3 (p : Path34) (suffix : String) : String := System.mkFilePath [p.modInfo.l3path, p.mrpath.path] ++ suffix def Path34.toTLean (p : Path34) : String := p.toLean3 ".tlean" def Path34.toLean3Source (p : Path34) : String := p.toLean3 ".lean" def Path34.toLean4dot (p : Path34) : String := ".".intercalate [p.modInfo.l4name, p.mrpath.toDotPath.path] def Path34.toLean4path (p : Path34) (suffix : String) : String := System.mkFilePath [Lib4Path, p.modInfo.l4name, p.mrpath.path] ++ suffix def Path34.toLean4olean (p : Path34) : String := p.toLean4path ".olean" def Path34.toLean4autolean (p : Path34) : String := p.toLean4path "_auto.lean" def resolveDotPath (dotPath : DotPath) : IO Path34 := do let mrp : ModRelPath := dotPath.toModRelPath for modInfo in MODULES do let p34 := Path34.mk modInfo mrp if ← IO.fileExists p34.toTLean then return p34 let p34 := Path34.mk modInfo $ ⟨mrp.path ++ "/default"⟩ if ← IO.fileExists p34.toTLean then return p34 throw $ IO.userError s!"[resolveImport3] failed to resolve '{mrp.path}'" end MathPort
c7b60dd1fa2fd16c815470d93c1a2c5ed21c7c28
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/analysis/calculus/local_extr.lean
564ec14cbaec19827a1987a2b01fc7c3f4ed8454
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
18,092
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.local_extr import topology.algebra.ordered.extend_from import analysis.calculus.deriv import topology.algebra.polynomial /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ universes u v open filter set open_locale topological_space classical section module variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : E →L[ℝ] ℝ} /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) := begin rintros s t hst y ⟨c, d, hd, hc, hcd⟩, exact ⟨c, d, mem_sets_of_superset hd $ λ h hn, hst hn, hc, hcd⟩ end lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y ⊆ s) : y - x ∈ pos_tangent_cone_at s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), tendsto_pow_at_top_at_top_of_one_lt one_lt_two, _⟩, show x + d n ∈ segment x y, { rw segment_eq_image', refine ⟨(c n)⁻¹, ⟨_, _⟩, rfl⟩, exacts [inv_nonneg.2 (pow_nonneg zero_le_two _), inv_le_one (one_le_pow_of_one_le one_le_two _)] }, show tendsto (λ n, c n • d n) at_top (𝓝 (y - x)), { convert tendsto_const_nhds, ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ two_ne_zero } end lemma mem_pos_tangent_cone_at_of_segment_subset' {s : set E} {x y : E} (h : segment x (x + y) ⊆ s) : y ∈ pos_tangent_cone_at s x := by simpa only [add_sub_cancel'] using mem_pos_tangent_cone_at_of_segment_subset h lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ := eq_univ_of_forall $ λ x, mem_pos_tangent_cone_at_of_segment_subset' (subset_univ _) /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : f' y ≤ 0 := begin rcases hy with ⟨c, d, hd, hc, hcd⟩, have hc' : tendsto (λ n, ∥c n∥) at_top at_top, from tendsto_at_top_mono (λ n, le_abs_self _) hc, refine le_of_tendsto (hf.lim at_top hd hc' hcd) _, replace hd : tendsto (λ n, a + d n) at_top (𝓝[s] (a + 0)), from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd), by rwa tendsto_principal⟩, rw [add_zero] at hd, replace h : ∀ᶠ n in at_top, f (a + d n) ≤ f a, from mem_map.1 (hd h), replace hc : ∀ᶠ n in at_top, 0 ≤ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))), filter_upwards [h, hc], simp only [smul_eq_mul, mem_preimage, subset_def], assume n hnf hn, exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf) end /-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y ≤ 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $ by simpa using h.has_fderiv_within_at_nonpos hf hy' /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ f' y := by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy /-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy' /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := begin ext y, apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at; rw pos_tangent_cone_at_univ; apply mem_univ end /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) : has_fderiv_at f f' a → f' = 0 := h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 := h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero end module section real variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ} /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := by simpa using continuous_linear_map.ext_iff.1 (h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1 /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) : has_deriv_at f f' a → f' = 0 := h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 := h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero end real section Rolle variables (f f' : ℝ → ℝ) {a b : ℝ} /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ lemma exists_Ioo_extr_on_Icc (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c := begin have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab), -- Consider absolute min and max points obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x, from compact_Icc.exists_forall_le ne hfc, obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C, from compact_Icc.exists_forall_ge ne hfc, by_cases hc : f c = f a, { by_cases hC : f C = f a, { have : ∀ x ∈ Icc a b, f x = f a, from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx), -- `f` is a constant, so we can take any point in `Ioo a b` rcases exists_between hab with ⟨c', hc'⟩, refine ⟨c', hc', or.inl _⟩, assume x hx, rw [mem_set_of_eq, this x hx, ← hC], exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ }, { refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } }, { refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } end /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ lemma exists_local_extr_Ioo (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_local_extr f c := let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI in ⟨c, cmem, hc.is_local_extr $ Icc_mem_nhds cmem.1 cmem.2⟩ /-- Rolle's Theorem `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩ /-- Rolle's Theorem `deriv` version -/ lemma exists_deriv_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, deriv f c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.deriv_eq_zero⟩ variables {f f'} {l : ℝ} /-- Rolle's Theorem, a version for a function on an open interval: if `f` has derivative `f'` on `(a, b)` and has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `f' c = 0` for some `c ∈ (a, b)`. -/ lemma exists_has_deriv_at_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := begin have : continuous_on f (Ioo a b) := λ x hx, (hff' x hx).continuous_at.continuous_within_at, have hcont := continuous_on_Icc_extend_from_Ioo hab this hfa hfb, obtain ⟨c, hc, hcextr⟩ : ∃ c ∈ Ioo a b, is_local_extr (extend_from (Ioo a b) f) c, { apply exists_local_extr_Ioo _ hab hcont, rw eq_lim_at_right_extend_from_Ioo hab hfb, exact eq_lim_at_left_extend_from_Ioo hab hfa }, use [c, hc], apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc), rw eventually_eq_iff_exists_mem, exact ⟨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends this⟩ end /-- Rolle's Theorem, a version for a function on an open interval: if `f` has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `deriv f c = 0` for some `c ∈ (a, b)`. This version does not require differentiability of `f` because we define `deriv f c = 0` whenever `f` is not differentiable at `c`. -/ lemma exists_deriv_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) : ∃ c ∈ Ioo a b, deriv f c = 0 := classical.by_cases (assume h : ∀ x ∈ Ioo a b, differentiable_at ℝ f x, show ∃ c ∈ Ioo a b, deriv f c = 0, from exists_has_deriv_at_eq_zero' hab hfa hfb (λ x hx, (h x hx).has_deriv_at)) (assume h : ¬∀ x ∈ Ioo a b, differentiable_at ℝ f x, have h : ∃ x, x ∈ Ioo a b ∧ ¬differentiable_at ℝ f x, by { push_neg at h, exact h }, let ⟨c, hc, hcdiff⟩ := h in ⟨c, hc, deriv_zero_of_not_differentiable_at hcdiff⟩) end Rolle namespace polynomial lemma card_root_set_le_derivative {F : Type*} [field F] [algebra F ℝ] (p : polynomial F) : fintype.card (p.root_set ℝ) ≤ fintype.card (p.derivative.root_set ℝ) + 1 := begin haveI : char_zero F := (ring_hom.char_zero_iff (algebra_map F ℝ).injective).mpr (by apply_instance), by_cases hp : p = 0, { simp_rw [hp, derivative_zero, root_set_zero, set.empty_card', zero_le_one] }, by_cases hp' : p.derivative = 0, { rw eq_C_of_nat_degree_eq_zero (nat_degree_eq_zero_of_derivative_eq_zero hp'), simp_rw [root_set_C, set.empty_card', zero_le] }, simp_rw [root_set_def, fintype.card_coe], refine finset.card_le_of_interleaved (λ x y hx hy hxy, _), rw [←finset.mem_coe, ←root_set_def, mem_root_set hp] at hx hy, obtain ⟨z, hz1, hz2⟩ := exists_deriv_eq_zero (λ x : ℝ, aeval x p) hxy p.continuous_aeval.continuous_on (hx.trans hy.symm), refine ⟨z, _, hz1⟩, rw [←finset.mem_coe, ←root_set_def, mem_root_set hp', ←hz2], simp_rw [aeval_def, ←eval_map, polynomial.deriv, derivative_map], end end polynomial
3b9e1451a552e7cbc98a271fce5d817bb505cddd
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/field_theory/separable.lean
d5b0f797b275a02119aaa97cff6362779de32c11
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,694
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.big_operators import field_theory.minpoly import field_theory.splitting_field import field_theory.tower import algebra.squarefree /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ universes u v w open_locale classical big_operators open finset namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : polynomial R) : Prop := is_coprime f f.derivative lemma separable_def (f : polynomial R) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : polynomial R) : f.separable ↔ ∃ a b : polynomial R, a * f + b * f.derivative = 1 := iff.rfl lemma not_separable_zero [nontrivial R] : ¬ separable (0 : polynomial R) := begin rintro ⟨x, y, h⟩, simpa only [derivative_zero, mul_zero, add_zero, zero_ne_one] using h, end lemma separable_one : (1 : polynomial R).separable := is_coprime_one_left lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : polynomial R).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.of_dvd {f g : polynomial R} (hf : f.separable) (hfg : g ∣ f) : g.separable := by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf } lemma separable_gcd_left {F : Type*} [field F] {f : polynomial F} (hf : f.separable) (g : polynomial F) : (euclidean_domain.gcd f g).separable := separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g) lemma separable_gcd_right {F : Type*} [field F] {g : polynomial F} (f : polynomial F) (hg : g.separable) : (euclidean_domain.gcd f g).separable := separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g) lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : polynomial R} : ∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := λ h, or.inr $ or.inr rfl | 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩ | (n+2) := λ h, by { rw [pow_succ, pow_succ] at h, exact or.inl (is_coprime_self.1 h.is_coprime.of_mul_right_left) } theorem separable.of_pow {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : polynomial R} (h : p.separable) {f : R →+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩ variables (R) (p q : ℕ) /-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/ noncomputable def expand : polynomial R →ₐ[R] polynomial R := { commutes' := λ r, eval₂_C _ _, .. (eval₂_ring_hom C (X ^ p) : polynomial R →+* polynomial R) } lemma coe_expand : (expand R p : polynomial R → polynomial R) = eval₂ C (X ^ p) := rfl variables {R} lemma expand_eq_sum {f : polynomial R} : expand R p f = f.sum (λ e a, C a * (X ^ p) ^ e) := by { dsimp [expand, eval₂], refl, } @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (λ r, by simp_rw expand_C) (λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f := polynomial.induction_on f (λ r, by rw expand_C) (λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih, by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih] theorem derivative_expand (f : polynomial R) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_eval₂_C, derivative_pow, derivative_X, mul_one] theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin simp only [expand_eq_sum], simp_rw [coeff_sum, ← pow_mul, C_mul_X_pow_eq_monomial, coeff_monomial, sum], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : polynomial R} : expand R p f = expand R p g ↔ f = g := ⟨λ H, ext $ λ n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩ theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 := by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero] theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : ℕ) (f : polynomial R) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end theorem map_expand {p : ℕ} (hp : 0 < p) {f : R →+* S} {q : polynomial R} : map f (expand R p q) = expand S p (map f q) := by { ext, rw [coeff_map, coeff_expand hp, coeff_expand hp], split_ifs; simp, } /-- Expansion is injective. -/ lemma expand_injective {n : ℕ} (hn : 0 < n) : function.injective (expand R n) := λ g g' h, begin ext, have h' : (expand R n g).coeff (n * n_1) = (expand R n g').coeff (n * n_1) := begin apply polynomial.ext_iff.1, exact h, end, rw [polynomial.coeff_expand hn g (n * n_1), polynomial.coeff_expand hn g' (n * n_1)] at h', simp only [if_true, dvd_mul_right] at h', rw (nat.mul_div_right n_1 hn) at h', exact h', end end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable_X_sub_C {x : R} : separable (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using separable_X_add_C (-x) lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } lemma separable_prod' {ι : Sort*} {f : ι → polynomial R} {s : finset ι} : (∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) → (∏ x in s, f x).separable := finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has, exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $ ne.symm $ ne_of_mem_of_not_mem his has) end lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → polynomial R} (h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable := separable_prod' (λ x hx y hy hxy, h1 x y hxy) (λ x hx, h2 x) lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι} (hfs : (∏ i in s, (X - C (f i))).separable) {x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := begin by_contra hxy, rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy), prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← sq] at hfs, cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C) two_ne_zero).2 end lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R} (hfs : (∏ i, (X - C (f i))).separable) : function.injective f := λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy lemma is_unit_of_self_mul_dvd_separable {p q : polynomial R} (hp : p.separable) (hq : q * q ∣ p) : is_unit q := begin obtain ⟨p, rfl⟩ := hq, apply is_coprime_self.mp, have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)), { simp only [← mul_assoc, mul_add], convert hp, rw [derivative_mul, derivative_mul], ring }, exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this) end end comm_ring section integral_domain variables (R : Type u) [comm_ring R] [integral_domain R] theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : polynomial R →+* polynomial R) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end end integral_domain section field variables {F : Type u} [field F] {K : Type v} [field K] theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) : f.separable ↔ f.derivative ≠ 0 := ⟨λ h1 h2, hf.not_unit $ is_coprime_zero_right.1 $ h2 ▸ h1, λ h, is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.is_unit_or_is_unit hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩ theorem separable_map (f : F →+* K) {p : polynomial F} : (p.map f).separable ↔ p.separable := by simp_rw [separable_def, derivative_map, is_coprime_map] section char_p /-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ noncomputable def contract (p : ℕ) (f : polynomial F) : polynomial F := ∑ n in range (f.nat_degree + 1), monomial n (f.coeff (n * p)) variables (p : ℕ) [hp : fact p.prime] include hp theorem coeff_contract (f : polynomial F) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) := begin simp only [contract, coeff_monomial, sum_ite_eq', finset_sum_coeff, mem_range, not_lt, ite_eq_left_iff], assume hn, apply (coeff_eq_zero_of_nat_degree_lt _).symm, calc f.nat_degree < f.nat_degree + 1 : nat.lt_succ_self _ ... ≤ n * 1 : by simpa only [mul_one] using hn ... ≤ n * p : mul_le_mul_of_nonneg_left (@nat.prime.one_lt p (fact.out _)).le (zero_le n) end theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) : irreducible f := @@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.1.pos) hf theorem of_irreducible_expand_pow {f : polynomial F} {n : ℕ} : irreducible (expand F (p ^ n) f) → irreducible f := nat.rec_on n (λ hf, by rwa [pow_zero, expand_one] at hf) $ λ n ih hf, ih $ of_irreducible_expand p $ by { rw pow_succ at hf, rwa [expand_expand] } variables [HF : char_p F p] include HF theorem expand_char (f : polynomial F) : map (frobenius F p) (expand F p f) = f ^ p := begin refine f.induction_on' (λ a b ha hb, _) (λ n a, _), { rw [alg_hom.map_add, map_add, ha, hb, add_pow_char], }, { rw [expand_monomial, map_monomial, monomial_eq_C_mul_X, monomial_eq_C_mul_X, mul_pow, ← C.map_pow, frobenius_def], ring_exp } end theorem map_expand_pow_char (f : polynomial F) (n : ℕ) : map ((frobenius F p) ^ n) (expand F (p ^ n) f) = f ^ (p ^ n) := begin induction n, { simp [ring_hom.one_def] }, symmetry, rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm, expand_mul, ← map_expand (nat.prime.pos hp.1)], end theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) : expand F p (contract p f) = f := begin ext n, rw [coeff_expand hp.1.pos, coeff_contract], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this, exact absurd this h } end theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨ ¬f.separable ∧ ∃ g : polynomial F, irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, by haveI := is_local_ring_hom_expand F hp.1.pos; exact of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf), expand_contract p H⟩ else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : ∃ (n : ℕ) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f := begin unfreezingI { induction hn : f.nat_degree using nat.strong_induction_on with N ih generalizing f }, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree ≠ 0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.1.one_lt (nat.pos_of_ne_zero hg2) }, have hg4 : g ≠ 0, { rintro rfl, exact hg2 nat_degree_zero }, rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩, rw [← hgf, expand_expand, pow_succ] } end theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : ℕ) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw or_iff_not_imp_right, intro hn, have hf2 : (expand F (p ^ n) f).derivative = 0, { by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (pow_pos hp.1.pos _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) (n₁ : ℕ) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (n₂ : ℕ) (g₂ : polynomial F) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := begin revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁] tactic.skip, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp.1.pos n₁)] at hgf₂, subst hgf₂, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, pow_zero, expand_one], split; refl } }, exact λ g₁ g₂ hg₁ hgf₁ hg₂ hgf₂, let ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩ end end char_p lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} : (∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy, λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy, @pairwise_coprime_X_sub _ _ { x // x ∈ s } (λ x, f x) (λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy) (λ _ _, separable_X_sub_C) }⟩ lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} : (∏ i, (X - C (f i))).separable ↔ function.injective f := separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff, function.injective] section splits open_locale big_operators variables {i : F →+* K} lemma not_unit_X_sub_C (a : F) : ¬ is_unit (X - C a) := λ h, have one_eq_zero : (1 : with_bot ℕ) = 0, by simpa using degree_eq_zero_of_is_unit h, one_ne_zero (option.some_injective _ one_eq_zero) lemma nodup_of_separable_prod {s : multiset F} (hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup := begin rw multiset.nodup_iff_ne_cons_cons, rintros a t rfl, refine not_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _), simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _) end lemma multiplicity_le_one_of_separable {p q : polynomial F} (hq : ¬ is_unit q) (hsep : separable p) : multiplicity q p ≤ 1 := begin contrapose! hq, apply is_unit_of_self_mul_dvd_separable hsep, rw ← sq, apply multiplicity.pow_dvd_of_le_multiplicity, simpa only [nat.cast_one, nat.cast_bit0] using enat.add_one_le_of_lt hq end lemma separable.squarefree {p : polynomial F} (hsep : separable p) : squarefree p := begin rw multiplicity.squarefree_iff_multiplicity_le_one p, intro f, by_cases hunit : is_unit f, { exact or.inr hunit }, exact or.inl (multiplicity_le_one_of_separable hunit hsep) end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/ lemma separable_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : separable (X ^ n - C a) := begin cases nat.eq_zero_or_pos n with hzero hpos, { exfalso, rw hzero at hn, exact hn (refl 0) }, apply (separable_def' (X ^ n - C a)).2, use [-C (a⁻¹), (C ((a⁻¹) * (↑n)⁻¹) * X)], have mul_pow_sub : X * X ^ (n - 1) = X ^ n, { nth_rewrite 0 [←pow_one X], rw pow_mul_pow_sub X (nat.succ_le_iff.mpr hpos) }, rw [derivative_sub, derivative_C, sub_zero, derivative_pow X n, derivative_X, mul_one], have hcalc : C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * (X ^ n), { calc C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * C ((↑n)⁻¹) * (C ↑n * (X ^ n)) : by rw [C_mul, C_eq_nat_cast] ... = C a⁻¹ * (C ((↑n)⁻¹) * C ↑n) * (X ^ n) : by ring ... = C a⁻¹ * C ((↑n)⁻¹ * ↑n) * (X ^ n) : by rw [← C_mul] ... = C a⁻¹ * C 1 * (X ^ n) : by field_simp [hn] ... = C a⁻¹ * (X ^ n) : by rw [C_1, mul_one] }, calc -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * X * (↑n * X ^ (n - 1)) = -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * (↑n * (X * X ^ (n - 1))) : by ring ... = -C a⁻¹ * (X ^ n - C a) + C a⁻¹ * (X ^ n) : by rw [mul_pow_sub, hcalc] ... = C a⁻¹ * C a : by ring ... = (1 : polynomial F) : by rw [← C_mul, inv_mul_cancel ha, C_1] end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is squarefree for any `a ≠ 0`. -/ lemma squarefree_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : squarefree (X ^ n - C a) := (separable_X_pow_sub_C a hn ha).squarefree lemma root_multiplicity_le_one_of_separable {p : polynomial F} (hp : p ≠ 0) (hsep : separable p) (x : F) : root_multiplicity x p ≤ 1 := begin rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_le_coe, enat.coe_get, nat.cast_one], exact multiplicity_le_one_of_separable (not_unit_X_sub_C _) hsep end lemma count_roots_le_one {p : polynomial F} (hsep : separable p) (x : F) : p.roots.count x ≤ 1 := begin by_cases hp : p = 0, { simp [hp] }, rw count_roots hp, exact root_multiplicity_le_one_of_separable hp hsep x end lemma nodup_roots {p : polynomial F} (hsep : separable p) : p.roots.nodup := multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep) lemma card_root_set_eq_nat_degree [algebra F K] {p : polynomial F} (hsep : p.separable) (hsplit : splits (algebra_map F K) p) : fintype.card (p.root_set K) = p.nat_degree := begin simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots hsplit], exact nodup_roots hsep.map, end lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : polynomial F} (h_ne_zero : h ≠ 0) (h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h) (h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits, apply finset.mk.inj, { change _ = {i x}, rw finset.eq_singleton_iff_unique_mem, split, { apply finset.mem_mk.mpr, rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero), rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root], exact ring_hom.map_zero i }, { exact h_roots } }, { exact nodup_roots (separable.map h_sep) }, end lemma exists_finset_of_splits (i : F →+* K) {f : polynomial F} (sep : separable f) (sp : splits i f) : ∃ (s : finset K), f.map i = C (i f.leading_coeff) * (s.prod (λ a : K, (X : polynomial K) - C a)) := begin classical, obtain ⟨s, h⟩ := exists_multiset_of_splits i sp, use s.to_finset, rw [h, finset.prod_eq_multiset_prod, ←multiset.to_finset_eq], apply nodup_of_separable_prod, apply separable.of_mul_right, rw ←h, exact sep.map, end end splits end field end polynomial open polynomial theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩, rw [pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine λ hf1, hf.not_unit _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf.ne_zero end section comm_ring variables (F K : Type*) [comm_ring F] [ring K] [algebra F K] -- TODO: refactor to allow transcendental extensions? -- See: https://en.wikipedia.org/wiki/Separable_extension#Separability_of_transcendental_extensions /-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff the minimal polynomial of every `x : K` is separable. We define this for general (commutative) rings and only assume `F` and `K` are fields if this is needed for a proof. -/ class is_separable : Prop := (is_integral' (x : K) : is_integral F x) (separable' (x : K) : (minpoly F x).separable) variables (F) {K} theorem is_separable.is_integral [is_separable F K] : ∀ x : K, is_integral F x := is_separable.is_integral' theorem is_separable.separable [is_separable F K] : ∀ x : K, (minpoly F x).separable := is_separable.separable' variables {F K} theorem is_separable_iff : is_separable F K ↔ ∀ x : K, is_integral F x ∧ (minpoly F x).separable := ⟨λ h x, ⟨@@is_separable.is_integral F _ _ _ h x, @@is_separable.separable F _ _ _ h x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩ end comm_ring instance is_separable_self (F : Type*) [field F] : is_separable F F := ⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact separable_X_sub_C }⟩ /-- A finite field extension in characteristic 0 is separable. -/ @[priority 100] -- See note [lower instance priority] instance is_separable.of_finite (F K : Type*) [field F] [field K] [algebra F K] [finite_dimensional F K] [char_zero F] : is_separable F K := have ∀ (x : K), is_integral F x, from λ x, (is_algebraic_iff_is_integral _).mp (algebra.is_algebraic_of_finite _), ⟨this, λ x, (minpoly.irreducible (this x)).separable⟩ section is_separable_tower variables (F K E : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_separable_tower_top_of_is_separable [is_separable F E] : is_separable K E := ⟨λ x, is_integral_of_is_scalar_tower x (is_separable.is_integral F x), λ x, (is_separable.separable F x).map.of_dvd (minpoly.dvd_map_of_is_scalar_tower _ _ _)⟩ lemma is_separable_tower_bot_of_is_separable [h : is_separable F E] : is_separable F K := is_separable_iff.2 $ λ x, begin refine (is_separable_iff.1 h (algebra_map K E x)).imp is_integral_tower_bot_of_is_integral_field (λ hs, _), obtain ⟨q, hq⟩ := minpoly.dvd F x (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field (minpoly.aeval F ((algebra_map K E) x))), rw hq at hs, exact hs.of_mul_left end variables {E} lemma is_separable.of_alg_hom (E' : Type*) [field E'] [algebra F E'] (f : E →ₐ[F] E') [is_separable F E'] : is_separable F E := begin letI : algebra E E' := ring_hom.to_algebra f.to_ring_hom, haveI : is_scalar_tower F E E' := is_scalar_tower.of_algebra_map_eq (λ x, (f.commutes x).symm), exact is_separable_tower_bot_of_is_separable F E E', end end is_separable_tower section card_alg_hom variables {R S T : Type*} [comm_ring S] variables {K L F : Type*} [field K] [field L] [field F] variables [algebra K S] [algebra K L] lemma alg_hom.card_of_power_basis (pb : power_basis K S) (h_sep : (minpoly K pb.gen).separable) (h_splits : (minpoly K pb.gen).splits (algebra_map K L)) : @fintype.card (S →ₐ[K] L) (power_basis.alg_hom.fintype pb) = pb.dim := begin let s := ((minpoly K pb.gen).map (algebra_map K L)).roots.to_finset, have H := λ x, multiset.mem_to_finset, rw [fintype.card_congr pb.lift_equiv', fintype.card_of_subtype s H, ← pb.nat_degree_minpoly, nat_degree_eq_card_roots h_splits, multiset.to_finset_card_of_nodup], exact nodup_roots ((separable_map (algebra_map K L)).mpr h_sep) end end card_alg_hom
2799035cc4670267de716fe0e1737ba30e9c9d03
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Std/Data/RBMap.lean
005c32b2ba44dc1dabacfb2f387cb8246de71154
[ "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
14,048
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ namespace Std universe u v w w' inductive Rbcolor where | red | black inductive RBNode (α : Type u) (β : α → Type v) where | leaf : RBNode α β | node (color : Rbcolor) (lchild : RBNode α β) (key : α) (val : β key) (rchild : RBNode α β) : RBNode α β namespace RBNode variable {α : Type u} {β : α → Type v} {σ : Type w} open Std.Rbcolor Nat def depth (f : Nat → Nat → Nat) : RBNode α β → Nat | leaf => 0 | node _ l _ _ r => succ (f (depth f l) (depth f r)) protected def min : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ leaf k v _ => some ⟨k, v⟩ | node _ l _ _ _ => RBNode.min l protected def max : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ _ k v leaf => some ⟨k, v⟩ | node _ _ _ _ r => RBNode.max r @[specialize] def fold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => fold f (f (fold f b l) k v) r @[specialize] def forM [Monad m] (f : (k : α) → β k → m Unit) : RBNode α β → m Unit | leaf => pure () | node _ l k v r => do forM f l; f k v; forM f r @[specialize] def foldM [Monad m] (f : σ → (k : α) → β k → m σ) : (init : σ) → RBNode α β → m σ | b, leaf => pure b | b, node _ l k v r => do let b ← foldM f b l let b ← f b k v foldM f b r @[inline] protected def forIn [Monad m] (as : RBNode α β) (init : σ) (f : (k : α) → β k → σ → m (ForInStep σ)) : m σ := do let rec @[specialize] visit : RBNode α β → σ → m (ForInStep σ) | leaf, b => return ForInStep.yield b | node _ l k v r, b => do match (← visit l b) with | r@(ForInStep.done _) => return r | ForInStep.yield b => match (← f k v b) with | r@(ForInStep.done _) => return r | ForInStep.yield b => visit r b match (← visit as init) with | ForInStep.done b => pure b | ForInStep.yield b => pure b @[specialize] def revFold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => revFold f (f (revFold f b r) k v) l @[specialize] def all (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => true | node _ l k v r => p k v && all p l && all p r @[specialize] def any (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => false | node _ l k v r => p k v || any p l || any p r def singleton (k : α) (v : β k) : RBNode α β := node red leaf k v leaf @[inline] def balance1 : (a : α) → β a → RBNode α β → RBNode α β → RBNode α β | kv, vv, t, node _ (node red l kx vx r₁) ky vy r₂ => node red (node black l kx vx r₁) ky vy (node black r₂ kv vv t) | kv, vv, t, node _ l₁ ky vy (node red l₂ kx vx r) => node red (node black l₁ ky vy l₂) kx vx (node black r kv vv t) | kv, vv, t, node _ l ky vy r => node black (node red l ky vy r) kv vv t | _, _, _, _ => leaf -- unreachable @[inline] def balance2 : RBNode α β → (a : α) → β a → RBNode α β → RBNode α β | t, kv, vv, node _ (node red l kx₁ vx₁ r₁) ky vy r₂ => node red (node black t kv vv l) kx₁ vx₁ (node black r₁ ky vy r₂) | t, kv, vv, node _ l₁ ky vy (node red l₂ kx₂ vx₂ r₂) => node red (node black t kv vv l₁) ky vy (node black l₂ kx₂ vx₂ r₂) | t, kv, vv, node _ l ky vy r => node black t kv vv (node red l ky vy r) | _, _, _, _ => leaf -- unreachable def isRed : RBNode α β → Bool | node red .. => true | _ => false def isBlack : RBNode α β → Bool | node black .. => true | _ => false section Insert variable (cmp : α → α → Ordering) @[specialize] def ins : RBNode α β → (k : α) → β k → RBNode α β | leaf, kx, vx => node red leaf kx vx leaf | node red a ky vy b, kx, vx => match cmp kx ky with | Ordering.lt => node red (ins a kx vx) ky vy b | Ordering.gt => node red a ky vy (ins b kx vx) | Ordering.eq => node red a kx vx b | node black a ky vy b, kx, vx => match cmp kx ky with | Ordering.lt => if isRed a then balance1 ky vy b (ins a kx vx) else node black (ins a kx vx) ky vy b | Ordering.gt => if isRed b then balance2 a ky vy (ins b kx vx) else node black a ky vy (ins b kx vx) | Ordering.eq => node black a kx vx b def setBlack : RBNode α β → RBNode α β | node _ l k v r => node black l k v r | e => e @[specialize] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β := if isRed t then setBlack (ins cmp t k v) else ins cmp t k v end Insert def balance₃ (a : RBNode α β) (k : α) (v : β k) (d : RBNode α β) : RBNode α β := match a with | node red (node red a kx vx b) ky vy c => node red (node black a kx vx b) ky vy (node black c k v d) | node red a kx vx (node red b ky vy c) => node red (node black a kx vx b) ky vy (node black c k v d) | a => match d with | node red b ky vy (node red c kz vz d) => node red (node black a k v b) ky vy (node black c kz vz d) | node red (node red b ky vy c) kz vz d => node red (node black a k v b) ky vy (node black c kz vz d) | _ => node black a k v d def setRed : RBNode α β → RBNode α β | node _ a k v b => node red a k v b | e => e def balLeft : RBNode α β → (k : α) → β k → RBNode α β → RBNode α β | node red a kx vx b, k, v, r => node red (node black a kx vx b) k v r | l, k, v, node black a ky vy b => balance₃ l k v (node red a ky vy b) | l, k, v, node red (node black a ky vy b) kz vz c => node red (node black l k v a) ky vy (balance₃ b kz vz (setRed c)) | l, k, v, r => node red l k v r -- unreachable def balRight (l : RBNode α β) (k : α) (v : β k) (r : RBNode α β) : RBNode α β := match r with | (node red b ky vy c) => node red l k v (node black b ky vy c) | _ => match l with | node black a kx vx b => balance₃ (node red a kx vx b) k v r | node red a kx vx (node black b ky vy c) => node red (balance₃ (setRed a) kx vx b) ky vy (node black c k v r) | _ => node red l k v r -- unreachable -- TODO: use wellfounded recursion partial def appendTrees : RBNode α β → RBNode α β → RBNode α β | leaf, x => x | x, leaf => x | node red a kx vx b, node red c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node red a kx vx b') kz vz (node red c' ky vy d) | bc => node red a kx vx (node red bc ky vy d) | node black a kx vx b, node black c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node black a kx vx b') kz vz (node black c' ky vy d) | bc => balLeft a kx vx (node black bc ky vy d) | a, node red b kx vx c => node red (appendTrees a b) kx vx c | node red a kx vx b, c => node red a kx vx (appendTrees b c) section Erase variable (cmp : α → α → Ordering) @[specialize] def del (x : α) : RBNode α β → RBNode α β | leaf => leaf | node _ a y v b => match cmp x y with | Ordering.lt => if a.isBlack then balLeft (del x a) y v b else node red (del x a) y v b | Ordering.gt => if b.isBlack then balRight a y v (del x b) else node red a y v (del x b) | Ordering.eq => appendTrees a b @[specialize] def erase (x : α) (t : RBNode α β) : RBNode α β := let t := del cmp x t; t.setBlack end Erase section Membership variable (cmp : α → α → Ordering) @[specialize] def findCore : RBNode α β → (k : α) → Option (Sigma (fun k => β k)) | leaf, _ => none | node _ a ky vy b, x => match cmp x ky with | Ordering.lt => findCore a x | Ordering.gt => findCore b x | Ordering.eq => some ⟨ky, vy⟩ @[specialize] def find {β : Type v} : RBNode α (fun _ => β) → α → Option β | leaf, _ => none | node _ a ky vy b, x => match cmp x ky with | Ordering.lt => find a x | Ordering.gt => find b x | Ordering.eq => some vy @[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, _, lb => lb | node _ a ky vy b, x, lb => match cmp x ky with | Ordering.lt => lowerBound a x lb | Ordering.gt => lowerBound b x (some ⟨ky, vy⟩) | Ordering.eq => some ⟨ky, vy⟩ end Membership inductive WellFormed (cmp : α → α → Ordering) : RBNode α β → Prop where | leafWff : WellFormed cmp leaf | insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed cmp n → n' = insert cmp n k v → WellFormed cmp n' | eraseWff {n n' : RBNode α β} {k : α} : WellFormed cmp n → n' = erase cmp k n → WellFormed cmp n' end RBNode open Std.RBNode /- TODO(Leo): define dRBMap -/ def RBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Type (max u v) := {t : RBNode α (fun _ => β) // t.WellFormed cmp } @[inline] def mkRBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : RBMap α β cmp := ⟨leaf, WellFormed.leafWff⟩ @[inline] def RBMap.empty {α : Type u} {β : Type v} {cmp : α → α → Ordering} : RBMap α β cmp := mkRBMap .. instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : EmptyCollection (RBMap α β cmp) := ⟨RBMap.empty⟩ instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Inhabited (RBMap α β cmp) := ⟨∅⟩ namespace RBMap variable {α : Type u} {β : Type v} {σ : Type w} {cmp : α → α → Ordering} def depth (f : Nat → Nat → Nat) (t : RBMap α β cmp) : Nat := t.val.depth f @[inline] def fold (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.fold f b @[inline] def revFold (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.revFold f b @[inline] def foldM [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β cmp → m σ | b, ⟨t, _⟩ => t.foldM f b @[inline] def forM [Monad m] (f : α → β → m PUnit) (t : RBMap α β cmp) : m PUnit := t.foldM (fun _ k v => f k v) ⟨⟩ @[inline] protected def forIn [Monad m] (t : RBMap α β cmp) (init : σ) (f : (α × β) → σ → m (ForInStep σ)) : m σ := t.val.forIn init (fun a b acc => f (a, b) acc) instance : ForIn m (RBMap α β cmp) (α × β) where forIn := RBMap.forIn @[inline] def isEmpty : RBMap α β cmp → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : RBMap α β cmp → List (α × β) | ⟨t, _⟩ => t.revFold (fun ps k v => (k, v)::ps) [] @[inline] protected def min : RBMap α β cmp → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none @[inline] protected def max : RBMap α β cmp → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [Repr α] [Repr β] : Repr (RBMap α β cmp) where reprPrec m prec := Repr.addAppParen ("Std.rbmapOf " ++ repr m.toList) prec @[inline] def insert : RBMap α β cmp → α → β → RBMap α β cmp | ⟨t, w⟩, k, v => ⟨t.insert cmp k v, WellFormed.insertWff w rfl⟩ @[inline] def erase : RBMap α β cmp → α → RBMap α β cmp | ⟨t, w⟩, k => ⟨t.erase cmp k, WellFormed.eraseWff w rfl⟩ @[specialize] def ofList : List (α × β) → RBMap α β cmp | [] => mkRBMap .. | ⟨k,v⟩::xs => (ofList xs).insert k v @[inline] def findCore? : RBMap α β cmp → α → Option (Sigma (fun (_ : α) => β)) | ⟨t, _⟩, x => t.findCore cmp x @[inline] def find? : RBMap α β cmp → α → Option β | ⟨t, _⟩, x => t.find cmp x @[inline] def findD (t : RBMap α β cmp) (k : α) (v₀ : β) : β := (t.find? k).getD v₀ /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound : RBMap α β cmp → α → Option (Sigma (fun (_ : α) => β)) | ⟨t, _⟩, x => t.lowerBound cmp x none @[inline] def contains (t : RBMap α β cmp) (a : α) : Bool := (t.find? a).isSome @[inline] def fromList (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β cmp) @[inline] def all : RBMap α β cmp → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p @[inline] def any : RBMap α β cmp → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p def size (m : RBMap α β cmp) : Nat := m.fold (fun sz _ _ => sz+1) 0 def maxDepth (t : RBMap α β cmp) : Nat := t.val.depth Nat.max @[inline] def min! [Inhabited α] [Inhabited β] (t : RBMap α β cmp) : α × β := match t.min with | some p => p | none => panic! "map is empty" @[inline] def max! [Inhabited α] [Inhabited β] (t : RBMap α β cmp) : α × β := match t.max with | some p => p | none => panic! "map is empty" @[inline] def find! [Inhabited β] (t : RBMap α β cmp) (k : α) : β := match t.find? k with | some b => b | none => panic! "key is not in the map" end RBMap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBMap.fromList l cmp end Std
42ae1ea069b3764b2bd0b1c5afe930cb04a38d35
9028d228ac200bbefe3a711342514dd4e4458bff
/src/combinatorics/pigeonhole.lean
5b1ee4c7461cb472db2def04165ca9ed04889931
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,928
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Yury Kudryashov -/ import data.fintype.basic import algebra.big_operators.order /-! # Pigeonhole principles Given pigeons (possibly infinitely many) in pigeonholes, the pigeonhole principle states that, if there are more pigeons than pigeonholes, then there is a pigeonhole with two or more pigeons. There are a few variations on this statement, and the conclusion can be made stronger depending on how many pigeons you know you might have. The basic statements of the pigeonhole principle appear in the following locations: * `data.finset.basic` has `finset.exists_ne_map_eq_of_card_lt_of_maps_to` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_card_lt` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_infinite` * `data.fintype.basic` has `fintype.exists_infinite_fiber` This module gives access to these pigeonhole principles along with 20 more. The versions vary by: * using a function between `fintype`s or a function between possibly infinite types restricted to `finset`s; * counting pigeons by a general weight function (`∑ x in s, w x`) or by heads (`finset.card s`); * using strict or non-strict inequalities; * establishing upper or lower estimate on the number (or the total weight) of the pigeons in one pigeonhole; * in case when we count pigeons by some weight function `w` and consider a function `f` between `finset`s `s` and `t`, we can either assume that each pigeon is in one of the pigeonholes (`∀ x ∈ s, f x ∈ t`), or assume that for `y ∉ t`, the total weight of the pigeons in this pigeonhole `∑ x in s.filter (λ x, f x = y), w x` is nonpositive or nonnegative depending on the inequality we are proving. Lemma names follow `mathlib` convention (e.g., `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`); "pigeonhole principle" is mentioned in the docstrings instead of the names. ## See also * `ordinal.infinite_pigeonhole`: pigeonhole principle for cardinals, formulated using cofinality; * `measure_theory.exists_nonempty_inter_of_measure_univ_lt_tsum_measure`, `measure_theory.exists_nonempty_inter_of_measure_univ_lt_sum_measure`: pigeonhole principle in a measure space. ## Tags pigeonhole principle -/ universes u v w variables {α : Type u} {β : Type v} {M : Type w} [decidable_linear_ordered_cancel_add_comm_monoid M] [decidable_eq β] open_locale big_operators namespace finset variables {s : finset α} {t : finset β} {f : α → β} {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `finset`s, pigeons counted by weight In this section we prove the following version of the pigeonhole principle: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greateer than `b`, and a few variations of this theorem. The principle is formalized in the following way, see `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`: if `f : α → β` is a function which maps all elements of `s : finset α` to `t : finset β` and `card t •ℕ b < ∑ x in s, w x`, where `w : α → M` is a weight function taking values in a `decidable_linear_ordered_cancel_add_comm_monoid`, then for some `y ∈ t`, the sum of the weights of all `x ∈ s` such that `f x = y` is greater than `b`. There are a few bits we can change in this theorem: * reverse all inequalities, with obvious adjustments to the name; * replace the assumption `∀ a ∈ s, f a ∈ t` with `∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0`, and replace `of_maps_to` with `of_sum_fiber_nonpos` in the name; * use non-strict inequalities assuming `t` is nonempty. We can do all these variations independently, so we have eight versions of the theorem. -/ /-! #### Strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (hf : ∀ a ∈ s, f a ∈ t) (hb : t.card •ℕ b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_maps_to_of_sum_lt_nsmul (hf : ∀ a ∈ s, f a ∈ t) (hb : (∑ x in s, w x) < t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ hf hb /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum (ht : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (hb : t.card •ℕ b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ calc (∑ y in t, b) < ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos ht /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (ht : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (hb : (∑ x in s, w x) < t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ ht hb /-! #### Non-strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : t.card •ℕ b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_maps_to_of_sum_le_nsmul (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum (hf : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (ht : t.nonempty) (hb : t.card •ℕ b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ calc (∑ y in t, b) ≤ ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos hf /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (hf : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-! ### The pigeonhole principles on `finset`s, pigeons counted by heads In this section we formalize a few versions of the following pigeonhole principle: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. First, we can use strict or non-strict inequalities. While the versions with non-strict inequalities are weaker than those with strict inequalities, sometimes it might be more convenient to apply the weaker version. Second, we can either state that there exists a pigeonhole with at least `n` pigeons, or state that there exists a pigeonhole with at most `n` pigeons. In the latter case we do not need the assumption `∀ a ∈ s, f a ∈ t`. So, we prove four theorems: `finset.exists_lt_card_fiber_of_maps_to_of_mul_lt_card`, `finset.exists_le_card_fiber_of_maps_to_of_mul_le_card`, `finset.exists_card_fiber_lt_of_card_lt_mul`, and `finset.exists_card_fiber_le_of_card_le_mul`. -/ /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n < card s`, there exists `y ∈ t` such that its preimage in `s` has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (hn : t.card * n < s.card) : ∃ y ∈ t, n < (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum hf, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s < card t * n`, there exists `y ∈ t` such that its preimage in `s` has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : s.card < t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card < n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (λ _ _, nat.zero_le _), simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n ≤ card s`, there exists `y ∈ t` such that its preimage in `s` has at least `n` elements. See also `finset.exists_lt_card_fiber_of_mul_lt_card_of_maps_to` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hn : t.card * n ≤ s.card) : ∃ y ∈ t, n ≤ (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum hf ht, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s ≤ card t * n`, there exists `y ∈ t` such that its preimage in `s` has no more than `n` elements. See also `finset.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul (ht : t.nonempty) (hn : s.card ≤ t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card ≤ n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (λ _ _, nat.zero_le _) ht, simpa end end finset namespace fintype open finset variables [fintype α] [fintype β] (f : α → β) {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `fintypes`s, pigeons counted by weight In this section we specialize theorems from the previous section to the special case of functions between `fintype`s and `s = univ`, `t = univ`. In this case the assumption `∀ x ∈ s, f x ∈ t` always holds, so we have four theorems instead of eight. -/ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than `b` provided that the total number of pigeonholes times `b` is less than the total weight of all pigeons. -/ lemma exists_lt_sum_fiber_of_nsmul_lt_sum (hb : card β •ℕ b < ∑ x, w x) : ∃ y, b < ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (λ _ _, mem_univ _) hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than or equal to `b` provided that the total number of pigeonholes times `b` is less than or equal to the total weight of all pigeons. -/ lemma exists_le_sum_fiber_of_nsmul_le_sum [nonempty β] (hb : card β •ℕ b ≤ ∑ x, w x) : ∃ y, b ≤ ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (λ _ _, mem_univ _) univ_nonempty hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than `b` provided that the total number of pigeonholes times `b` is greater than the total weight of all pigeons. -/ lemma exists_sum_fiber_lt_of_sum_lt_nsmul (hb : (∑ x, w x) < card β •ℕ b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ w b hb /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than or equal to `b` provided that the total number of pigeonholes times `b` is greater than or equal to the total weight of all pigeons. -/ lemma exists_sum_fiber_le_of_sum_le_nsmul [nonempty β] (hb : (∑ x, w x) ≤ card β •ℕ b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ w b _ hb /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n < card α`, there exists an element `y : β` such that its preimage has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card (hn : card β * n < card α) : ∃ y : β, n < (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_lt_card_fiber_of_mul_lt_card_of_maps_to (λ _ _, mem_univ _) hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card α < card β * n`, there exists an element `y : β` such that its preimage has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : card α < card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card < n := let ⟨y, _, h⟩ := exists_card_fiber_lt_of_card_lt_mul hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n ≤ card α`, there exists an element `y : β` such that its preimage has at least `n` elements. See also `fintype.exists_lt_card_fiber_of_mul_lt_card` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card [nonempty β] (hn : card β * n ≤ card α) : ∃ y : β, n ≤ (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_le_card_fiber_of_mul_le_card_of_maps_to (λ _ _, mem_univ _) univ_nonempty hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card α ≤ card β * n`, there exists an element `y : β` such that its preimage has at most `n` elements. See also `fintype.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul [nonempty β] (hn : card α ≤ card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card ≤ n := let ⟨y, _, h⟩ := exists_card_fiber_le_of_card_le_mul univ_nonempty hn in ⟨y, h⟩ end fintype
047f9bdd7a63d75fe3c0bc5fad42e2289efa10a6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monoidal/preadditive.lean
10c0e82a496054d3ba06f0be4d5cb891c9a09419
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
9,665
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.additive_functor import category_theory.monoidal.functor /-! # Preadditive monoidal categories A monoidal category is `monoidal_preadditive` if it is preadditive and tensor product of morphisms is linear in both factors. -/ noncomputable theory open_locale classical namespace category_theory open category_theory.limits open category_theory.monoidal_category variables (C : Type*) [category C] [preadditive C] [monoidal_category C] /-- A category is `monoidal_preadditive` if tensoring is additive in both factors. Note we don't `extend preadditive C` here, as `abelian C` already extends it, and we'll need to have both typeclasses sometimes. -/ class monoidal_preadditive := (tensor_zero' : ∀ {W X Y Z : C} (f : W ⟶ X), f ⊗ (0 : Y ⟶ Z) = 0 . obviously) (zero_tensor' : ∀ {W X Y Z : C} (f : Y ⟶ Z), (0 : W ⟶ X) ⊗ f = 0 . obviously) (tensor_add' : ∀ {W X Y Z : C} (f : W ⟶ X) (g h : Y ⟶ Z), f ⊗ (g + h) = f ⊗ g + f ⊗ h . obviously) (add_tensor' : ∀ {W X Y Z : C} (f g : W ⟶ X) (h : Y ⟶ Z), (f + g) ⊗ h = f ⊗ h + g ⊗ h . obviously) restate_axiom monoidal_preadditive.tensor_zero' restate_axiom monoidal_preadditive.zero_tensor' restate_axiom monoidal_preadditive.tensor_add' restate_axiom monoidal_preadditive.add_tensor' attribute [simp] monoidal_preadditive.tensor_zero monoidal_preadditive.zero_tensor variables {C} [monoidal_preadditive C] local attribute [simp] monoidal_preadditive.tensor_add monoidal_preadditive.add_tensor instance tensor_left_additive (X : C) : (tensor_left X).additive := {} instance tensor_right_additive (X : C) : (tensor_right X).additive := {} instance tensoring_left_additive (X : C) : ((tensoring_left C).obj X).additive := {} instance tensoring_right_additive (X : C) : ((tensoring_right C).obj X).additive := {} /-- A faithful additive monoidal functor to a monoidal preadditive category ensures that the domain is monoidal preadditive. -/ def monoidal_preadditive_of_faithful {D : Type*} [category D] [preadditive D] [monoidal_category D] (F : monoidal_functor D C) [faithful F.to_functor] [F.to_functor.additive] : monoidal_preadditive D := { tensor_zero' := by { intros, apply F.to_functor.map_injective, simp [F.map_tensor], }, zero_tensor' := by { intros, apply F.to_functor.map_injective, simp [F.map_tensor], }, tensor_add' := begin intros, apply F.to_functor.map_injective, simp only [F.map_tensor, F.to_functor.map_add, preadditive.comp_add, preadditive.add_comp, monoidal_preadditive.tensor_add], end, add_tensor' := begin intros, apply F.to_functor.map_injective, simp only [F.map_tensor, F.to_functor.map_add, preadditive.comp_add, preadditive.add_comp, monoidal_preadditive.add_tensor], end, } open_locale big_operators lemma tensor_sum {P Q R S : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (R ⟶ S)) : f ⊗ ∑ j in s, g j = ∑ j in s, f ⊗ g j := begin rw ←tensor_id_comp_id_tensor, let tQ := (((tensoring_left C).obj Q).map_add_hom : (R ⟶ S) →+ _), change _ ≫ tQ _ = _, rw [tQ.map_sum, preadditive.comp_sum], dsimp [tQ], simp only [tensor_id_comp_id_tensor], end lemma sum_tensor {P Q R S : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (R ⟶ S)) : (∑ j in s, g j) ⊗ f = ∑ j in s, g j ⊗ f := begin rw ←tensor_id_comp_id_tensor, let tQ := (((tensoring_right C).obj P).map_add_hom : (R ⟶ S) →+ _), change tQ _ ≫ _ = _, rw [tQ.map_sum, preadditive.sum_comp], dsimp [tQ], simp only [tensor_id_comp_id_tensor], end variables {C} -- In a closed monoidal category, this would hold because -- `tensor_left X` is a left adjoint and hence preserves all colimits. -- In any case it is true in any preadditive category. instance (X : C) : preserves_finite_biproducts (tensor_left X) := { preserves := λ J _, by exactI { preserves := λ f, { preserves := λ b i, is_bilimit_of_total _ begin dsimp, simp only [←tensor_comp, category.comp_id, ←tensor_sum, ←tensor_id, is_bilimit.total i], end } } } instance (X : C) : preserves_finite_biproducts (tensor_right X) := { preserves := λ J _, by exactI { preserves := λ f, { preserves := λ b i, is_bilimit_of_total _ begin dsimp, simp only [←tensor_comp, category.comp_id, ←sum_tensor, ←tensor_id, is_bilimit.total i], end } } } variables [has_finite_biproducts C] /-- The isomorphism showing how tensor product on the left distributes over direct sums. -/ def left_distributor {J : Type} [fintype J] (X : C) (f : J → C) : X ⊗ (⨁ f) ≅ ⨁ (λ j, X ⊗ f j) := (tensor_left X).map_biproduct f @[simp] lemma left_distributor_hom {J : Type} [fintype J] (X : C) (f : J → C) : (left_distributor X f).hom = ∑ j : J, (𝟙 X ⊗ biproduct.π f j) ≫ biproduct.ι _ j := begin ext, dsimp [tensor_left, left_distributor], simp [preadditive.sum_comp, biproduct.ι_π, comp_dite], end @[simp] lemma left_distributor_inv {J : Type} [fintype J] (X : C) (f : J → C) : (left_distributor X f).inv = ∑ j : J, biproduct.π _ j ≫ (𝟙 X ⊗ biproduct.ι f j) := begin ext, dsimp [tensor_left, left_distributor], simp [preadditive.comp_sum, biproduct.ι_π_assoc, dite_comp], end lemma left_distributor_assoc {J : Type} [fintype J] (X Y : C) (f : J → C) : (as_iso (𝟙 X) ⊗ left_distributor Y f) ≪≫ left_distributor X _ = (α_ X Y (⨁ f)).symm ≪≫ left_distributor (X ⊗ Y) f ≪≫ biproduct.map_iso (λ j, α_ X Y _) := begin ext, simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.trans_hom, iso.symm_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum, tensor_sum, id_tensor_comp, tensor_iso_hom, left_distributor_hom, biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π, finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero], simp only [←id_tensor_comp, biproduct.ι_π], simp only [id_tensor_comp, tensor_dite, comp_dite], simp only [category.comp_id, comp_zero, monoidal_preadditive.tensor_zero, eq_to_hom_refl, tensor_id, if_true, dif_ctx_congr, finset.sum_congr, finset.mem_univ, finset.sum_dite_eq'], simp only [←tensor_id, associator_naturality, iso.inv_hom_id_assoc], end /-- The isomorphism showing how tensor product on the right distributes over direct sums. -/ def right_distributor {J : Type} [fintype J] (X : C) (f : J → C) : (⨁ f) ⊗ X ≅ ⨁ (λ j, f j ⊗ X) := (tensor_right X).map_biproduct f @[simp] lemma right_distributor_hom {J : Type} [fintype J] (X : C) (f : J → C) : (right_distributor X f).hom = ∑ j : J, (biproduct.π f j ⊗ 𝟙 X) ≫ biproduct.ι _ j := begin ext, dsimp [tensor_right, right_distributor], simp [preadditive.sum_comp, biproduct.ι_π, comp_dite], end @[simp] lemma right_distributor_inv {J : Type} [fintype J] (X : C) (f : J → C) : (right_distributor X f).inv = ∑ j : J, biproduct.π _ j ≫ (biproduct.ι f j ⊗ 𝟙 X) := begin ext, dsimp [tensor_right, right_distributor], simp [preadditive.comp_sum, biproduct.ι_π_assoc, dite_comp], end lemma right_distributor_assoc {J : Type} [fintype J] (X Y : C) (f : J → C) : (right_distributor X f ⊗ as_iso (𝟙 Y)) ≪≫ right_distributor Y _ = α_ (⨁ f) X Y ≪≫ right_distributor (X ⊗ Y) f ≪≫ biproduct.map_iso (λ j, (α_ _ X Y).symm) := begin ext, simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.symm_hom, iso.trans_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum, sum_tensor, comp_tensor_id, tensor_iso_hom, right_distributor_hom, biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π, finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero, finset.mem_univ, if_true], simp only [←comp_tensor_id, biproduct.ι_π, dite_tensor, comp_dite], simp only [category.comp_id, comp_tensor_id, eq_to_hom_refl, tensor_id, comp_zero, monoidal_preadditive.zero_tensor, if_true, dif_ctx_congr, finset.mem_univ, finset.sum_congr, finset.sum_dite_eq'], simp only [←tensor_id, associator_inv_naturality, iso.hom_inv_id_assoc] end lemma left_distributor_right_distributor_assoc {J : Type*} [fintype J] (X Y : C) (f : J → C) : (left_distributor X f ⊗ as_iso (𝟙 Y)) ≪≫ right_distributor Y _ = α_ X (⨁ f) Y ≪≫ (as_iso (𝟙 X) ⊗ right_distributor Y _) ≪≫ left_distributor X _ ≪≫ biproduct.map_iso (λ j, (α_ _ _ _).symm) := begin ext, simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.symm_hom, iso.trans_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum, sum_tensor, tensor_sum, comp_tensor_id, tensor_iso_hom, left_distributor_hom, right_distributor_hom, biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π, finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero, finset.mem_univ, if_true], simp only [←comp_tensor_id, ←id_tensor_comp_assoc, category.assoc, biproduct.ι_π, comp_dite, dite_comp, tensor_dite, dite_tensor], simp only [category.comp_id, category.id_comp, category.assoc, id_tensor_comp, comp_zero, zero_comp, monoidal_preadditive.tensor_zero, monoidal_preadditive.zero_tensor, comp_tensor_id, eq_to_hom_refl, tensor_id, if_true, dif_ctx_congr, finset.sum_congr, finset.mem_univ, finset.sum_dite_eq'], simp only [associator_inv_naturality, iso.hom_inv_id_assoc] end end category_theory
2f43f9aa877c9b1ea13178fdbe64a5274b12f072
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/linear_ordered_comm_group_with_zero.lean
b4bbe13ac8b17441720693cf9b0574d78f04813d
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,716
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ordered_group import Mathlib.algebra.group_with_zero.default import Mathlib.algebra.group_with_zero.power import Mathlib.tactic.abel import Mathlib.PostPort universes u_1 l u_2 namespace Mathlib /-! # Linearly ordered commutative groups and monoids with a zero element adjoined This file sets up a special class of linearly ordered commutative monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}. The disadvantage is that a type such as `nnreal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. Note that to avoid issues with import cycles, `linear_ordered_comm_monoid_with_zero` is defined in another file. However, the lemmas about it are stated here. -/ /-- A linearly ordered commutative group with a zero element. -/ class linear_ordered_comm_group_with_zero (α : Type u_1) extends comm_group_with_zero α, linear_ordered_comm_monoid_with_zero α where /- The following facts are true more generally in a (linearly) ordered commutative monoid. -/ theorem one_le_pow_of_one_le' {α : Type u_1} {x : α} [linear_ordered_comm_monoid_with_zero α] {n : ℕ} (H : 1 ≤ x) : 1 ≤ x ^ n := Nat.rec (le_refl 1) (fun (n : ℕ) (ih : 1 ≤ x ^ n) => one_le_mul H ih) n theorem pow_le_one_of_le_one {α : Type u_1} {x : α} [linear_ordered_comm_monoid_with_zero α] {n : ℕ} (H : x ≤ 1) : x ^ n ≤ 1 := Nat.rec (le_refl 1) (fun (n : ℕ) (ih : x ^ n ≤ 1) => mul_le_one' H ih) n theorem eq_one_of_pow_eq_one {α : Type u_1} {x : α} [linear_ordered_comm_monoid_with_zero α] {n : ℕ} (hn : n ≠ 0) (H : x ^ n = 1) : x = 1 := sorry theorem pow_eq_one_iff {α : Type u_1} {x : α} [linear_ordered_comm_monoid_with_zero α] {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := { mp := eq_one_of_pow_eq_one hn, mpr := fun (ᾰ : x = 1) => Eq._oldrec (one_pow n) (Eq.symm ᾰ) } theorem one_le_pow_iff {α : Type u_1} {x : α} [linear_ordered_comm_monoid_with_zero α] {n : ℕ} (hn : n ≠ 0) : 1 ≤ x ^ n ↔ 1 ≤ x := sorry theorem pow_le_one_iff {α : Type u_1} {x : α} [linear_ordered_comm_monoid_with_zero α] {n : ℕ} (hn : n ≠ 0) : x ^ n ≤ 1 ↔ x ≤ 1 := sorry theorem zero_le_one' {α : Type u_1} [linear_ordered_comm_monoid_with_zero α] : 0 ≤ 1 := linear_ordered_comm_monoid_with_zero.zero_le_one @[simp] theorem zero_le' {α : Type u_1} {a : α} [linear_ordered_comm_monoid_with_zero α] : 0 ≤ a := sorry @[simp] theorem not_lt_zero' {α : Type u_1} {a : α} [linear_ordered_comm_monoid_with_zero α] : ¬a < 0 := not_lt_of_le zero_le' @[simp] theorem le_zero_iff {α : Type u_1} {a : α} [linear_ordered_comm_monoid_with_zero α] : a ≤ 0 ↔ a = 0 := { mp := fun (h : a ≤ 0) => le_antisymm h zero_le', mpr := fun (h : a = 0) => h ▸ le_refl a } theorem zero_lt_iff {α : Type u_1} {a : α} [linear_ordered_comm_monoid_with_zero α] : 0 < a ↔ a ≠ 0 := { mp := ne_of_gt, mpr := fun (h : a ≠ 0) => lt_of_le_of_ne zero_le' (ne.symm h) } theorem ne_zero_of_lt {α : Type u_1} {a : α} {b : α} [linear_ordered_comm_monoid_with_zero α] (h : b < a) : a ≠ 0 := fun (h1 : a = 0) => not_lt_zero' ((fun (this : b < 0) => this) (h1 ▸ h)) theorem zero_lt_one'' {α : Type u_1} [linear_ordered_comm_group_with_zero α] : 0 < 1 := lt_of_le_of_ne zero_le_one' zero_ne_one theorem le_of_le_mul_right {α : Type u_1} {a : α} {b : α} {c : α} [linear_ordered_comm_group_with_zero α] (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b := sorry theorem le_mul_inv_of_mul_le {α : Type u_1} {a : α} {b : α} {c : α} [linear_ordered_comm_group_with_zero α] (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * (c⁻¹) := sorry theorem mul_inv_le_of_le_mul {α : Type u_1} {a : α} {b : α} {c : α} [linear_ordered_comm_group_with_zero α] (h : c ≠ 0) (hab : a ≤ b * c) : a * (c⁻¹) ≤ b := sorry theorem div_le_div' {α : Type u_1} [linear_ordered_comm_group_with_zero α] (a : α) (b : α) (c : α) (d : α) (hb : b ≠ 0) (hd : d ≠ 0) : a * (b⁻¹) ≤ c * (d⁻¹) ↔ a * d ≤ c * b := sorry @[simp] theorem units.zero_lt {α : Type u_1} [linear_ordered_comm_group_with_zero α] (u : units α) : 0 < ↑u := iff.mpr zero_lt_iff (units.ne_zero u) theorem mul_lt_mul'''' {α : Type u_1} {a : α} {b : α} {c : α} {d : α} [linear_ordered_comm_group_with_zero α] (hab : a < b) (hcd : c < d) : a * c < b * d := sorry theorem mul_inv_lt_of_lt_mul' {α : Type u_1} {x : α} {y : α} {z : α} [linear_ordered_comm_group_with_zero α] (h : x < y * z) : x * (z⁻¹) < y := sorry theorem mul_lt_right' {α : Type u_1} {a : α} {b : α} [linear_ordered_comm_group_with_zero α] (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c := sorry theorem pow_lt_pow_succ {α : Type u_1} [linear_ordered_comm_group_with_zero α] {x : α} {n : ℕ} (hx : 1 < x) : x ^ n < x ^ Nat.succ n := eq.mpr (id (Eq._oldrec (Eq.refl (x ^ n < x ^ Nat.succ n)) (Eq.symm (one_mul (x ^ n))))) (mul_lt_right' (x ^ n) hx (pow_ne_zero n (ne_of_gt (lt_trans zero_lt_one'' hx)))) theorem pow_lt_pow' {α : Type u_1} [linear_ordered_comm_group_with_zero α] {x : α} {m : ℕ} {n : ℕ} (hx : 1 < x) (hmn : m < n) : x ^ m < x ^ n := nat.less_than_or_equal.drec (pow_lt_pow_succ hx) (fun {n : ℕ} (hmn : nat.less_than_or_equal (Nat.succ m) n) (ih : x ^ m < x ^ n) => lt_trans ih (pow_lt_pow_succ hx)) hmn theorem inv_lt_inv'' {α : Type u_1} {a : α} {b : α} [linear_ordered_comm_group_with_zero α] (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < (b⁻¹) ↔ b < a := inv_lt_inv_iff theorem inv_le_inv'' {α : Type u_1} {a : α} {b : α} [linear_ordered_comm_group_with_zero α] (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ (b⁻¹) ↔ b ≤ a := inv_le_inv_iff namespace monoid_hom theorem map_neg_one {α : Type u_1} [linear_ordered_comm_group_with_zero α] {R : Type u_2} [ring R] (f : R →* α) : coe_fn f (-1) = 1 := sorry @[simp] theorem map_neg {α : Type u_1} [linear_ordered_comm_group_with_zero α] {R : Type u_2} [ring R] (f : R →* α) (x : R) : coe_fn f (-x) = coe_fn f x := sorry theorem map_sub_swap {α : Type u_1} [linear_ordered_comm_group_with_zero α] {R : Type u_2} [ring R] (f : R →* α) (x : R) (y : R) : coe_fn f (x - y) = coe_fn f (y - x) := sorry
2a4974753ce67e76176073fbe1971edb40ec498a
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/free_module/basic.lean
b9c8ae4430a7df1cb87399ba34bebd233db97dfa
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,433
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.direct_sum.finsupp import logic.small /-! # Free modules We introduce a class `module.free R M`, for `R` a `semiring` and `M` an `R`-module and we provide several basic instances for this class. Use `finsupp.total_id_surjective` to prove that any module is the quotient of a free module. ## Main definition * `module.free R M` : the class of free `R`-modules. -/ universes u v w z variables (R : Type u) (M : Type v) (N : Type z) open_locale tensor_product direct_sum big_operators section basic variables [semiring R] [add_comm_monoid M] [module R M] /-- `module.free R M` is the statement that the `R`-module `M` is free.-/ class module.free : Prop := (exists_basis [] : nonempty (Σ (I : Type v), basis I R M)) /- If `M` fits in universe `w`, then freeness is equivalent to existence of a basis in that universe. Note that if `M` does not fit in `w`, the reverse direction of this implication is still true as `module.free.of_basis`. -/ lemma module.free_def [small.{w} M] : module.free R M ↔ ∃ (I : Type w), nonempty (basis I R M) := ⟨ λ h, ⟨shrink (set.range h.exists_basis.some.2), ⟨(basis.reindex_range h.exists_basis.some.2).reindex (equiv_shrink _)⟩⟩, λ h, ⟨(nonempty_sigma.2 h).map $ λ ⟨i, b⟩, ⟨set.range b, b.reindex_range⟩⟩⟩ lemma module.free_iff_set : module.free R M ↔ ∃ (S : set M), nonempty (basis S R M) := ⟨λ h, ⟨set.range h.exists_basis.some.2, ⟨basis.reindex_range h.exists_basis.some.2⟩⟩, λ ⟨S, hS⟩, ⟨nonempty_sigma.2 ⟨S, hS⟩⟩⟩ variables {R M} lemma module.free.of_basis {ι : Type w} (b : basis ι R M) : module.free R M := (module.free_def R M).2 ⟨set.range b, ⟨b.reindex_range⟩⟩ end basic namespace module.free section semiring variables (R M) [semiring R] [add_comm_monoid M] [module R M] [module.free R M] variables [add_comm_monoid N] [module R N] /-- If `[finite_free R M]` then `choose_basis_index R M` is the `ι` which indexes the basis `ι → M`. -/ @[nolint has_inhabited_instance] def choose_basis_index := (exists_basis R M).some.1 /-- If `[finite_free R M]` then `choose_basis : ι → M` is the basis. Here `ι = choose_basis_index R M`. -/ noncomputable def choose_basis : basis (choose_basis_index R M) R M := (exists_basis R M).some.2 /-- The isomorphism `M ≃ₗ[R] (choose_basis_index R M →₀ R)`. -/ noncomputable def repr : M ≃ₗ[R] (choose_basis_index R M →₀ R) := (choose_basis R M).repr /-- The universal property of free modules: giving a functon `(choose_basis_index R M) → N`, for `N` an `R`-module, is the same as giving an `R`-linear map `M →ₗ[R] N`. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ noncomputable def constr {S : Type z} [semiring S] [module S N] [smul_comm_class R S N] : ((choose_basis_index R M) → N) ≃ₗ[S] M →ₗ[R] N := basis.constr (choose_basis R M) S @[priority 100] instance no_zero_smul_divisors [no_zero_divisors R] : no_zero_smul_divisors R M := let ⟨⟨_, b⟩⟩ := exists_basis R M in b.no_zero_smul_divisors variables {R M N} lemma of_equiv (e : M ≃ₗ[R] N) : module.free R N := of_basis $ (choose_basis R M).map e /-- A variation of `of_equiv`: the assumption `module.free R P` here is explicit rather than an instance. -/ lemma of_equiv' {P : Type v} [add_comm_monoid P] [module R P] (h : module.free R P) (e : P ≃ₗ[R] N) : module.free R N := of_equiv e variables (R M N) instance {ι : Type v} : module.free R (ι →₀ R) := of_basis (basis.of_repr (linear_equiv.refl _ _)) instance {ι : Type v} [fintype ι] : module.free R (ι → R) := of_equiv (basis.of_repr $ linear_equiv.refl _ _).equiv_fun instance prod [module.free R N] : module.free R (M × N) := of_basis $ (choose_basis R M).prod (choose_basis R N) instance self : module.free R R := of_basis $ basis.singleton unit R @[priority 100] instance of_subsingleton [subsingleton N] : module.free R N := of_basis (basis.empty N : basis pempty R N) instance dfinsupp {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π₀ i, M i) := of_basis $ dfinsupp.basis $ λ i, choose_basis R (M i) instance direct_sum {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (⨁ i, M i) := module.free.dfinsupp R M end semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] [module.free R M] variables [add_comm_group N] [module R N] [module.free R N] instance tensor : module.free R (M ⊗[R] N) := of_equiv' (of_equiv' (finsupp.free R) (finsupp_tensor_finsupp' R _ _).symm) (tensor_product.congr (choose_basis R M).repr (choose_basis R N).repr).symm end comm_ring section division_ring variables [division_ring R] [add_comm_group M] [module R M] @[priority 100] instance of_division_ring : module.free R M := of_basis (basis.of_vector_space R M) end division_ring end module.free
74d097d87fdaa3633ca90ba410fdbc0c2bc46a70
32da3d0f92cab08875472ef6cacc1931c2b3eafa
/src/data/nat/fib.lean
b03780b68d8008ec7040710842b0894ec9392e3f
[ "Apache-2.0" ]
permissive
karthiknadig/mathlib
b6073c3748860bfc9a3e55da86afcddba62dc913
33a86cfff12d7f200d0010cd03b95e9b69a6c1a5
refs/heads/master
1,676,389,371,851
1,610,061,127,000
1,610,061,127,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,641
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.stream.basic import tactic import data.nat.gcd /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. ## Main Definitions - `fib` returns the stream of Fibonacci numbers. ## Main Statements - `fib_succ_succ` : shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`. - `fib_gcd` : `fib n` is a strong divisibility sequence. ## Implementation Notes For efficiency purposes, the sequence is defined using `stream.iterate`. ## Tags fib, fibonacci -/ namespace nat /-- Auxiliary function used in the definition of `fib_aux_stream`. -/ private def fib_aux_step : (ℕ × ℕ) → (ℕ × ℕ) := λ p, ⟨p.snd, p.fst + p.snd⟩ /-- Auxiliary stream creating Fibonacci pairs `⟨Fₙ, Fₙ₊₁⟩`. -/ private def fib_aux_stream : stream (ℕ × ℕ) := stream.iterate fib_aux_step ⟨0, 1⟩ /-- Implementation of the fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ @[pp_nodot] def fib (n : ℕ) : ℕ := (fib_aux_stream n).fst @[simp] lemma fib_zero : fib 0 = 0 := rfl @[simp] lemma fib_one : fib 1 = 1 := rfl @[simp] lemma fib_two : fib 2 = 1 := rfl private lemma fib_aux_stream_succ {n : ℕ} : fib_aux_stream (n + 1) = fib_aux_step (fib_aux_stream n) := begin change (stream.nth (n + 1) $ stream.iterate fib_aux_step ⟨0, 1⟩) = fib_aux_step (stream.nth n $ stream.iterate fib_aux_step ⟨0, 1⟩), rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map] end /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/ lemma fib_succ_succ {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by simp only [fib, fib_aux_stream_succ, fib_aux_step] lemma fib_pos {n : ℕ} (n_pos : 0 < n) : 0 < fib n := begin induction n with n IH, case nat.zero { norm_num at n_pos }, case nat.succ { cases n, case nat.zero { simp [fib_succ_succ, zero_lt_one] }, case nat.succ { have : 0 ≤ fib n, by simp, exact (lt_add_of_nonneg_of_lt this $ IH n.succ_pos) }} end lemma fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by { cases n; simp [fib_succ_succ] } lemma fib_mono {n m : ℕ} (n_le_m : n ≤ m) : fib n ≤ fib m := by { induction n_le_m with m n_le_m IH, { refl }, { exact (le_trans IH fib_le_fib_succ) }} lemma le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := begin induction five_le_n with n five_le_n IH, { have : 5 = fib 5, by refl, -- 5 ≤ fib 5 exact le_of_eq this }, { -- n + 1 ≤ fib (n + 1) for 5 ≤ n cases n with n', -- rewrite n = succ n' to use fib.succ_succ { have : 5 = 0, from nat.le_zero_iff.elim_left five_le_n, contradiction }, rw fib_succ_succ, suffices : 1 + (n' + 1) ≤ fib n' + fib (n' + 1), by rwa [nat.succ_eq_add_one, add_comm], have : n' ≠ 0, by { intro h, have : 5 ≤ 1, by rwa h at five_le_n, norm_num at this }, have : 1 ≤ fib n', from nat.succ_le_of_lt (fib_pos $ zero_lt_iff_ne_zero.mpr this), mono } end /-- Subsequent Fibonacci numbers are coprime, see https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime -/ lemma fib_coprime_fib_succ (n : ℕ) : nat.coprime (fib n) (fib (n + 1)) := begin unfold coprime, induction n with n ih, { simp }, { convert ih using 1, rw [fib_succ_succ, succ_eq_add_one, gcd_rec, add_mod_right, gcd_comm (fib n), gcd_rec (fib (n + 1))], } end /-- See https://proofwiki.org/wiki/Fibonacci_Number_in_terms_of_Smaller_Fibonacci_Numbers -/ lemma fib_add (m n : ℕ) : fib m * fib n + fib (m + 1) * fib (n + 1) = fib (m + n + 1) := begin induction n with n ih generalizing m, { simp }, { intros, specialize ih (m + 1), rw [add_assoc m 1 n, add_comm 1 n] at ih, simp only [fib_succ_succ, ← ih], ring, } end lemma gcd_fib_add_self (m n : ℕ) : gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n) := begin cases eq_zero_or_pos n, { rw h, simp }, replace h := nat.succ_pred_eq_of_pos h, rw [← h, succ_eq_add_one], calc gcd (fib m) (fib (n.pred + 1 + m)) = gcd (fib m) (fib (n.pred) * (fib m) + fib (n.pred + 1) * fib (m + 1)) : by { rw fib_add n.pred _, ring } ... = gcd (fib m) (fib (n.pred + 1) * fib (m + 1)) : by rw [add_comm, gcd_add_mul_self (fib m) _ (fib (n.pred))] ... = gcd (fib m) (fib (n.pred + 1)) : coprime.gcd_mul_right_cancel_right (fib (n.pred + 1)) (coprime.symm (fib_coprime_fib_succ m)) end lemma gcd_fib_add_mul_self (m n : ℕ) : ∀ k, gcd (fib m) (fib (n + k * m)) = gcd (fib m) (fib n) | 0 := by simp | (k+1) := by rw [← gcd_fib_add_mul_self k, add_mul, ← add_assoc, one_mul, gcd_fib_add_self _ _] /-- `fib n` is a strong divisibility sequence, see https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers -/ lemma fib_gcd (m n : ℕ) : fib (gcd m n) = gcd (fib m) (fib n) := begin wlog h : m ≤ n using [n m, m n], exact le_total m n, { apply gcd.induction m n, { simp }, intros m n mpos h, rw ← gcd_rec m n at h, conv_rhs { rw ← mod_add_div n m }, rwa [mul_comm, gcd_fib_add_mul_self m (n % m) (n / m), gcd_comm (fib m) _] }, rwa [gcd_comm, gcd_comm (fib m)] end lemma fib_dvd (m n : ℕ) (h : m ∣ n) : fib m ∣ fib n := by rwa [gcd_eq_left_iff_dvd, ← fib_gcd, gcd_eq_left_iff_dvd.mp] end nat
91d50431459f47853af9ebd789eba52abb34c1f2
590f94277ab689acdc713c44e3bbca2e012fc074
/Sequent Calculus (Lean)/src/soundnessProof.lean
5b750c060d819e7bcc0c7fa959ce5743a2a00d13
[]
no_license
Bpalkmim/iALC
bd3f882ad942c876d65c2d33cb50a36b2f8e5d16
9c2982ae916d01d9ebab9d58e0842292ed974876
refs/heads/master
1,689,527,062,560
1,631,502,537,000
1,631,502,537,000
108,029,498
0
0
null
null
null
null
UTF-8
Lean
false
false
412
lean
-- Prova de correção de SCiALC, composta por provas de correção de -- cada regra de SCiALC. -- Autor: Bernardo Alkmim -- bpalkmim@gmail.com namespace soundnessSCiALC open iALCbasics -- TODO definição de sequente válido -- TODO abox??????? constants A B : Formula constant X : Nominal #check valid_seq (subj_r_n (Proof (Sequent ((Formula.elemOf X A) :: Δ) B))) -- TODO completar end soundnessSCiALC
7de9379466b6dc028aad5db9587aa5422d70f1b9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/direct_limit.lean
3709237a7883a879ab4cb414b47efc069e786a64
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,002
lean
/- Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes -/ import data.finset.order import algebra.direct_sum.module import ring_theory.free_comm_ring import ring_theory.ideal.operations /-! # Direct limit of modules, abelian groups, rings, and fields. See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270 Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring, or incomparable abelian groups, or rings, or fields. It is constructed as a quotient of the free module (for the module case) or quotient of the free commutative ring (for the ring case) instead of a quotient of the disjoint union so as to make the operations (addition etc.) "computable". -/ universes u v w u₁ open submodule variables {R : Type u} [ring R] variables {ι : Type v} variables [dec_ι : decidable_eq ι] [directed_order ι] variables (G : ι → Type w) /-- A directed system is a functor from the category (directed poset) to another category. This is used for abelian groups and rings and fields because their maps are not bundled. See module.directed_system -/ class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) namespace module variables [Π i, add_comm_group (G i)] [Π i, module R (G i)] /-- A directed system is a functor from the category (directed poset) to the category of `R`-modules. -/ class directed_system (f : Π i j, i ≤ j → G i →ₗ[R] G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) variables (f : Π i j, i ≤ j → G i →ₗ[R] G j) include dec_ι /-- The direct limit of a directed system is the modules glued together along the maps. -/ def direct_limit : Type (max v w) := (span R $ { a | ∃ (i j) (H : i ≤ j) x, direct_sum.lof R ι G i x - direct_sum.lof R ι G j (f i j H x) = a }).quotient namespace direct_limit instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _ instance : module R (direct_limit G f) := quotient.module _ instance : inhabited (direct_limit G f) := ⟨0⟩ variables (R ι) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[R] direct_limit G f := (mkq _).comp $ direct_sum.lof R ι G i variables {R ι G f} @[simp] lemma of_f {i j hij x} : (of R ι G f j (f i j hij x)) = of R ι G f i x := eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of R ι G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ z, direct_sum.induction_on z ⟨ind, 0, linear_map.map_zero _⟩ (λ i x, ⟨i, x, rfl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of R ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [add_comm_group P] [module R P] (g : Π i, G i →ₗ[R] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (R ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[R] P := liftq _ (direct_sum.to_module R ι P g) (span_le.2 $ λ a ⟨i, j, hij, x, hx⟩, by rw [← hx, set_like.mem_coe, linear_map.sub_mem_ker_iff, direct_sum.to_module_lof, direct_sum.to_module_lof, Hg]) variables {R ι G f} omit Hg lemma lift_of {i} (x) : lift R ι G f g Hg (of R ι G f i x) = g i x := direct_sum.to_module_lof R _ _ theorem lift_unique [nonempty ι] (F : direct_limit G f →ₗ[R] P) (x) : F x = lift R ι G f (λ i, F.comp $ of R ι G f i) (λ i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl section totalize open_locale classical variables (G f) omit dec_ι /-- `totalize G f i j` is a linear map from `G i` to `G j`, for *every* `i` and `j`. If `i ≤ j`, then it is the map `f i j` that comes with the directed system `G`, and otherwise it is the zero map. -/ noncomputable def totalize : Π i j, G i →ₗ[R] G j := λ i j, if h : i ≤ j then f i j h else 0 variables {G f} lemma totalize_apply (i j x) : totalize G f i j x = if h : i ≤ j then f i j h x else 0 := if h : i ≤ j then by dsimp only [totalize]; rw [dif_pos h, dif_pos h] else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply] end totalize variables [directed_system G f] open_locale classical lemma to_module_totalize_of_le {x : direct_sum ι G} {i j : ι} (hij : i ≤ j) (hx : ∀ k ∈ x.support, k ≤ i) : direct_sum.to_module R ι (G j) (λ k, totalize G f k j) x = f i j hij (direct_sum.to_module R ι (G i) (λ k, totalize G f k i) x) := begin rw [← @dfinsupp.sum_single ι G _ _ _ x], unfold dfinsupp.sum, simp only [linear_map.map_sum], refine finset.sum_congr rfl (λ k hk, _), rw direct_sum.single_eq_lof R k (x k), simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f] end lemma of.zero_exact_aux [nonempty ι] {x : direct_sum ι G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) : ∃ j, (∀ k ∈ x.support, k ≤ j) ∧ direct_sum.to_module R ι (G j) (λ i, totalize G f i j) x = (0 : G j) := nonempty.elim (by apply_instance) $ assume ind : ι, span_induction ((quotient.mk_eq_zero _).1 H) (λ x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, begin clear_, subst hxy, split, { intros i0 hi0, rw [dfinsupp.mem_support_iff, direct_sum.sub_apply, ← direct_sum.single_eq_lof, ← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0, split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk }, exfalso, apply hi0, rw sub_zero }, simp [linear_map.map_sub, totalize_apply, hik, hjk, directed_system.map_map f, direct_sum.apply_eq_component, direct_sum.component.of], end⟩) ⟨ind, λ _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩ (λ x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, λ l hl, (finset.mem_union.1 (dfinsupp.support_add hl)).elim (λ hl, le_trans (hi _ hl) hik) (λ hl, le_trans (hj _ hl) hjk), by simp [linear_map.map_add, hxi, hyj, to_module_totalize_of_le hik hi, to_module_totalize_of_le hjk hj]⟩) (λ a x ⟨i, hi, hxi⟩, ⟨i, λ k hk, hi k (direct_sum.support_smul _ _ hk), by simp [linear_map.map_smul, hxi]⟩) /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact {i x} (H : of R ι G f i x = 0) : ∃ j hij, f i j hij x = (0 : G j) := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in if hx0 : x = 0 then ⟨i, le_refl _, by simp [hx0]⟩ else have hij : i ≤ j, from hj _ $ by simp [direct_sum.apply_eq_component, hx0], ⟨j, hij, by simpa [totalize_apply, hij] using hxj⟩ end direct_limit end module namespace add_comm_group variables [Π i, add_comm_group (G i)] include dec_ι /-- The direct limit of a directed system is the abelian groups glued together along the maps. -/ def direct_limit (f : Π i j, i ≤ j → G i →+ G j) : Type* := @module.direct_limit ℤ _ ι _ _ G _ _ (λ i j hij, (f i j hij).to_int_linear_map) namespace direct_limit variables (f : Π i j, i ≤ j → G i →+ G j) omit dec_ι protected lemma directed_system [directed_system G (λ i j h, f i j h)] : module.directed_system G (λ i j hij, (f i j hij).to_int_linear_map) := ⟨directed_system.map_self (λ i j h, f i j h), directed_system.map_map (λ i j h, f i j h)⟩ include dec_ι local attribute [instance] direct_limit.directed_system instance : add_comm_group (direct_limit G f) := module.direct_limit.add_comm_group G (λ i j hij, (f i j hij).to_int_linear_map) instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[ℤ] direct_limit G f := module.direct_limit.of ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map) i variables {G f} @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := module.direct_limit.of_f @[elab_as_eliminator] protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := module.direct_limit.induction_on z ih /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact [directed_system G (λ i j h, f i j h)] (i x) (h : of G f i x = 0) : ∃ j hij, f i j hij x = 0 := module.direct_limit.of.zero_exact h variables (P : Type u₁) [add_comm_group P] variables (g : Π i, G i →+ P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables (G f) /-- The universal property of the direct limit: maps from the components to another abelian group that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[ℤ] P := module.direct_limit.lift ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map) (λ i, (g i).to_int_linear_map) Hg variables {G f} @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := module.direct_limit.lift_of _ _ _ lemma lift_unique [nonempty ι] (F : direct_limit G f →+ P) (x) : F x = lift G f P (λ i, F.comp (of G f i).to_add_monoid_hom) (λ i j hij x, by simp) x := direct_limit.induction_on x $ λ i x, by simp end direct_limit end add_comm_group namespace ring variables [Π i, comm_ring (G i)] section variables (f : Π i j, i ≤ j → G i → G j) open free_comm_ring /-- The direct limit of a directed system is the rings glued together along the maps. -/ def direct_limit : Type (max v w) := (ideal.span { a | (∃ i j H x, of (⟨j, f i j H x⟩ : Σ i, G i) - of ⟨i, x⟩ = a) ∨ (∃ i, of (⟨i, 1⟩ : Σ i, G i) - 1 = a) ∨ (∃ i x y, of (⟨i, x + y⟩ : Σ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨ (∃ i x y, of (⟨i, x * y⟩ : Σ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }).quotient namespace direct_limit instance : comm_ring (direct_limit G f) := ideal.quotient.comm_ring _ instance : ring (direct_limit G f) := comm_ring.to_ring _ instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →+* direct_limit G f := ring_hom.mk' { to_fun := λ x, ideal.quotient.mk _ (of (⟨i, x⟩ : Σ i, G i)), map_one' := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩, map_mul' := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, } (λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩) variables {G f} @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ x, free_abelian_group.induction_on x ⟨ind, 0, (of _ _ ind).map_zero⟩ (λ s, multiset.induction_on s ⟨ind, 1, (of _ _ ind).map_one⟩ (λ a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x * f j k hjk y, by rw [(of _ _ _).map_mul, of_f, of_f, hs]; refl⟩)) (λ s ⟨i, x, ih⟩, ⟨i, -x, by rw [(of _ _ _).map_neg, ih]; refl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [(of _ _ _).map_add, of_f, of_f, ihx, ihy]; refl⟩) section open_locale classical open polynomial variables {f' : Π i j, i ≤ j → G i →+* G j} theorem polynomial.exists_of [nonempty ι] (q : polynomial (direct_limit G (λ i j h, f' i j h))) : ∃ i p, polynomial.map (of G (λ i j h, f' i j h) i) p = q := polynomial.induction_on q (λ z, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x, by rw [map_C, h]⟩) (λ q₁ q₂ ⟨i₁, p₁, ih₁⟩ ⟨i₂, p₂, ih₂⟩, let ⟨i, h1, h2⟩ := directed_order.directed i₁ i₂ in ⟨i, p₁.map (f' i₁ i h1) + p₂.map (f' i₂ i h2), by { rw [polynomial.map_add, map_map, map_map, ← ih₁, ← ih₂], congr' 2; ext x; simp_rw [ring_hom.comp_apply, of_f] }⟩) (λ n z ih, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x * X ^ (n + 1), by rw [polynomial.map_mul, map_C, h, polynomial.map_pow, map_X]⟩) end @[elab_as_eliminator] theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := let ⟨i, x, hx⟩ := exists_of z in hx ▸ ih i x section of_zero_exact open_locale classical variables (f' : Π i j, i ≤ j → G i →+* G j) variables [directed_system G (λ i j h, f' i j h)] variables (G f) lemma of.zero_exact_aux2 {x : free_comm_ring Σ i, G i} {s t} (hxs : is_supported x s) {j k} (hj : ∀ z : Σ i, G i, z ∈ s → z.1 ≤ j) (hk : ∀ z : Σ i, G i, z ∈ t → z.1 ≤ k) (hjk : j ≤ k) (hst : s ⊆ t) : f' j k hjk (lift (λ ix : s, f' ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) = lift (λ ix : t, f' ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) := begin refine subring.in_closure.rec_on hxs _ _ _ _, { rw [(restriction _).map_one, (free_comm_ring.lift _).map_one, (f' j k hjk).map_one, (restriction _).map_one, (free_comm_ring.lift _).map_one] }, { rw [(restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one, (f' j k hjk).map_neg, (f' j k hjk).map_one, (restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one] }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, (f' j k hjk).map_mul, ih, (restriction _).map_mul, (free_comm_ring.lift _).map_mul, restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of], dsimp only, have := directed_system.map_map (λ i j h, f' i j h), dsimp only at this, rw this, refl }, { rintros x y ihx ihy, rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, (f' j k hjk).map_add, ihx, ihy, (restriction _).map_add, (free_comm_ring.lift _).map_add] } end variables {G f f'} lemma of.zero_exact_aux [nonempty ι] {x : free_comm_ring Σ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G (λ i j h, f' i j h))) : ∃ j s, ∃ H : (∀ k : Σ i, G i, k ∈ s → k.1 ≤ j), is_supported x s ∧ lift (λ ix : s, f' ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) := begin refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _, { rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩), { refine ⟨j, {⟨i, x⟩, ⟨j, f' i j hij x⟩}, _, is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩, { rintros k (rfl | ⟨rfl | _⟩), exact hij, refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of], dsimp only, have := directed_system.map_map (λ i j h, f' i j h), dsimp only at this, rw this, exact sub_self _, exacts [or.inr rfl, or.inl rfl] } }, { refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩, { rintros k (rfl|h), refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, (restriction _).map_one, lift_of, (free_comm_ring.lift _).map_one], dsimp only, rw [(f' i i _).map_one, sub_self], { exact set.mem_singleton _ } } }, { refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_add, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_add, lift_of, lift_of, lift_of], dsimp only, rw (f' i i _).map_add, exact sub_self _, exacts [or.inl rfl, or.inr (or.inr rfl), or.inr (or.inl rfl)] } }, { refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_mul, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_mul, lift_of, lift_of, lift_of], dsimp only, rw (f' i i _).map_mul, exacts [sub_self _, or.inl rfl, or.inr (or.inr rfl), or.inr (or.inl rfl)] } } }, { refine nonempty.elim (by apply_instance) (assume ind : ι, _), refine ⟨ind, ∅, λ _, false.elim, is_supported_zero, _⟩, rw [(restriction _).map_zero, (free_comm_ring.lift _).map_zero] }, { rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, s ∪ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hyt $ set.subset_union_right s t), _⟩, { rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, ← of.zero_exact_aux2 G f' hxs hi this hik (set.subset_union_left s t), ← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right s t), ihs, (f' i k hik).map_zero, iht, (f' j k hjk).map_zero, zero_add] } }, { rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul, rcases exists_finset_support x with ⟨s, hxs⟩, rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ ↑s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exacts [(hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩).trans hik, (hj z hz).trans hjk] }, refine ⟨k, ↑s ∪ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left ↑s t) (is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, ← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right ↑s t), iht, (f' j k hjk).map_zero, mul_zero] } end /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ lemma of.zero_exact {i x} (hix : of G (λ i j h, f' i j h) i x = 0) : ∃ j (hij : i ≤ j), f' i j hij x = 0 := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in have hixs : (⟨i, x⟩ : Σ i, G i) ∈ s, from is_supported_of.1 hxs, ⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩ end of_zero_exact variables (f' : Π i j, i ≤ j → G i →+* G j) /-- If the maps in the directed system are injective, then the canonical maps from the components to the direct limits are injective. -/ theorem of_injective [directed_system G (λ i j h, f' i j h)] (hf : ∀ i j hij, function.injective (f' i j hij)) (i) : function.injective (of G (λ i j h, f' i j h) i) := begin suffices : ∀ x, of G (λ i j h, f' i j h) i x = 0 → x = 0, { intros x y hxy, rw ← sub_eq_zero, apply this, rw [(of G _ i).map_sub, hxy, sub_self] }, intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩, apply hf i j hij, rw [hfx, (f' i j hij).map_zero] end variables (P : Type u₁) [comm_ring P] variables (g : Π i, G i →+* P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg open free_comm_ring variables (G f) /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →+* P := ideal.quotient.lift _ (free_comm_ring.lift $ λ (x : Σ i, G i), g x.1 x.2) begin suffices : ideal.span _ ≤ ideal.comap (free_comm_ring.lift (λ (x : Σ (i : ι), G i), g (x.fst) (x.snd))) ⊥, { intros x hx, exact (mem_bot P).1 (this hx) }, rw ideal.span_le, intros x hx, rw [set_like.mem_coe, ideal.mem_comap, mem_bot], rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩; simp only [ring_hom.map_sub, lift_of, Hg, ring_hom.map_one, ring_hom.map_add, ring_hom.map_mul, (g i).map_one, (g i).map_add, (g i).map_mul, sub_self] end variables {G f} omit Hg @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _ theorem lift_unique [nonempty ι] (F : direct_limit G f →+* P) (x) : F x = lift G f P (λ i, F.comp $ of G f i) (λ i j hij x, by simp) x := direct_limit.induction_on x $ λ i x, by simp end direct_limit end end ring namespace field variables [nonempty ι] [Π i, field (G i)] variables (f : Π i j, i ≤ j → G i → G j) variables (f' : Π i j, i ≤ j → G i →+* G j) namespace direct_limit instance nontrivial [directed_system G (λ i j h, f' i j h)] : nontrivial (ring.direct_limit G (λ i j h, f' i j h)) := ⟨⟨0, 1, nonempty.elim (by apply_instance) $ assume i : ι, begin change (0 : ring.direct_limit G (λ i j h, f' i j h)) ≠ 1, rw ← (ring.direct_limit.of _ _ _).map_one, intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩, rw (f' i j hij).map_one at hf, exact one_ne_zero hf end ⟩⟩ theorem exists_inv {p : ring.direct_limit G f} : p ≠ 0 → ∃ y, p * y = 1 := ring.direct_limit.induction_on p $ λ i x H, ⟨ring.direct_limit.of G f i (x⁻¹), by erw [← (ring.direct_limit.of _ _ _).map_mul, mul_inv_cancel (assume h : x = 0, H $ by rw [h, (ring.direct_limit.of _ _ _).map_zero]), (ring.direct_limit.of _ _ _).map_one]⟩ section open_locale classical /-- Noncomputable multiplicative inverse in a direct limit of fields. -/ noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f := if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H) protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : p * inv G f p = 1 := by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)] protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : inv G f p * p = 1 := by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp] /-- Noncomputable field structure on the direct limit of fields. See note [reducible non-instances]. -/ @[reducible] protected noncomputable def field [directed_system G (λ i j h, f' i j h)] : field (ring.direct_limit G (λ i j h, f' i j h)) := { inv := inv G (λ i j h, f' i j h), mul_inv_cancel := λ p, direct_limit.mul_inv_cancel G (λ i j h, f' i j h), inv_zero := dif_pos rfl, .. ring.direct_limit.comm_ring G (λ i j h, f' i j h), .. direct_limit.nontrivial G (λ i j h, f' i j h) } end end direct_limit end field
2b5e640fbd7e53e0cfb66289dd9afafa3f5dfd37
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/match_tac3.lean
bd5f7738df4dbf83c0e83519e37fbb7711be676e
[ "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
239
lean
import data.nat open nat algebra theorem tst (a b : nat) (H : a = 0) : a + b = b := begin revert H, match a with | zero := λ H, by krewrite zero_add | (n+1) := λ H, nat.no_confusion H end end reveal tst print definition tst
278d776381dcc22ee8b1d4c9e7e910829183c708
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/basic.lean
083253038a6bba11d4ff76894a90796e8f459db0
[ "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
17,847
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.subtype import data.prod open function /-! # Basic definitions about `≤` and `<` ## Definitions ### Predicates on functions - `monotone f`: a function between two types equipped with `≤` is monotone if `a ≤ b` implies `f a ≤ f b`. - `strict_mono f` : a function between two types equipped with `<` is strictly monotone if `a < b` implies `f a < f b`. - `order_dual α` : a type tag reversing the meaning of all inequalities. ### Transfering orders - `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`, `decidable_linear_order.lift`: transfer a partial (resp., linear, decidable linear) order on `β` to a partial (resp., linear, decidable linear) order on `α` using an injective function `f`. ### Extra classes - `no_top_order`, `no_bot_order`: an order without a maximal/minimal element. - `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists `c`, `a<c<b`. ## Main theorems - `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone; - `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## See also - `algebra.order` for basic lemmas about orders, and projection notation for orders ## Tags preorder, order, partial order, linear order, monotone, strictly monotone -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin casesI A, casesI B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := preorder.ext H, casesI A, casesI B, injection this, congr' } theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := partial_order.ext H, casesI A, casesI B, injection this, congr' } /-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `rel_embedding` (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n ihn, ihn.comp hf) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } end monotone /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id /-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies `f x < f y`. -/ def strict_mono_incr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ (x ∈ t) (y ∈ t), x < y → f x < f y /-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies `f y < f x`. -/ def strict_mono_decr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ (x ∈ t) (y ∈ t), x < y → f y < f x namespace strict_mono open ordering function lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf) lemma id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n := λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (lt_of_le_of_lt hn $ h $ nat.lt_succ_self n)) section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {a b} : f a < f b ↔ a < b := ⟨λ h, ((lt_trichotomy b a) .resolve_left $ λ h', lt_asymm h $ H h') .resolve_left $ λ e, ne_of_gt h $ congr_arg _ e, @H _ _⟩ lemma injective (H : strict_mono f) : injective f | a b e := ((lt_trichotomy a b) .resolve_left $ λ h, ne_of_lt (H h) e) .resolve_right $ λ h, ne_of_gt (H h) e theorem compares (H : strict_mono f) {a b} : ∀ {o}, compares o (f a) (f b) ↔ compares o a b | lt := H.lt_iff_lt | eq := ⟨λ h, H.injective h, congr_arg _⟩ | gt := H.lt_iff_lt lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H h')) (λ h', h' ▸ le_refl _)⟩ lemma top_preimage_top (H : strict_mono f) {a} (h_top : ∀ p, p ≤ f a) (x : α) : x ≤ a := H.le_iff_le.mp (h_top (f x)) lemma bot_preimage_bot (H : strict_mono f) {a} (h_bot : ∀ p, f a ≤ p) (x : α) : a ≤ x := H.le_iff_le.mp (h_bot (f x)) end protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f := by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact ih.trans (h _) } -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl) end strict_mono section open function lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f := begin intros x y k, contrapose k, rw [←ne.def, ne_iff_lt_or_gt] at k, cases k, { apply h _ _ k }, { rw eq_comm, apply h _ _ k } end lemma strict_mono_of_monotone_of_injective [partial_order α] [partial_order β] {f : α → β} (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end lemma strict_mono_of_le_iff_le [preorder α] [preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f x ≤ f y) : strict_mono f := λ a b, by simp [lt_iff_le_not_le, h] {contextual := tt} end /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, hbc.trans hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.linear_order α } instance : Π [inhabited α], inhabited (order_dual α) := id end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] protected theorem monotone.order_dual {f : α → γ} (hf : monotone f) : @monotone (order_dual α) (order_dual γ) _ _ f := λ x y hxy, hf hxy theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) : @strict_mono (order_dual α) (order_dual β) _ _ f := λ x y hxy, hf hxy /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/ def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. -/ def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. -/ def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj } /-- Transfer a `decidable_linear_order` on `β` to a `decidable_linear_order` on `α` using an injective function `f : α → β`. -/ def decidable_linear_order.lift {α β} [decidable_linear_order β] (f : α → β) (inj : injective f) : decidable_linear_order α := { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective instance subtype.decidable_linear_order {α} [decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val subtype.val_injective lemma strict_mono_coe [preorder α] (t : set α) : strict_mono (coe : (subtype t) → α) := λ x y, id instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /-! ### Additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top instance nonempty_gt {α : Type u} [preorder α] [no_top_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (no_top a) /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ instance nonempty_lt {α : Type u} [preorder α] [no_bot_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (no_bot a) /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@dense α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃<a₁, a₃ ≤ a₂) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₃ ≤ a₂) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a₂ ≤ a) ∧ (∀a<a₂, a ≤ a₁)) := or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ variables {s : β → β → Prop} {t : γ → γ → Prop} /-- Any `linear_order` is a noncomputable `decidable_linear_order`. This is not marked as an instance to avoid a loop. -/ noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } /-- Type synonym to create an instance of `linear_order` from a `partial_order` and `[is_total α (≤)]` -/ def as_linear_order (α : Type u) := α instance {α} [inhabited α] : inhabited (as_linear_order α) := ⟨ (default α : α) ⟩ instance as_linear_order.linear_order {α} [partial_order α] [is_total α (≤)] : linear_order (as_linear_order α) := { le_total := @total_of α (≤) _, .. (_ : partial_order α) }
633b79b3bcf4fe080f923bfa862e8d8e0d0c0c3b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/quiver/push.lean
ee82a7c6ecd3e50e9b5ce62611e4752f3c80f190
[ "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,677
lean
/- Copyright (c) 2022 Rémi Bottinelli. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémi Bottinelli -/ import combinatorics.quiver.basic /-! # Pushing a quiver structure along a map > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a map `σ : V → W` and a `quiver` instance on `V`, this files defines a `quiver` instance on `W` by associating to each arrow `v ⟶ v'` in `V` an arrow `σ v ⟶ σ v'` in `W`. -/ universes v v₁ v₂ u u₁ u₂ variables {V : Type*} [quiver V] {W : Type*} (σ : V → W) namespace quiver /-- The `quiver` instance obtained by pushing arrows of `V` along the map `σ : V → W` -/ @[nolint unused_arguments] def push (σ : V → W) := W instance [h : nonempty W] : nonempty (push σ) := h /-- The quiver structure obtained by pushing arrows of `V` along the map `σ : V → W` -/ @[nolint has_nonempty_instance] inductive push_quiver {V : Type u} [quiver.{v} V] {W : Type u₂} (σ : V → W) : W → W → Type (max u u₂ v) | arrow {X Y : V} (f : X ⟶ Y) : push_quiver (σ X) (σ Y) instance : quiver (push σ) := ⟨push_quiver σ⟩ namespace push /-- The prefunctor induced by pushing arrows via `σ` -/ def of : V ⥤q push σ := { obj := σ, map := λ X Y f, push_quiver.arrow f } @[simp] lemma of_obj : (of σ).obj = σ := rfl variables {W' : Type*} [quiver W'] (φ : V ⥤q W') (τ : W → W') (h : ∀ x, φ.obj x = τ (σ x) ) include φ h /-- Given a function `τ : W → W'` and a prefunctor `φ : V ⥤q W'`, one can extend `τ` to be a prefunctor `W ⥤q W'` if `τ` and `σ` factorize `φ` at the level of objects, where `W` is given the pushforward quiver structure `push σ`. -/ def lift : push σ ⥤q W' := { obj := τ, map := @push_quiver.rec V _ W σ (λ X Y f, τ X ⟶ τ Y) (λ X Y f, by { rw [←h X, ←h Y], exact φ.map f, }) } lemma lift_obj : (lift σ φ τ h).obj = τ := rfl lemma lift_comp : of σ ⋙q lift σ φ τ h = φ := begin fapply prefunctor.ext, { rintros, simp only [prefunctor.comp_obj], symmetry, exact h X, }, { rintros _ _ f, simp only [prefunctor.comp_map], apply eq_of_heq, iterate 2 { apply (cast_heq _ _).trans }, symmetry, iterate 2 { apply (eq_rec_heq _ _).trans }, refl, }, end lemma lift_unique (Φ : push σ ⥤q W') (Φ₀ : Φ.obj = τ) (Φcomp : of σ ⋙q Φ = φ) : Φ = lift σ φ τ h := begin dsimp only [of,lift], fapply prefunctor.ext, { rintros, simp_rw [←Φ₀], }, { rintros _ _ ⟨⟩, subst_vars, simp only [prefunctor.comp_map, cast_eq], refl, } end end push end quiver
f7d6d2f884bbadf08d1b04239f29623d8a261364
5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61
/values.lean
a6ca09b3f4da3e9d6b72ff2ba05c1c5208b5f5a6
[]
no_license
mbrodersen/kremlin
f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec
d4665929ce9012e93a0b05fc7063b96256bab86f
refs/heads/master
1,624,057,268,130
1,496,957,084,000
1,496,957,084,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,369
lean
/- This module defines the type of values that is used in the dynamic semantics of all our intermediate languages. -/ import .lib .integers .floats .ast namespace values open integers word floats ast ast.typ ast.memory_chunk def block : Type := pos_num instance eq_block : decidable_eq block := by tactic.mk_dec_eq_instance instance coe_block : has_coe block ℕ := ⟨λp, num.pos p⟩ instance dlo_block : decidable_linear_order block := pos_num.decidable_linear_order instance block_one : has_one block := ⟨(1 : pos_num)⟩ /- A value is either: - a machine integer; - a floating-point number; - a pointer: a pair of a memory address and an integer offset with respect to this address; - the [Vundef] value denoting an arbitrary bit pattern, such as the value of an uninitialized variable. -/ inductive val : Type | Vundef : val | Vint : int32 → val | Vlong : int64 → val | Vfloat : float → val | Vsingle : float32 → val | Vptr : block → ptrofs → val export val instance coe_int32_val : has_coe int32 val := ⟨Vint⟩ instance coe_int64_val : has_coe int64 val := ⟨Vlong⟩ instance coe_Int32_val : has_coe (@word W32) val := ⟨Vint⟩ instance coe_Int64_val : has_coe (@word W64) val := ⟨Vlong⟩ instance coe_float_val : has_coe float val := ⟨Vfloat⟩ instance coe_single_val : has_coe float32 val := ⟨Vsingle⟩ instance inhabited_val : inhabited val := ⟨Vundef⟩ def Vzero : val := Vint 0 def Vone : val := Vint 1 def Vmone : val := Vint (-1) instance val_zero : has_zero val := ⟨Vzero⟩ instance val_one : has_one val := ⟨Vone⟩ def Vtrue : val := 1 def Vfalse : val := 0 def Vnullptr := if archi.ptr64 then Vlong 0 else Vint 0 def Vptrofs (n : ptrofs) : val := if archi.ptr64 then ptrofs.to_int64 n else ptrofs.to_int n /- * Operations over values -/ /- The module [val] defines a number of arithmetic and logical operations over type [val]. Most of these operations are straightforward extensions of the corresponding integer or floating-point operations. -/ namespace val instance val_eq : decidable_eq val := by tactic.mk_dec_eq_instance def has_type : val → typ → Prop | Vundef _ := true | (Vint _) Tint := true | (Vlong _) Tlong := true | (Vfloat _) Tfloat := true | (Vsingle _) Tsingle := true | (Vptr _ _) Tint := ¬ archi.ptr64 | (Vptr _ _) Tlong := archi.ptr64 | (Vint _) Tany32 := true | (Vsingle _) Tany32 := true | (Vptr _ _) Tany32 := ¬ archi.ptr64 | _ Tany64 := true | _ _ := false def has_type_list : list val → list typ → Prop | [] [] := true | (v1 :: vs) (t1 :: ts) := has_type v1 t1 ∧ has_type_list vs ts | _ _ := false def has_opttype (v : val) : option typ → Prop | none := v = Vundef | (some t) := has_type v t lemma Vptr_has_type (b ofs) : has_type (Vptr b ofs) Tptr := begin delta Tptr, ginduction archi.ptr64 with h, { intro h2, note := h.symm.trans h2, contradiction }, { exact h } end lemma Vnullptr_has_type : has_type Vnullptr Tptr := by delta Tptr Vnullptr; cases archi.ptr64; trivial lemma has_subtype (ty1 ty2 v) : subtype ty1 ty2 → has_type v ty1 → has_type v ty2 := sorry' lemma has_subtype_list (tyl1 tyl2 vl) : subtype_list tyl1 tyl2 → has_type_list vl tyl1 → has_type_list vl tyl2 := sorry' /- Truth values. Non-zero integers are treated as [True]. The integer 0 (also used to represent the null pointer) is [False]. Other values are neither true nor false. -/ def to_bool : val → option bool | (Vint n) := some (n ≠ 0) | _ := none /- Arithmetic operations -/ protected def neg : val → val | (Vint n) := word.neg n | _ := Vundef instance : has_neg val := ⟨val.neg⟩ def negf : val → val | (Vfloat f) := float.neg f | _ := Vundef def absf : val → val | (Vfloat f) := float.abs f | _ := Vundef def negfs : val → val | (Vsingle f) := float32.neg f | _ := Vundef def absfs : val → val | (Vsingle f) := float32.abs f | _ := Vundef def make_total (ov : option val) : val := ov.get_or_else Vundef def int_of_float : val → option val | (Vfloat f) := Vint <$> float.to_int f | _ := none def intu_of_float : val → option val | (Vfloat f) := Vint <$> float.to_intu f | _ := none def float_of_int : val → option val | (Vint n) := float.of_int n | _ := none def float_of_intu : val → option val | (Vint n) := float.of_intu n | _ := none def int_of_single : val → option val | (Vsingle f) := Vint <$> float32.to_int f | _ := none def intu_of_single : val → option val | (Vsingle f) := Vint <$> float32.to_intu f | _ := none def single_of_int : val → option val | (Vint n) := float32.of_int n | _ := none def single_of_intu : val → option val | (Vint n) := float32.of_intu n | _ := none def negint : val → val | (Vint n) := word.neg n | _ := Vundef def notint : val → val | (Vint n) := word.not n | _ := Vundef def of_bool (b : bool) : val := if b then Vtrue else Vfalse instance : has_coe bool val := ⟨of_bool⟩ def boolval : val → val | (Vint n) := of_bool (n ≠ 0) | (Vptr b ofs) := Vtrue | _ := Vundef def notbool : val → val | (Vint n) := of_bool (n = 0) | (Vptr b ofs) := Vfalse | _ := Vundef def zero_ext (nbits : ℕ) : val → val | (Vint n) := word.zero_ext nbits n | _ := Vundef def sign_ext (nbits : ℕ+) : val → val | (Vint n) := word.sign_ext nbits n | _ := Vundef def single_of_float : val → val | (Vfloat f) := float.to_single f | _ := Vundef def float_of_single : val → val | (Vsingle f) := float.of_single f | _ := Vundef protected def add : val → val → val | (Vint m) (Vint n) := Vint $ m + n | (Vptr b1 ofs1) (Vint n) := if archi.ptr64 then Vundef else Vptr b1 (ofs1 + ptrofs.of_int n) | (Vint m) (Vptr b2 ofs2) := if archi.ptr64 then Vundef else Vptr b2 (ofs2 + ptrofs.of_int m) | _ _ := Vundef instance : has_add val := ⟨val.add⟩ protected def sub : val → val → val | (Vint m) (Vint n) := Vint $ m - n | (Vptr b1 ofs1) (Vint n) := if archi.ptr64 then Vundef else Vptr b1 (ofs1 - ptrofs.of_int n) | (Vptr b1 ofs1) (Vptr b2 ofs2) := if archi.ptr64 ∨ b1 ≠ b2 then Vundef else ptrofs.to_int (ofs1 - ofs2) | _ _ := Vundef instance : has_sub val := ⟨val.sub⟩ protected def mul : val → val → val | (Vint m) (Vint n) := Vint (m * n) | _ _ := Vundef instance : has_mul val := ⟨val.mul⟩ def mulhs : val → val → val | (Vint m) (Vint n) := word.mulhs m n | _ _ := Vundef def mulhu : val → val → val | (Vint m) (Vint n) := word.mulhu m n | _ _ := Vundef def divs : val → val → option val | (Vint m) (Vint n) := if n = 0 ∨ m = repr (word.min_signed W32) ∧ n = -1 then none else some (m / n : word _) | _ _ := none def mods : val → val → option val | (Vint m) (Vint n) := if n = 0 ∨ m = repr (@min_signed W32) ∧ n = -1 then none else some (m % n : word _) | _ _ := none def divu : val → val → option val | (Vint m) (Vint n) := if n = 0 then none else word.divu m n | _ _ := none def modu : val → val → option val | (Vint m) (Vint n) := if n = 0 then none else word.modu m n | _ _ := none def add_carry : val → val → val → val | (Vint m) (Vint n) (Vint c) := word.add_carry m n c | _ _ _ := Vundef def sub_overflow : val → val → val | (Vint m) (Vint n) := word.sub_overflow m n 0 | _ _ := Vundef def negative : val → val | (Vint n) := word.negative n | _ := Vundef protected def and : val → val → val | (Vint m) (Vint n) := word.and m n | _ _ := Vundef protected def or : val → val → val | (Vint m) (Vint n) := word.or m n | _ _ := Vundef protected def xor : val → val → val | (Vint m) (Vint n) := word.xor m n | _ _ := Vundef def shl : val → val → val | (Vint m) (Vint n) := if word.ltu n iwordsize then word.shl m n else Vundef | _ _ := Vundef def shr : val → val → val | (Vint m) (Vint n) := if word.ltu n iwordsize then word.shr m n else Vundef | _ _ := Vundef def shr_carry : val → val → val | (Vint m) (Vint n) := if word.ltu n iwordsize then word.shr_carry m n else Vundef | _ _ := Vundef def shrx : val → val → option val | (Vint m) (Vint n) := if word.ltu n (repr 31) then word.shrx m n else none | _ _ := none def shru : val → val → val | (Vint m) (Vint n) := if word.ltu n iwordsize then word.shru m n else Vundef | _ _ := Vundef def rol : val → val → val | (Vint m) (Vint n) := word.rol m n | _ _ := Vundef def rolm : val → int32 → int32 → val | (Vint n) amount mask := word.rolm n amount mask | _ amount mask := Vundef def ror : val → val → val | (Vint m) (Vint n) := word.ror m n | _ _ := Vundef def addf : val → val → val | (Vfloat x) (Vfloat y) := Vfloat $ x + y | _ _ := Vundef def subf : val → val → val | (Vfloat x) (Vfloat y) := Vfloat $ x - y | _ _ := Vundef def mulf : val → val → val | (Vfloat x) (Vfloat y) := Vfloat $ x * y | _ _ := Vundef def divf : val → val → val | (Vfloat x) (Vfloat y) := Vfloat $ x / y | _ _ := Vundef def float_of_words : val → val → val | (Vint m) (Vint n) := float.from_words m n | _ _ := Vundef def addfs : val → val → val | (Vsingle x) (Vsingle y) := float32.add x y | _ _ := Vundef def subfs : val → val → val | (Vsingle x) (Vsingle y) := float32.sub x y | _ _ := Vundef def mulfs : val → val → val | (Vsingle x) (Vsingle y) := float32.mul x y | _ _ := Vundef def divfs : val → val → val | (Vsingle x) (Vsingle y) := float32.div x y | _ _ := Vundef /- Operations on 64-bit integers -/ def long_of_words : val → val → val | (Vint m) (Vint n) := int64.ofwords m n | _ _ := Vundef def loword : val → val | (Vlong n) := int64.loword n | _ := Vundef def hiword : val → val | (Vlong n) := int64.hiword n | _ := Vundef def negl : val → val | (Vlong n) := Vlong $ -n | _ := Vundef def notl : val → val | (Vlong n) := word.not n | _ := Vundef def long_of_int : val → val | (Vint n) := Vlong $ scoe n | _ := Vundef def long_of_intu : val → val | (Vint n) := Vlong $ ucoe n | _ := Vundef def long_of_float : val → option val | (Vfloat f) := Vlong <$> float.to_long f | _ := none def longu_of_float : val → option val | (Vfloat f) := Vlong <$> float.to_longu f | _ := none def long_of_single : val → option val | (Vsingle f) := Vlong <$> float32.to_long f | _ := none def longu_of_single : val → option val | (Vsingle f) := Vlong <$> float32.to_longu f | _ := none def float_of_long : val → option val | (Vlong n) := float.of_long n | _ := none def float_of_longu : val → option val | (Vlong n) := float.of_longu n | _ := none def single_of_long : val → option val | (Vlong n) := float32.of_long n | _ := none def single_of_longu : val → option val | (Vlong n) := float32.of_longu n | _ := none def addl : val → val → val | (Vlong n1) (Vlong n2) := Vlong (n1 + n2) | (Vptr b1 ofs1) (Vlong n2) := if archi.ptr64 then Vptr b1 (ofs1 + ptrofs.of_int64 n2) else Vundef | (Vlong n1) (Vptr b2 ofs2) := if archi.ptr64 then Vptr b2 (ofs2 + ptrofs.of_int64 n1) else Vundef | _ _ := Vundef def subl : val → val → val | (Vlong n1) (Vlong n2) := Vlong (n1 - n2) | (Vptr b1 ofs1) (Vlong n2) := if archi.ptr64 then Vptr b1 (ofs1 - ptrofs.of_int64 n2) else Vundef | (Vptr b1 ofs1) (Vptr b2 ofs2) := if archi.ptr64 ∨ b1 ≠ b2 then Vundef else ptrofs.to_int64 (ofs1 - ofs2) | _ _ := Vundef def mull : val → val → val | (Vlong m) (Vlong n) := Vlong (m * n) | _ _ := Vundef def mull' : val → val → val | (Vint m) (Vint n) := Vlong (ucoe m * ucoe n) | _ _ := Vundef def mullhs : val → val → val | (Vlong m) (Vlong n) := word.mulhs m n | _ _ := Vundef def mullhu : val → val → val | (Vlong m) (Vlong n) := word.mulhu m n | _ _ := Vundef def divls : val → val → option val | (Vlong m) (Vlong n) := if n = 0 ∨ m = repr (min_signed 64) ∧ n = -1 then none else some (m / n : word _) | _ _ := none def modls : val → val → option val | (Vlong m) (Vlong n) := if n = 0 ∨ m = repr (min_signed 64) ∧ n = -1 then none else some (m % n : word _) | _ _ := none def divlu : val → val → option val | (Vlong m) (Vlong n) := if n = 0 then none else word.divu m n | _ _ := none def modlu : val → val → option val | (Vlong m) (Vlong n) := if n = 0 then none else word.modu m n | _ _ := none def subl_overflow : val → val → val | (Vlong m) (Vlong n) := Vint $ ucoe $ word.sub_overflow m n 0 | _ _ := Vundef def negativel : val → val | (Vlong n) := Vint $ ucoe $ word.negative n | _ := Vundef def andl : val → val → val | (Vlong m) (Vlong n) := word.and m n | _ _ := Vundef def orl : val → val → val | (Vlong m) (Vlong n) := word.or m n | _ _ := Vundef def xorl : val → val → val | (Vlong m) (Vlong n) := word.xor m n | _ _ := Vundef def shll : val → val → val | (Vlong m) (Vint n) := if word.ltu n 64 then word.shl m (ucoe n) else Vundef | _ _ := Vundef def shrl : val → val → val | (Vlong m) (Vint n) := if word.ltu n 64 then word.shr m (ucoe n) else Vundef | _ _ := Vundef def shrlu : val → val → val | (Vlong m) (Vint n) := if word.ltu n 64 then word.shru m (ucoe n) else Vundef | _ _ := Vundef def shrxl : val → val → option val | (Vlong m) (Vint n) := if word.ltu n 63 then word.shrx m (ucoe n) else none | _ _ := none def roll : val → val → val | (Vlong m) (Vint n) := word.rol m (ucoe n) | _ _ := Vundef def rorl : val → val → val | (Vlong m) (Vint n) := word.ror m (ucoe n) | _ _ := Vundef def rolml : val → int64 → int64 → val | (Vlong n) amount mask := word.rolm n amount mask | _ amount mask := Vundef /- Comparisons -/ section comparisons parameter valid_ptr : block → ℕ → bool def weak_valid_ptr (b : block) (ofs : ℕ) := valid_ptr b ofs || valid_ptr b (ofs - 1) def cmp_bool (c : comparison) : val → val → option bool | (Vint m) (Vint n) := cmp c m n | _ _ := none def cmp_different_blocks : comparison → option bool | Ceq := some ff | Cne := some tt | _ := none def cmpu_bool (c : comparison) : val → val → option bool | (Vint m) (Vint n) := some $ cmpu c m n | (Vint m) (Vptr b2 ofs2) := if archi.ptr64 then none else if m = 0 ∧ weak_valid_ptr b2 (unsigned ofs2) then cmp_different_blocks c else none | (Vptr b1 ofs1) (Vptr b2 ofs2) := if archi.ptr64 then none else if b1 = b2 then if weak_valid_ptr b1 (unsigned ofs1) ∧ weak_valid_ptr b2 (unsigned ofs2) then cmpu c ofs1 ofs2 else none else if valid_ptr b1 (unsigned ofs1) ∧ valid_ptr b2 (unsigned ofs2) then cmp_different_blocks c else none | (Vptr b1 ofs1) (Vint n) := if archi.ptr64 then none else if n = 0 ∧ weak_valid_ptr b1 (unsigned ofs1) then cmp_different_blocks c else none | _ _ := none def cmpf_bool (c : comparison) : val → val → option bool | (Vfloat x) (Vfloat y) := float.cmp c x y | _ _ := none def cmpfs_bool (c : comparison) : val → val → option bool | (Vsingle x) (Vsingle y) := float32.cmp c x y | _ _ := none def cmpl_bool (c : comparison) : val → val → option bool | (Vlong m) (Vlong n) := cmp c m n | _ _ := none def cmplu_bool (c : comparison) : val → val → option bool | (Vlong n1) (Vlong n2) := some $ cmpu c n1 n2 | (Vlong n1) (Vptr b2 ofs2) := if archi.ptr64 ∧ n1 = 0 ∧ weak_valid_ptr b2 (unsigned ofs2) then cmp_different_blocks c else none | (Vptr b1 ofs1) (Vptr b2 ofs2) := if ¬ archi.ptr64 then none else if b1 = b2 then if weak_valid_ptr b1 (unsigned ofs1) && weak_valid_ptr b2 (unsigned ofs2) then some (cmpu c ofs1 ofs2) else none else if valid_ptr b1 (unsigned ofs1) && valid_ptr b2 (unsigned ofs2) then cmp_different_blocks c else none | (Vptr b1 ofs1) (Vlong n2) := if archi.ptr64 ∧ n2 = 0 ∧ weak_valid_ptr b1 (unsigned ofs1) then cmp_different_blocks c else none | _ _ := none def of_optbool : option bool → val | (some tt) := Vtrue | (some ff) := Vfalse | none := Vundef def cmp (c : comparison) (v1 v2 : val) : val := of_optbool $ cmp_bool c v1 v2 def cmpu (c : comparison) (v1 v2 : val) : val := of_optbool $ cmpu_bool c v1 v2 def cmpf (c : comparison) (v1 v2 : val) : val := of_optbool $ cmpf_bool c v1 v2 def cmpfs (c : comparison) (v1 v2 : val) : val := of_optbool $ cmpfs_bool c v1 v2 def cmpl (c : comparison) (v1 v2 : val) : option val := of_bool <$> cmpl_bool c v1 v2 def cmplu (c : comparison) (v1 v2 : val) : option val := of_bool <$> cmplu_bool c v1 v2 def maskzero_bool : val → int32 → option bool | (Vint n) mask := some $ word.and n mask = 0 | _ mask := none end comparisons /- Add the given offset to the given pointer. -/ def offset_ptr : val → ptrofs → val | (Vptr b ofs) delta := Vptr b (ofs + delta) | _ delta := Vundef /- [load_result] reflects the effect of storing a value with a given memory chunk, then reading it back with the same chunk. Depending on the chunk and the type of the value, some normalization occurs. For instance, consider storing the integer value [0xFFF] on 1 byte at a given address, and reading it back. If it is read back with chunk [Mint8unsigned], zero-extension must be performed, resulting in [0xFF]. If it is read back as a [Mint8signed], sign-extension is performed and [0xFFFFFFFF] is returned. -/ def load_result : memory_chunk → val → val | Mint8signed (Vint n) := word.sign_ext W8 n | Mint8unsigned (Vint n) := word.zero_ext 8 n | Mint16signed (Vint n) := word.sign_ext W16 n | Mint16unsigned (Vint n) := word.zero_ext 16 n | Mint32 (Vint n) := Vint n | Mint32 (Vptr b ofs) := if archi.ptr64 then Vundef else Vptr b ofs | Mint64 (Vlong n) := Vlong n | Mint64 (Vptr b ofs) := if archi.ptr64 then Vptr b ofs else Vundef | Mfloat32 (Vsingle f) := Vsingle f | Mfloat64 (Vfloat f) := Vfloat f | Many32 (Vint n) := Vint n | Many32 (Vsingle f) := Vsingle f | Many32 (Vptr b ofs) := if archi.ptr64 then Vundef else Vptr b ofs | Many64 v := v | _ _ := Vundef lemma load_result_type (chunk v) : has_type (load_result chunk v) chunk.type := sorry' lemma load_result_same {v ty} : has_type v ty → load_result (chunk_of_type ty) v = v := sorry' /- Theorems on arithmetic operations. -/ theorem cast8unsigned_and (x) : zero_ext 8 x = val.and x (0xFF : int32) := sorry' theorem cast16unsigned_and (x) : zero_ext 16 x = val.and x (0xFFFF : int32) := sorry' theorem to_bool_of_bool (b1 b2) : (of_bool b1).to_bool = some b2 → b1 = b2 := sorry' theorem to_bool_of_optbool (ob) : (of_optbool ob).to_bool = ob := sorry' theorem notbool_negb_1 (b) : of_bool (bnot b) = notbool (of_bool b) := sorry' theorem notbool_negb_2 (b) : of_bool b = notbool (of_bool (bnot b)) := sorry' theorem notbool_negb_3 (ob) : of_optbool (bnot <$> ob) = notbool (of_optbool ob) := sorry' set_option type_context.unfold_lemmas true theorem notbool_idem2 (b) : notbool (notbool (of_bool b)) = of_bool b := by cases b; refl theorem notbool_idem3 (x) : notbool (notbool (notbool x)) = notbool x := sorry' theorem notbool_idem4 (ob) : notbool (notbool (of_optbool ob)) = of_optbool ob := sorry' theorem add_comm (x y : val) : x + y = y + x := sorry' theorem add_assoc (x y z : val) : (x + y) + z = x + (y + z) := sorry' theorem neg_zero : (-0 : val) = 0 := sorry' theorem neg_add (x y : val) : -(x + y) = -x + -y := sorry' theorem zero_sub (x : val) : 0 - x = -x := sorry' theorem sub_eq_add_neg (x y) : x - Vint y = x + Vint (-y) := sorry' theorem sub_neg_eq_add (x y) : x - Vint (-y) = x + Vint y := sorry' theorem sub_add_eq_add_sub (v1 v2 i) : v1 + Vint i - v2 = v1 - v2 + Vint i := sorry' theorem sub_add_eq_sub_add_neg (v1 v2 i) : v1 - (v2 + Vint i) = v1 - v2 + Vint (-i) := sorry' theorem mul_comm (x y : val) : x * y = y * x := sorry' theorem mul_assoc (x y z : val) : (x * y) * z = x * (y * z) := sorry' theorem right_distrib (x y z : val) : (x + y) * z = x * z + y * z := sorry' theorem left_distrib (x y z : val) : x * (y + z) = x * y + x * z := sorry' theorem mul_pow2 (x n logn) : is_power2 n = some logn → x * Vint n = shl x (Vint logn) := sorry' theorem mods_divs (x y z) : mods x y = some z → ∃ v, divs x y = some v ∧ z = x - v * y := sorry' theorem modu_divu (x y z) : modu x y = some z → ∃ v, divu x y = some v ∧ z = x - v * y := sorry' theorem divs_pow2 (x n logn y) : is_power2 n = some logn → word.ltu logn 31 → divs x (Vint n) = some y → shrx x (Vint logn) = some y := sorry' theorem divu_pow2 (x n logn y) : is_power2 n = some logn → divu x (Vint n) = some y → shru x (Vint logn) = y := sorry' theorem modu_pow2 (x n logn y) : is_power2 n = some logn → modu x (Vint n) = some y → val.and x (Vint (n - 1)) = y := sorry' theorem and_comm (x y) : val.and x y = val.and y x := sorry' theorem and_assoc (x y z) : val.and (val.and x y) z = val.and x (val.and y z) := sorry' theorem or_comm (x y) : val.or x y = val.or y x := sorry' theorem or_assoc (x y z) : val.or (val.or x y) z = val.or x (val.or y z) := sorry' theorem xor_commut (x y) : val.xor x y = val.xor y x := sorry' theorem xor_assoc (x y z) : val.xor (val.xor x y) z = val.xor x (val.xor y z) := sorry' theorem not_xor (x) : notint x = val.xor x (Vint (-1)) := sorry' theorem shl_rolm (x n) : word.ltu n 32 → shl x (Vint n) = rolm x n (word.shl (-1) n) := sorry' theorem shru_rolm (x n) : word.ltu n 32 → shru x (Vint n) = rolm x (32 - n) (word.shru (-1) n) := sorry' theorem shrx_carry (x y z) : shrx x y = some z → shr x y + shr_carry x y = z := sorry' theorem shrx_shr (x y z) : shrx x y = some z → ∃ p, ∃ q, x = Vint p ∧ y = Vint q ∧ z = shr (if p < 0 then x + Vint (word.shl 1 q - 1) else x) (Vint q) := sorry' theorem shrx_shr_2 (n x z) : shrx x (Vint n) = some z → z = if n = 0 then x else shr (x + shru (shr x 31) (Vint (32 - n))) (Vint n) := sorry' theorem or_rolm (x n m1 m2) : val.or (rolm x n m1) (rolm x n m2) = rolm x n (word.or m1 m2) := sorry' theorem rolm_rolm (x n1 m1 n2 m2) : rolm (rolm x n1 m1) n2 m2 = rolm x (word.modu (n1 + n2) 32) (word.and (word.rol m1 n2) m2) := sorry' theorem rolm_zero (x m) : rolm x 0 m = val.and x (Vint m) := sorry' theorem addl_comm (x y) : addl x y = addl y x := sorry' theorem addl_assoc (x y z) : addl (addl x y) z = addl x (addl y z) := sorry' theorem negl_addl_distr (x y) : negl (addl x y) = addl (negl x) (negl y) := sorry' theorem subl_addl_opp (x y) : subl x (Vlong y) = addl x (Vlong (-y)) := sorry' theorem subl_opp_addl : ∀ x y, subl x (Vlong (-y)) = addl x (Vlong y) := sorry' theorem subl_addl_l (v1 v2 i) : subl (addl v1 (Vlong i)) v2 = addl (subl v1 v2) (Vlong i) := sorry' theorem subl_addl_r (v1 v2 i) : subl v1 (addl v2 (Vlong i)) = addl (subl v1 v2) (Vlong (-i)) := sorry' theorem mull_comm (x y) : mull x y = mull y x := sorry' theorem mull_assoc (x y z) : mull (mull x y) z = mull x (mull y z) := sorry' theorem mull_addl_distr_l (x y z) : mull (addl x y) z = addl (mull x z) (mull y z) := sorry' theorem mull_addl_distr_r (x y z) : mull x (addl y z) = addl (mull x y) (mull x z) := sorry' theorem andl_comm (x y) : andl x y = andl y x := sorry' theorem andl_assoc (x y z) : andl (andl x y) z = andl x (andl y z) := sorry' theorem orl_comm (x y) : orl x y = orl y x := sorry' theorem orl_assoc (x y z) : orl (orl x y) z = orl x (orl y z) := sorry' theorem xorl_commut (x y) : xorl x y = xorl y x := sorry' theorem xorl_assoc (x y z) : xorl (xorl x y) z = xorl x (xorl y z) := sorry' theorem notl_xorl (x) : notl x = xorl x (Vlong (-1)) := sorry' theorem divls_pow2 (x n logn y) : int64.is_power2 n = some logn → word.ltu logn 63 → divls x (Vlong n) = some y → shrxl x (Vint logn) = some y := sorry' theorem divlu_pow2 (x n logn y) : int64.is_power2 n = some logn → divlu x (Vlong n) = some y → shrlu x (Vint logn) = y := sorry' theorem modlu_pow2 (x n logn y) : int64.is_power2 n = some logn → modlu x (Vlong n) = some y → andl x (Vlong (n - 1)) = y := sorry' theorem shrxl_shrl_2 (n x z) : shrxl x (Vint n) = some z → z = if n = 0 then x else shrl (addl x (shrlu (shrl x (Vint 63)) (Vint (64 - n)))) (Vint n) := sorry' theorem negate_cmp_bool (c x y) : cmp_bool (negate_comparison c) x y = bnot <$> cmp_bool c x y := sorry' theorem negate_cmpu_bool (valid_ptr c x y) : cmpu_bool valid_ptr (negate_comparison c) x y = bnot <$> cmpu_bool valid_ptr c x y := sorry' theorem negate_cmpl_bool (c x y) : cmpl_bool (negate_comparison c) x y = bnot <$> cmpl_bool c x y := sorry' theorem negate_cmplu_bool (valid_ptr c x y) : cmplu_bool valid_ptr (negate_comparison c) x y = bnot <$> cmplu_bool valid_ptr c x y := sorry' lemma not_of_optbool (ob) : of_optbool (bnot <$> ob) = notbool (of_optbool ob) := sorry' theorem negate_cmp (c x y) : cmp (negate_comparison c) x y = notbool (cmp c x y) := sorry' theorem negate_cmpu (valid_ptr c x y) : cmpu valid_ptr (negate_comparison c) x y = notbool (cmpu valid_ptr c x y) := sorry' theorem swap_cmp_bool (c x y) : cmp_bool (swap_comparison c) x y = cmp_bool c y x := sorry' theorem swap_cmpu_bool (valid_ptr c x y) : cmpu_bool valid_ptr (swap_comparison c) x y = cmpu_bool valid_ptr c y x := sorry' theorem swap_cmpl_bool (c x y) : cmpl_bool (swap_comparison c) x y = cmpl_bool c y x := sorry' theorem swap_cmplu_bool (valid_ptr c x y) : cmplu_bool valid_ptr (swap_comparison c) x y = cmplu_bool valid_ptr c y x := sorry' theorem negate_cmpf_eq (v1 v2) : notbool (cmpf Cne v1 v2) = cmpf Ceq v1 v2 := sorry' theorem negate_cmpf_ne (v1 v2) : notbool (cmpf Ceq v1 v2) = cmpf Cne v1 v2 := sorry' theorem cmpf_le (v1 v2) : cmpf Cle v1 v2 = val.or (cmpf Clt v1 v2) (cmpf Ceq v1 v2) := sorry' theorem cmpf_ge (v1 v2) : cmpf Cge v1 v2 = val.or (cmpf Cgt v1 v2) (cmpf Ceq v1 v2) := sorry' theorem cmp_ne_0_optbool (ob) : cmp Cne (of_optbool ob) 0 = of_optbool ob := sorry' theorem cmp_eq_1_optbool (ob) : cmp Ceq (of_optbool ob) 1 = of_optbool ob := sorry' theorem cmp_eq_0_optbool (ob) : cmp Ceq (of_optbool ob) 0 = of_optbool (bnot <$> ob) := sorry' theorem cmp_ne_1_optbool (ob) : cmp Cne (of_optbool ob) 1 = of_optbool (bnot <$> ob) := sorry' theorem cmpu_ne_0_optbool (valid_ptr ob) : cmpu valid_ptr Cne (of_optbool ob) 0 = of_optbool ob := sorry' theorem cmpu_eq_1_optbool (valid_ptr ob) : cmpu valid_ptr Ceq (of_optbool ob) 1 = of_optbool ob := sorry' theorem cmpu_eq_0_optbool (valid_ptr ob) : cmpu valid_ptr Ceq (of_optbool ob) 0 = of_optbool (bnot <$> ob) := sorry' theorem cmpu_ne_1_optbool (valid_ptr ob) : cmpu valid_ptr Cne (of_optbool ob) 1 = of_optbool (bnot <$> ob) := sorry' lemma zero_ext_and (n v) : 0 < n → n < 32 → val.zero_ext n v = val.and v (Vint (repr (2^n - 1))) := sorry' lemma rolm_lt_zero (v) : rolm v 1 1 = cmp Clt v 0 := sorry' lemma rolm_ge_zero (v) : val.xor (rolm v 1 1) 1 = cmp Cge v 0 := sorry' /- The ``is less defined'' relation between values. A value is less defined than itself, and [Vundef] is less defined than any value. -/ inductive lessdef : val → val → Prop | refl (v) : lessdef v v | undef (v) : lessdef Vundef v lemma lessdef_of_eq : Π {v1 v2}, v1 = v2 → lessdef v1 v2 | v ._ rfl := lessdef.refl v lemma lessdef_trans {v1 v2 v3} : lessdef v1 v2 → lessdef v2 v3 → lessdef v1 v3 := by intros h1 h2; cases h1; try {assumption}; cases h2; assumption lemma lessdef_list_inv {vl1 vl2} : list.forall2 lessdef vl1 vl2 → vl1 = vl2 ∨ Vundef ∈ vl1 := sorry' lemma lessdef_list_trans {vl1 vl2 vl3} : list.forall2 lessdef vl1 vl2 → list.forall2 lessdef vl2 vl3 → list.forall2 lessdef vl1 vl3 := @list.forall2.trans _ _ @lessdef_trans _ _ _ /- Compatibility of operations with the [lessdef] relation. -/ lemma load_result_lessdef (chunk v1 v2) : lessdef v1 v2 → lessdef (load_result chunk v1) (load_result chunk v2) := sorry' lemma zero_ext_lessdef (n v1 v2) : lessdef v1 v2 → lessdef (zero_ext n v1) (zero_ext n v2) := sorry' lemma sign_ext_lessdef (n v1 v2) : lessdef v1 v2 → lessdef (sign_ext n v1) (sign_ext n v2) := sorry' lemma singleoffloat_lessdef (v1 v2) : lessdef v1 v2 → lessdef (single_of_float v1) (single_of_float v2) := sorry' lemma add_lessdef (v1 v1' v2 v2') : lessdef v1 v1' → lessdef v2 v2' → lessdef (v1 + v2) (v1' + v2') := sorry' lemma addl_lessdef (v1 v1' v2 v2') : lessdef v1 v1' → lessdef v2 v2' → lessdef (addl v1 v2) (addl v1' v2') := sorry' lemma cmpu_bool_lessdef {valid_ptr valid_ptr' : block → ℕ → bool} {c v1 v1' v2 v2' b} : (∀ b ofs, valid_ptr b ofs → valid_ptr' b ofs) → lessdef v1 v1' → lessdef v2 v2' → cmpu_bool valid_ptr c v1 v2 = some b → cmpu_bool valid_ptr' c v1' v2' = some b := sorry' lemma cmplu_bool_lessdef {valid_ptr valid_ptr' : block → ℕ → bool} {c v1 v1' v2 v2' b} : (∀ b ofs, valid_ptr b ofs → valid_ptr' b ofs) → lessdef v1 v1' → lessdef v2 v2' → cmplu_bool valid_ptr c v1 v2 = some b → cmplu_bool valid_ptr' c v1' v2' = some b := sorry' lemma of_optbool_lessdef {ob ob'} : (∀ b, ob = some b → ob' = some b) → lessdef (of_optbool ob) (of_optbool ob') := sorry' lemma long_of_words_lessdef {v1 v2 v1' v2'} : lessdef v1 v1' → lessdef v2 v2' → lessdef (long_of_words v1 v2) (long_of_words v1' v2') := sorry' lemma loword_lessdef {v v'} : lessdef v v' → lessdef (loword v) (loword v') := sorry' lemma hiword_lessdef {v v'} : lessdef v v' → lessdef (hiword v) (hiword v') := sorry' lemma offset_ptr_zero (v) : lessdef (offset_ptr v 0) v := sorry' lemma offset_ptr_assoc (v d1 d2) : offset_ptr (offset_ptr v d1) d2 = offset_ptr v (d1 + d2) := sorry' /- * Values and memory injections -/ /- A memory injection [f] is a function from addresses to either [none] or [some] of an address and an offset. It defines a correspondence between the blocks of two memory states [m1] and [m2]: - if [f b = none], the block [b] of [m1] has no equivalent in [m2]; - if [f b = some (b', ofs)], the block [b] of [m2] corresponds to a sub-block at offset [ofs] of the block [b'] in [m2]. -/ def meminj : Type := block → option (block × ℤ) /- A memory injection defines a relation between values that is the identity relation, except for pointer values which are shifted as prescribed by the memory injection. Moreover, [Vundef] values inject into any other value. -/ inductive inject (mi : meminj) : val → val → Prop | int (i) : inject (Vint i) (Vint i) | long (i) : inject (Vlong i) (Vlong i) | float (f) : inject (Vfloat f) (Vfloat f) | single (f) : inject (Vsingle f) (Vsingle f) | ptr (b1 ofs1 b2 ofs2 delta) : mi b1 = some (b2, delta) → (ofs2 : ptrofs) = ofs1 + repr delta → inject (Vptr b1 ofs1) (Vptr b2 ofs2) | undef (v) : inject Vundef v lemma inject_ptrofs (mi i) : inject mi (Vptrofs i) (Vptrofs i) := sorry' section val_inj_ops parameter f : meminj lemma load_result_inject (chunk v1 v2) : inject f v1 v2 → inject f (load_result chunk v1) (load_result chunk v2) := sorry' theorem add_inject {v1 v1' v2 v2'} : inject f v1 v1' → inject f v2 v2' → inject f (v1 + v2) (v1' + v2') := sorry' theorem sub_inject {v1 v1' v2 v2'} : inject f v1 v1' → inject f v2 v2' → inject f (v1 - v2) (v1' - v2') := sorry' theorem addl_inject {v1 v1' v2 v2'} : inject f v1 v1' → inject f v2 v2' → inject f (addl v1 v2) (addl v1' v2') := sorry' theorem subl_inject {v1 v1' v2 v2'} : inject f v1 v1' → inject f v2 v2' → inject f (subl v1 v2) (subl v1' v2') := sorry' lemma offset_ptr_inject {v v'} (ofs) : inject f v v' → inject f (offset_ptr v ofs) (offset_ptr v' ofs) := sorry' lemma cmp_bool_inject {c v1 v2 v1' v2' b} : inject f v1 v1' → inject f v2 v2' → cmp_bool c v1 v2 = some b → cmp_bool c v1' v2' = some b := sorry' parameters (valid_ptr1 valid_ptr2 : block → ℕ → bool) def weak_valid_ptr1 := weak_valid_ptr valid_ptr1 def weak_valid_ptr2 := weak_valid_ptr valid_ptr2 parameter valid_ptr_inj : ∀ b1 ofs b2 delta, f b1 = some (b2, delta) → valid_ptr1 b1 (unsigned (ofs : ptrofs)) → valid_ptr2 b2 (unsigned (ofs + repr delta)) parameter weak_valid_ptr_inj : ∀ b1 ofs b2 delta, f b1 = some (b2, delta) → weak_valid_ptr1 b1 (unsigned (ofs : ptrofs)) → weak_valid_ptr2 b2 (unsigned (ofs + repr delta)) parameter weak_valid_ptr_no_overflow : ∀ b1 ofs b2 delta, f b1 = some (b2, delta) → weak_valid_ptr1 b1 (unsigned (ofs : ptrofs)) → unsigned ofs + unsigned (repr delta : ptrofs) ≤ @max_unsigned ptrofs.wordsize parameter valid_different_ptrs_inj : ∀ b1 ofs1 b2 ofs2 b1' delta1 b2' delta2, b1 ≠ b2 → valid_ptr1 b1 (unsigned (ofs1 : ptrofs)) → valid_ptr1 b2 (unsigned (ofs2 : ptrofs)) → f b1 = some (b1', delta1) → f b2 = some (b2', delta2) → b1' = b2' → unsigned (ofs1 + repr delta1) ≠ unsigned (ofs2 + repr delta2) lemma cmpu_bool_inject {c v1 v2 v1' v2' b} : inject f v1 v1' → inject f v2 v2' → cmpu_bool valid_ptr1 c v1 v2 = some b → cmpu_bool valid_ptr2 c v1' v2' = some b := sorry' lemma cmplu_bool_inject {c v1 v2 v1' v2' b} : inject f v1 v1' → inject f v2 v2' → cmplu_bool valid_ptr1 c v1 v2 = some b → cmplu_bool valid_ptr2 c v1' v2' = some b := sorry' lemma long_of_words_inject {v1 v2 v1' v2'} : inject f v1 v1' → inject f v2 v2' → inject f (long_of_words v1 v2) (long_of_words v1' v2') := sorry' lemma loword_inject {v v'} : inject f v v' → inject f (loword v) (loword v') := sorry' lemma hiword_inject {v v'} : inject f v v' → inject f (hiword v) (hiword v') := sorry' end val_inj_ops end val export val (meminj) /- Monotone evolution of a memory injection. -/ def inject_incr (f1 f2 : meminj) : Prop := ∀ ⦃b b' delta⦄, f1 b = some (b', delta) → f2 b = some (b', delta) lemma inject_incr.refl (f) : inject_incr f f := λ _ _ _, id lemma inject_incr.trans {f1 f2 f3} (i1 : inject_incr f1 f2) (i2 : inject_incr f2 f3) : inject_incr f1 f3 := λ b b' d h, i2 (i1 h) lemma val_inject_incr {f1 f2 v v'} : inject_incr f1 f2 → inject f1 v v' → inject f2 v v' := sorry' lemma val_inject_list_incr {f1 f2 vl vl'} (i : inject_incr f1 f2) (il : list.forall2 (inject f1) vl vl') : list.forall2 (inject f2) vl vl' := il.imp (λ x y, val_inject_incr i) /- The identity injection gives rise to the "less defined than" relation. -/ def inject_id : meminj := λ b, some (b, 0) lemma val_inject_id {v1 v2} : inject inject_id v1 v2 ↔ val.lessdef v1 v2 := sorry' lemma val_inject_id_list {vl1 vl2} : list.forall2 (inject inject_id) vl1 vl2 ↔ list.forall2 val.lessdef vl1 vl2 := list.forall2.iff @val_inject_id /- Composing two memory injections -/ def val.meminj.comp (f f' : meminj) : meminj := λ b, do ⟨b', delta⟩ ← f b, ⟨b'', delta'⟩ ← f' b', return (b'', delta + delta') lemma inject.comp {f f' v1 v2 v3} : inject f v1 v2 → inject f' v2 v3 → inject (f.comp f') v1 v3 := sorry' end values
8a01beb426421c4e77e9b1cb8d47fc6542f24983
85da4f6a2a49be210b92bc39383b3c388ca0600d
/Compiler9000.lean
634b25c250c7b34709845ef89f7e8acbd332a8e8
[ "MIT" ]
permissive
RaitoBezarius/compiler9000
0bf69e073ba16bef02c93353067a7016c98a6a74
74194211838754b728f6b2420d1a6ae34180b09c
refs/heads/main
1,685,347,997,520
1,622,076,826,000
1,622,076,826,000
362,614,305
1
0
null
null
null
null
UTF-8
Lean
false
false
36,043
lean
import Lean open Classical -- For Core / standard library? def List.forall (p : α → Prop) := List.foldr (λ a b => p a ∧ b) True theorem List.forallCons (hd : α) (tl : List α) : List.forall p (hd :: tl) ↔ p hd ∧ List.forall p tl := by simp [List.forall, List.foldr] theorem Option.someOfNotNone {T: Type} (x: Option T): x ≠ none <-> ∃ t: T, x = some t := by apply Iff.intro intro notNone match x with | some u => exact ⟨u, by rfl⟩ | none => exact absurd notNone (by simp) intro hsome rw [hsome.2] exact Option.noConfusion theorem Nat.neOfLt {n m: Nat} (h: n < m): n ≠ m := by intro heq; rw [heq] at h exact Nat.ltIrrefl _ h theorem Nat.ltAddLeft {n m k: Nat} (h: n < m): n < k + m := by induction k with | zero => exact show n < 0 + m from (Nat.zero_add m).symm ▸ h | succ k h => exact succ_add k m ▸ leStep h theorem Nat.ltAddRight {n m k: Nat} (h: n < m): n < m + k := Nat.add_comm k m ▸ Nat.ltAddLeft h theorem Nat.ltMaxLeft {a b c: Nat}: a < b -> a < Nat.max b c := fun hab => by simp only [Nat.max] byCases hbc: b ≤ c rw [ifPos hbc]; exact Nat.ltOfLtOfLe hab hbc rw [ifNeg hbc]; exact hab theorem Nat.ltMaxRight {a b c: Nat}: a < c -> a < Nat.max b c := fun hac => by simp only [Nat.max] byCases hbc: b ≤ c rw [ifPos hbc]; exact hac rw [ifNeg hbc]; exact Nat.ltTrans hac (Nat.gtOfNotLe hbc) theorem Nat.succMaxEqMaxSucc {a b: Nat}: Nat.succ (Nat.max a b) = Nat.max (Nat.succ a) (Nat.succ b) := by simp [Nat.max]; byCases hab: a ≤ b focus byCases hsucc: succ a ≤ succ b rw [ifPos hab, ifPos hsucc] rw [ifNeg hsucc, ifNeg <| show ¬ a ≤ b from λ h => hsucc <| succLeSucc h] focus byCases hsucc: succ a ≤ succ b rw [ifPos hsucc, ifPos <| leOfSuccLeSucc hsucc] rw [ifNeg hab, ifNeg hsucc] theorem Nat.ltSuccMaxLeft {a b: Nat}: a < Nat.succ (Nat.max a b) := by rw [succMaxEqMaxSucc]; exact ltMaxLeft (lt.base _) theorem Nat.ltSuccMaxRight {a b: Nat}: b < Nat.succ (Nat.max a b) := by rw [succMaxEqMaxSucc]; exact ltMaxRight (lt.base _) theorem List.lengthMap (f : α → β) (l : List α) : List.length (List.map f l) = List.length l := by induction l with | nil => simp [length, lengthAux] | cons hd tl h_tl => simp [map, length_cons, h_tl] inductive LambdaTerm where | var (val : Nat) | app (fn: LambdaTerm) (arg: LambdaTerm) | lambda (body: LambdaTerm) deriving Inhabited -- Q1.2 def allFreeVariablesBoundBy (n: Nat) (t: LambdaTerm): Prop := aux n t 0 where aux n t depth : Prop := match t with | LambdaTerm.var (val := m) => m < n + depth | LambdaTerm.app (fn := fn) (arg := arg) => aux n fn depth ∧ aux n arg depth | LambdaTerm.lambda (body := fn) => aux n fn (depth + 1) theorem allFreeVariablesBoundBy.auxRec (t: LambdaTerm): ∀ n d: Nat, (allFreeVariablesBoundBy.aux n t d -> allFreeVariablesBoundBy.aux (n + 1) t d) := fun n d hn => by induction t generalizing d with | var m => apply Nat.ltTrans hn (Nat.addLtAddRight (Nat.lt.base _) _) | app fn arg h_fn h_arg => exact ⟨ h_fn _ hn.1, h_arg _ hn.2 ⟩ | lambda body h_body => exact h_body _ hn theorem allFreeVariablesBoundBy.auxRec₂ {t: LambdaTerm}: ∀ {n d: Nat}, (allFreeVariablesBoundBy.aux (n + 1) t d <-> allFreeVariablesBoundBy.aux n t (d + 1)) := by intro n d; induction t generalizing d with | var v => simp only [aux] rw [Nat.add_assoc, Nat.add_comm 1 d] exact Iff.rfl | app fn arg h_fn h_arg => exact Iff.intro (fun H => ⟨ h_fn.1 H.1, h_arg.1 H.2 ⟩) (fun H => ⟨ h_fn.2 H.1, h_arg.2 H.2 ⟩) | lambda body h_body => exact Iff.intro (fun H => (@h_body (d + 1)).1 H) (fun H => (@h_body (d + 1)).2 H) theorem allFreeVariablesBoundBy.lambda {t: LambdaTerm}: ∀ {n: Nat}, allFreeVariablesBoundBy n (LambdaTerm.lambda t) -> allFreeVariablesBoundBy (n + 1) t := by intro n hn; exact allFreeVariablesBoundBy.auxRec₂.2 hn macro "C[" n:term "](" t:term ")" : term => `(allFreeVariablesBoundBy $n $t) def isClosedTerm (t: LambdaTerm): Prop := C[0](t) theorem boundedByFollowing (m : Nat) (h : C[n](t)) : C[n + m](t) := by induction m with | zero => assumption | succ m ih => match t with | LambdaTerm.var (val := p) => exact allFreeVariablesBoundBy.auxRec _ _ _ ih | LambdaTerm.app (fn := fn) (arg := arg) => exact ⟨ allFreeVariablesBoundBy.auxRec _ _ _ ih.1, allFreeVariablesBoundBy.auxRec _ _ _ ih.2 ⟩ | LambdaTerm.lambda (body := fn) => exact allFreeVariablesBoundBy.auxRec _ _ _ ih theorem boundByGreater (greater : n ≤ m) (h : C[n](t)) : C[m](t) := by match Nat.le.dest greater with | ⟨ w, hw ⟩ => rw [← hw] exact boundedByFollowing w h theorem isClosedTerm.FVBoundness (t: LambdaTerm) (h: isClosedTerm t): ∀ n: Nat, C[n](t) := fun n => by induction n with | zero => assumption | succ m ih => match t with | LambdaTerm.var (val := p) => exact allFreeVariablesBoundBy.auxRec _ _ _ ih | LambdaTerm.app (fn := fn) (arg := arg) => exact ⟨ allFreeVariablesBoundBy.auxRec _ _ _ ih.1, allFreeVariablesBoundBy.auxRec _ _ _ ih.2 ⟩ | LambdaTerm.lambda (body := fn) => exact allFreeVariablesBoundBy.auxRec _ _ _ ih -- Q1.3 def substitute (t: LambdaTerm) (index: Nat) (expr: LambdaTerm): LambdaTerm := aux index t 0 where aux i t depth : LambdaTerm := match t with | LambdaTerm.var (val := m) => if i + depth = m then expr else t | LambdaTerm.app fn arg => LambdaTerm.app (aux i fn depth) (aux i arg depth) | LambdaTerm.lambda body => LambdaTerm.lambda (aux i body (depth + 1)) theorem substitute.idOnClosed (depth: Nat) (t: LambdaTerm) (ht: C[depth](t)) (index: Nat) (expr: LambdaTerm) (hexpr: isClosedTerm expr): substitute.aux expr index t depth = t := by induction t generalizing depth with | var m => have neg: index + depth ≠ m := (Nat.neOfLt $ Nat.ltAddLeft ht).symm; simp [aux, neg]; | app fn arg h_fn h_arg => simp [aux, h_fn depth (ht.1), h_arg depth (ht.2)] | lambda body h_body => simp [aux, h_body (depth + 1) (allFreeVariablesBoundBy.lambda ht)] -- Q1.4 def batchSubstitute (t : LambdaTerm) (index: Nat) (exprs : List LambdaTerm) : LambdaTerm := aux t 0 where find (l : List (Nat × LambdaTerm)) depth m : LambdaTerm := match l with | [] => LambdaTerm.var m | (i, expr) :: tail => if i + depth = m then expr else find tail depth m aux t depth : LambdaTerm := match t with | LambdaTerm.var (val := m) => find (List.enumFrom index exprs) depth m | LambdaTerm.app fn arg => LambdaTerm.app (aux fn depth) (aux arg depth) | LambdaTerm.lambda body => LambdaTerm.lambda (aux body (depth + 1)) macro t:term "[" i:term "←" l:term "]" : term => `(batchSubstitute $t $i $l) theorem batchSubstituteFindSwap (index depth : Nat) (exprs : List LambdaTerm) : batchSubstitute.find (List.enumFrom index exprs) (depth + 1) m = batchSubstitute.find (List.enumFrom (index + 1) exprs) depth m := by induction exprs generalizing index with | nil => simp [batchSubstitute.find] | cons e t h => have this : index + 1 + depth = index + (depth + 1) := by rw [Nat.add_assoc, Nat.add_comm 1 depth] simp [batchSubstitute.find, this, h (index + 1)] theorem batchSubstituteFindPop (index m : Nat) {depth : Nat} (exprs : List LambdaTerm) (h₁ : m < index + exprs.length) (h₂ : index + depth ≤ m) : batchSubstitute.find (List.enumFrom (index + 1) exprs) depth (m + 1) = batchSubstitute.find (List.enumFrom index exprs) depth m := by induction exprs generalizing index with | nil => simp only [List.length_nil, Nat.add_zero] at h₁ have p : m < index + depth := Nat.ltAddRight h₁ have p' := Nat.ltOfLtOfLe p h₂ exact absurd p' <| Nat.ltIrrefl m | cons hd tl h_tl => simp [batchSubstitute.find] byCases h' : (index + depth = m) focus have h'' : index + 1 + depth = m + 1 by rw [Nat.add_assoc, Nat.add_comm 1, ← Nat.add_assoc, h'] simp [ifPos h', ifPos h''] focus have h'' : index + 1 + depth ≠ m + 1 by rw [Nat.add_assoc, Nat.add_comm 1, ← Nat.add_assoc] intro h₀ simp [Nat.add_one] at h₀ apply Nat.noConfusion h₀ exact (λ h : index + depth = m => h' h) simp [ifNeg h', ifNeg h''] apply h_tl (index + 1) focus simp only [List.length_cons, (Nat.add_one _).symm, Nat.add_comm (List.length _) 1, (Nat.add_assoc _ _ _).symm] at h₁ exact h₁ focus apply Nat.leOfLtSucc rw [Nat.add_assoc, Nat.add_comm 1, ← Nat.add_assoc] apply Nat.succLeSucc exact Nat.succLeOfLt <| Nat.ltOfLeOfNe h₂ h' theorem batchSubstituteSwap (t : LambdaTerm) (l : List LambdaTerm) (i : Nat) (depth : Nat) : batchSubstitute.aux i l t (depth + 1) = batchSubstitute.aux (i + 1) l t depth := by induction t generalizing depth with | var m => simp [batchSubstitute.aux, batchSubstituteFindSwap] | app fn arg h_fn h_arg => simp [batchSubstitute.aux, h_fn, h_arg] | lambda body h_body => simp [batchSubstitute.aux, h_body] theorem substEmpty (t : LambdaTerm) {i : Nat} : t[i ← []] = t := by induction t generalizing i with | var m => simp [batchSubstitute, batchSubstitute.aux, batchSubstitute.find] | app fn arg h_fn h_arg => simp only [batchSubstitute] at h_fn simp only [batchSubstitute] at h_arg simp [batchSubstitute, batchSubstitute.aux, h_fn, h_arg] | lambda body h_body => simp only [batchSubstitute] at h_body simp only [batchSubstitute, batchSubstitute.aux] rw [batchSubstituteSwap body [] i 0, h_body] theorem substMinorized (h : C[i](t)) (l : List LambdaTerm) : t[i ← l] = t := by induction t generalizing i with | var m => simp [batchSubstitute, batchSubstitute.aux] suffices p : ∀ j, i ≤ j → batchSubstitute.find (List.enumFrom j l) 0 m = LambdaTerm.var m from p i (Nat.leRefl i) induction l with | nil => intro j h' simp [batchSubstitute.find] | cons hd tl tl_h => intro j h' simp [batchSubstitute.find] have p : j ≠ m := Nat.ltOfLtOfLe h h' |> Nat.neOfLt |> Ne.symm simp [p, tl_h (j + 1) (Nat.leStep h')] | app fn arg h_fn h_arg => simp only [batchSubstitute] at h_fn simp only [batchSubstitute] at h_arg simp [batchSubstitute, batchSubstitute.aux, h_fn h.1, h_arg h.2] | lambda body h_body => have p := h_body (allFreeVariablesBoundBy.auxRec₂.2 h) simp only [batchSubstitute] at p rw [← batchSubstituteSwap body l i 0] at p simp [batchSubstitute, batchSubstitute.aux, p] theorem batchSubstituteFindLower (h : m < i) : batchSubstitute.find (List.enumFrom i l) 0 m = LambdaTerm.var m := by induction l generalizing i with | nil => simp [batchSubstitute.find] | cons hd tl h_tl => simp only [Nat.add_zero, batchSubstitute.find, ifNeg $ Ne.symm $ Nat.neOfLt h] exact h_tl $ Nat.ltTrans h $ Nat.ltSuccSelf i theorem batchSubstituteFindMinorized (l : List LambdaTerm) (h_l : List.forall (λ t => C[i](t)) l) (i_le_j : i ≤ j) (depth m : Nat) : (λ result => result = LambdaTerm.var m ∨ C[i](result)) $ batchSubstitute.find (List.enumFrom j l) depth m := by induction l generalizing j with | nil => simp [batchSubstitute.find] | cons hd tl h_tl => simp only [batchSubstitute.find] simp only [List.forall, List.foldr] at h_l byCases h : j + depth = m focus simp only [ifPos h] exact Or.inr h_l.1 focus simp only [ifNeg h] exact h_tl h_l.2 $ Nat.leTrans i_le_j $ Nat.leSucc j theorem substRotate (t : LambdaTerm) {i : Nat} {hd : LambdaTerm} {tl : List LambdaTerm} (h_hd : C[i](hd)) (h_tl : List.forall (λ t => C[i](t)) tl) : t[i ← hd :: tl] = t[(i + 1) ← tl][i ← [hd]] := by suffices p : ∀ j : Nat, i ≤ j → t[j ← hd :: tl] = t[(j + 1) ← tl][j ← [hd]] by exact p i (Nat.leRefl i) induction t with | var m => intro j h simp only [batchSubstitute, batchSubstitute.aux, batchSubstitute.find, Nat.add_zero] byCases h₁ : m ≤ j focus rw [batchSubstituteFindLower (show m < j + 1 from Nat.ltOfLeOfLt h₁ $ Nat.ltSuccSelf j)] byCases h₂ : m = j simp [batchSubstitute.aux, batchSubstitute.find, h₂] simp [batchSubstitute.aux, batchSubstitute.find, Ne.symm h₂] focus have j_ne_m : j ≠ m := λ h' => h₁ $ Nat.leOfEq h'.symm have p := batchSubstituteFindMinorized tl h_tl (Nat.leTrans h $ Nat.leSucc j) 0 m simp at p cases p with | inl h => simp [h, batchSubstitute.aux, batchSubstitute.find, j_ne_m] | inr h' => have p' : C[j](_) := boundByGreater h h' have p'' := substMinorized p' [hd] simp only [ifNeg j_ne_m] simp only [batchSubstitute] at p'' rw [p''] | app fn arg h_fn h_arg => intro j h simp [batchSubstitute] at h_fn simp [batchSubstitute] at h_arg simp [batchSubstitute, batchSubstitute.aux, h_fn j h, h_arg j h] | lambda body h_body => intro j h simp only [batchSubstitute] at h_body simp only [batchSubstitute, batchSubstitute.aux, batchSubstituteSwap] rw [h_body (j + 1) (Nat.leTrans h $ Nat.leSucc j)] -- Another useful lemma theorem substAllByClosed {l : List LambdaTerm} {t : LambdaTerm} (h₁ : C[List.length l](t)) (h₂ : List.forall (λ t => C[0](t)) l) : C[0](t[0 ← l]) := by suffices p : ∀ {t i}, C[List.length l + i](t) → C[i](t[i ← l]) by apply p rw [Nat.add_zero] exact h₁ intro t induction t with | var m => intro i h simp only [allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux] at h simp only [batchSubstitute, batchSubstitute.aux] suffices p : ∀ l j, (List.forall (λ t => C[0](t)) l) → (m < List.length l + j + i) → C[0](batchSubstitute.find (List.enumFrom (j + i) l) 0 m) ∨ (batchSubstitute.find (List.enumFrom (j + i) l) 0 m = LambdaTerm.var m ∧ m < j + i) from match p l 0 h₂ h with | Or.inl p => boundByGreater (Nat.zeroLe i) (Nat.zero_add i ▸ p) | Or.inr p => by simp [Nat.add_zero] at p rw [p.1]; exact p.2 intro l j hl h induction l generalizing j with | nil => apply Or.inr simp [List.enumFrom, batchSubstitute.find] simp [List.length_nil] at h exact h | cons hd tl h_tl => simp [List.forall, List.foldr] at hl simp [List.length_cons, (Nat.add_one _).symm] at h rw [Nat.add_assoc _ 1 j] at h have p := h_tl (1 + j) hl.2 h byCases hm : m < j + i focus simp [batchSubstituteFindLower hm, hm] focus byCases hm' : j + i = m focus simp [List.enumFrom, batchSubstitute.find, hm', hl.1] focus match p with | Or.inl p => apply Or.inl simp [List.enumFrom, batchSubstitute.find, hm'] exact (show j + i + 1 = 1 + j + i by rw [Nat.add_comm, Nat.add_assoc]) ▸ p | Or.inr p => exact absurd p.2 (show ¬ m < 1 + j + i from λ h => by rw [Nat.add_assoc, Nat.add_comm, Nat.add_one] at h match Nat.eqOrLtOfLe (Nat.leOfLtSucc h) with | Or.inl h => exact hm' h.symm | Or.inr h => exact hm h) | app fn arg h_fn h_arg => intro i h simp [allFreeVariablesBoundBy, batchSubstitute] at h_fn simp [allFreeVariablesBoundBy, batchSubstitute] at h_arg simp [allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux, h_fn h.1, h_arg h.2] | lambda body h_body => intro i h simp [allFreeVariablesBoundBy, batchSubstitute] at h_body simp [allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux] have p := allFreeVariablesBoundBy.lambda h simp [allFreeVariablesBoundBy] at p simp [batchSubstituteSwap] apply allFreeVariablesBoundBy.auxRec₂.1 exact h_body p -- Part 2 -- Q2.1 inductive SmallStepBetaReduction: LambdaTerm -> LambdaTerm -> Prop := | Eval : ∀ (u v: LambdaTerm), SmallStepBetaReduction (LambdaTerm.app (LambdaTerm.lambda u) v) (u[0 ← [v]]) | LeftContext : ∀ (u v t: LambdaTerm), SmallStepBetaReduction t u -> SmallStepBetaReduction (LambdaTerm.app t v) (LambdaTerm.app u v) | RightContext : ∀ (t u v : LambdaTerm), SmallStepBetaReduction t u -> SmallStepBetaReduction (LambdaTerm.app v t) (LambdaTerm.app v u) | LambdaContext : ∀ (t u : LambdaTerm), SmallStepBetaReduction t u -> SmallStepBetaReduction (LambdaTerm.lambda t) (LambdaTerm.lambda u) -- Q2.2 inductive BetaReduction: LambdaTerm -> LambdaTerm -> Prop := | Rfl (u: LambdaTerm): BetaReduction u u | Trans (t u v: LambdaTerm): SmallStepBetaReduction t u -> BetaReduction u v -> BetaReduction t v -- Q2.3 theorem BetaReduction.subterms.reduceAux1 (t u v: LambdaTerm): BetaReduction t u -> BetaReduction (LambdaTerm.app t v) (LambdaTerm.app u v) := fun h_red => by induction h_red with | Rfl => exact BetaReduction.Rfl _ | Trans w x y h_smallstep h_step₁ h_step₂ => -- TODO(Ryan): golf me. apply BetaReduction.Trans (LambdaTerm.app w v) (LambdaTerm.app x v) apply SmallStepBetaReduction.LeftContext assumption assumption theorem BetaReduction.subterms.reduceAux2 (t u v: LambdaTerm): BetaReduction t u -> BetaReduction (LambdaTerm.app v t) (LambdaTerm.app v u) := fun h_red => by induction h_red with | Rfl => exact BetaReduction.Rfl _ | Trans w x y h_smallstep h_step₁ h_step₂ => -- TODO(Ryan): golf me. apply BetaReduction.Trans (LambdaTerm.app v w) (LambdaTerm.app v x) apply SmallStepBetaReduction.RightContext assumption assumption theorem BetaReduction.subterms.reduceAux3 (t u: LambdaTerm): BetaReduction t u -> BetaReduction (LambdaTerm.lambda t) (LambdaTerm.lambda u) := fun h_red => by induction h_red with | Rfl => exact BetaReduction.Rfl _ | Trans w x y h_smallstep h_step₁ h_step₂ => -- TODO(Ryan): golf me. apply BetaReduction.Trans (LambdaTerm.lambda w) (LambdaTerm.lambda x) apply SmallStepBetaReduction.LambdaContext assumption; assumption -- Part 3 -- Q3.2 inductive KrivineInstruction | Access (n: Nat) | Grab (next: KrivineInstruction) | Push (next: KrivineInstruction) (continuation: KrivineInstruction) inductive KrivineClosure | pair (i: KrivineInstruction) (e: List KrivineClosure) def KrivineEnv := List KrivineClosure def KrivineStack := List KrivineClosure -- TODO(Ryan): maybe, merge these two definitions? structure KrivineState where code: KrivineInstruction env: KrivineEnv stack: KrivineEnv instance : Inhabited KrivineState where default := { code := KrivineInstruction.Access 0, env := [], stack := [] } -- Q3.3 -- @[reducible] def evalKrivineMachine (state: KrivineState): Option KrivineState := match state.code, state.env, state.stack with | KrivineInstruction.Access 0, (KrivineClosure.pair code recEnv :: closures), stack => some $ KrivineState.mk code recEnv stack | KrivineInstruction.Access (Nat.succ n), (KrivineClosure.pair code recEnv :: closures), stack => some $ KrivineState.mk (KrivineInstruction.Access n) closures stack | KrivineInstruction.Push c' c, env, stack => some $ KrivineState.mk c env (KrivineClosure.pair c' env :: stack) | KrivineInstruction.Grab code, closures, (KrivineClosure.pair c₀ e₀ :: stack) => some $ KrivineState.mk code (KrivineClosure.pair c₀ e₀ :: closures) stack | _, _, _ => none -- Part 4 -- Q4.1 def compile_instr: LambdaTerm -> KrivineInstruction | LambdaTerm.lambda t => KrivineInstruction.Grab (compile_instr t) | LambdaTerm.app t u => KrivineInstruction.Push (compile_instr u) (compile_instr t) | LambdaTerm.var n => KrivineInstruction.Access n def compile : LambdaTerm -> KrivineState := fun t => KrivineState.mk (compile_instr t) [] [] -- Part 5 -- Q5.1 def undoInstruction : KrivineInstruction → LambdaTerm | KrivineInstruction.Access n => LambdaTerm.var n | KrivineInstruction.Push c' c => LambdaTerm.app (undoInstruction c) (undoInstruction c') | KrivineInstruction.Grab c => LambdaTerm.lambda (undoInstruction c) set_option codegen false in def undoClosure : KrivineClosure → LambdaTerm := KrivineClosure.rec (λ inst env env_undone => (undoInstruction inst)[0 ← env_undone]) [] (λ hd tl hd_undone tl_undone => hd_undone :: tl_undone) /-def a : List KrivineClosure → LambdaTerm := KrivineClosure.rec_1 (λ inst env env_undone => (undoInstruction inst)[0 ← env_undone]) [] (λ hd tl hd_undone tl_undone => hd_undone :: tl_undone)-/ set_option codegen false in def undo (s : KrivineState) : LambdaTerm := List.foldl (λ f arg => LambdaTerm.app f $ undoClosure arg) ((undoInstruction s.code)[0 ← List.map undoClosure s.env]) s.stack theorem undoClosureSpec : undoClosure (KrivineClosure.pair i e) = (undoInstruction i)[0 ← List.map undoClosure e] := by simp [undoClosure] apply show ∀ {x y}, x = y → (undoInstruction i)[0 ← x] = (undoInstruction i)[0 ← y] from λ h => by rw [h] induction e with | nil => simp | cons hd tl h_tl => simp [List.map] rw [h_tl] -- Q5.2 def compile.idOfLeftInv (t: LambdaTerm): undoInstruction (compile_instr t) = t := by induction t with | var n => rfl | app fn arg h_fn h_arg => simp [undoInstruction, h_fn, h_arg] | lambda t ht => simp [undoInstruction, ht] def List.max: List Nat → Nat | [] => 0 | x :: q => Nat.max x (max q) partial def KrivineClosure.depthUnsafe: KrivineClosure -> Nat | KrivineClosure.pair i env => List.max (List.map depthUnsafe env) + 1 set_option codegen false in @[implementedBy KrivineClosure.depthUnsafe] def KrivineClosure.depth: KrivineClosure -> Nat := fun closure => by induction closure with | pair i env depth_env => exact depth_env | nil => exact 0 | cons head tail head_depth tail_depth => exact Nat.max (head_depth + 1) (tail_depth + 1) theorem KrivineClosure.depth.cons (c: KrivineInstruction) (a: KrivineClosure) (q: List KrivineClosure): depth (pair c (a :: q)) = Nat.max (depth a + 1) (depth (pair c q) + 1) := rfl def KrivineClosure.depth.spec: ∀ (c: KrivineInstruction) (x: KrivineClosure) (e: List KrivineClosure), depth x < depth (KrivineClosure.pair c (x :: e)) := fun c x e => by simp [KrivineClosure.depth.cons] exact Nat.ltSuccMaxLeft namespace KrivineEnv def depth: KrivineEnv -> Nat | [] => 0 | closure :: closures => Nat.max (KrivineClosure.depth closure + 1) (depth closures + 1) theorem depth_of_kcDepth (c: KrivineInstruction) (x: KrivineEnv): KrivineClosure.depth (KrivineClosure.pair c x) = depth x := by induction x with | nil => simp [depth, KrivineClosure.depth] | cons a q hq => simp [depth, KrivineClosure.depth.cons, hq] theorem depth_spec₁: ∀ (c: KrivineInstruction) (x: KrivineEnv) (q: KrivineEnv), measure depth q (KrivineClosure.pair c x :: q) := fun c x q => by simp only [measure, InvImage, depth] rw [← Nat.succMaxEqMaxSucc] exact Nat.ltSuccMaxRight theorem depth_spec₂: ∀ (c: KrivineInstruction) (x: KrivineEnv) (q: KrivineEnv), measure depth x (KrivineClosure.pair c x :: q) := fun c x q => by simp only [measure, InvImage, depth, depth_of_kcDepth] exact Nat.ltSuccMaxLeft def depth_rel: KrivineEnv -> KrivineEnv -> Prop := measure depth def depth_wf: WellFounded (measure depth) := measureWf depth def correctF: (e: KrivineEnv) -> ((y : KrivineEnv) → measure depth y e → Prop) -> Prop := fun e correct => match (generalizing := true) e with | [] => true | KrivineClosure.pair c₀ e₀ :: env => C[List.length e₀](undoInstruction c₀) ∧ (correct e₀ (depth_spec₂ _ _ _)) ∧ (correct env (depth_spec₁ _ _ _)) def correct: KrivineEnv -> Prop := WellFounded.fix depth_wf correctF def correct.spec: ∀ (x: KrivineEnv), WellFounded.fix depth_wf correctF x = correctF x (fun y correct => WellFounded.fix depth_wf correctF y) := WellFounded.fixEq depth_wf correctF theorem lateralInduction {motive : KrivineEnv → Sort} (env : KrivineEnv) (nil : motive []) (cons : ∀ code env tail, motive env → motive tail → motive (KrivineClosure.pair code env :: tail)) : motive env := by apply WellFounded.fix depth_wf intros x h_acc match x with | [] => exact nil | KrivineClosure.pair code env :: tail => exact cons _ _ _ (h_acc _ $ depth_spec₂ _ _ _) (h_acc _ $ depth_spec₁ _ _ _) end KrivineEnv def KrivineState.correct (state: KrivineState): Prop := C[List.length state.env](undoInstruction state.code) ∧ (KrivineEnv.correct state.env) ∧ (KrivineEnv.correct state.stack) -- Q5.3 theorem Classical.dne {p: Prop}: ¬¬p -> p := fun hnnp => match (em p) with | Or.inl hp => hp | Or.inr hnp => absurd hnp hnnp theorem evalKrivineMachine.isTransitionOfCorrect (state: KrivineState) (hcorrect: KrivineState.correct state) (h_grab: (∃ c: KrivineInstruction, state.code = KrivineInstruction.Grab c) -> (List.length state.stack) ≥ 1): (evalKrivineMachine state) ≠ none := byContradiction (fun hcontra => by simp at hcontra have evalKrivineMachine state = none from Classical.dne hcontra match state with | KrivineState.mk code env stack => match code with | KrivineInstruction.Access 0 => match env, stack with | (KrivineClosure.pair code recEnv :: closures), stack => simp [evalKrivineMachine] at this | KrivineInstruction.Access (Nat.succ n) => match env, stack with | (KrivineClosure.pair code recEnv :: closures), stack => simp [evalKrivineMachine] at this | KrivineInstruction.Push c' c => match env, stack with | env, stack => simp [evalKrivineMachine] at this | KrivineInstruction.Grab code => match env, stack with | closures, (KrivineClosure.pair c₀ e₀ :: stack) => simp [evalKrivineMachine] at this | env, [] => simp only [List.length] at h_grab exact h_grab ⟨ code, by rfl ⟩ ) theorem correctness.code.aux₁ (code: KrivineInstruction) (env: KrivineEnv) (tail: KrivineEnv) (h: KrivineEnv.correct (KrivineClosure.pair code env :: tail)): C[List.length env](undoInstruction code) := by simp [KrivineEnv.correct] at h rw [KrivineEnv.correct.spec] at h exact h.1 theorem correctness.code.aux₂ (m n: Nat): C[Nat.succ m](undoInstruction $ KrivineInstruction.Access (Nat.succ n)) -> C[m](undoInstruction $ KrivineInstruction.Access n) := by intro h; simp [undoInstruction, allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux, Nat.lt.base]; simp [undoInstruction, allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux] at h; exact h theorem correctness.code.aux₃ {c c': KrivineInstruction} {n: Nat}: C[n](undoInstruction $ KrivineInstruction.Push c c') -> C[n](undoInstruction c') ∧ C[n](undoInstruction c) := by simp [undoInstruction, allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux] exact (fun a => a) theorem correctness.code.aux₄ {c: KrivineInstruction}: C[n](undoInstruction $ KrivineInstruction.Grab c) -> C[Nat.succ n](undoInstruction c) := by simp [undoInstruction, allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux] exact (fun H => by apply (allFreeVariablesBoundBy.auxRec₂).2; exact H) theorem correctness.env.aux₁ (code: KrivineInstruction) (env: KrivineEnv) (tail: KrivineEnv) (h: KrivineEnv.correct (KrivineClosure.pair code env :: tail)): KrivineEnv.correct env := by simp only [KrivineEnv.correct] at h; rw [KrivineEnv.correct.spec] at h exact h.2.1 theorem correctness.env.aux₂ {code: KrivineInstruction} {env: KrivineEnv} {tail: KrivineEnv} (h: KrivineEnv.correct (KrivineClosure.pair code env :: tail)): KrivineEnv.correct tail := by simp only [KrivineEnv.correct] at h; rw [KrivineEnv.correct.spec] at h exact h.2.2 theorem correctness.env.aux₃ {code: KrivineInstruction} {env: KrivineEnv} {tail: KrivineEnv} (h_code: C[List.length env](undoInstruction code)) (h_head: KrivineEnv.correct env) (h_tail: KrivineEnv.correct tail): KrivineEnv.correct (KrivineClosure.pair code env :: tail) := by simp only [KrivineEnv.correct]; rw [KrivineEnv.correct.spec] exact ⟨ h_code, ⟨ h_head, h_tail ⟩ ⟩ theorem transitionCorrectness (state: KrivineState) (hcorrect: KrivineState.correct state) (h_istransition: evalKrivineMachine state ≠ none): KrivineState.correct $ (evalKrivineMachine state).get! := by simp [KrivineState.correct] match state with | KrivineState.mk code env stack => match code with | KrivineInstruction.Access 0 => match env, stack with | (KrivineClosure.pair code recEnv :: closures), stack => simp [KrivineState.correct] at hcorrect have evalKrivineMachine { code := KrivineInstruction.Access 0, env := KrivineClosure.pair code recEnv :: closures, stack := stack } = some { code := code, env := recEnv, stack := stack} from by rfl simp [this, Option.get!] exact ⟨ (correctness.code.aux₁ _ _ closures hcorrect.2.1), ⟨ (correctness.env.aux₁ code recEnv closures hcorrect.2.1), hcorrect.2.2 ⟩ ⟩ | KrivineInstruction.Access (Nat.succ n) => match env, stack with | (KrivineClosure.pair code recEnv :: closures), stack => simp [KrivineState.correct] at hcorrect simp [evalKrivineMachine, Option.get!] exact ⟨ (correctness.code.aux₂ _ _ hcorrect.1), ⟨ correctness.env.aux₂ hcorrect.2.1, hcorrect.2.2 ⟩ ⟩ | KrivineInstruction.Push c' c => match env, stack with | env, stack => simp [KrivineState.correct] at hcorrect simp [evalKrivineMachine, Option.get!] have allFreeVariablesBoundBy (List.length env) (undoInstruction c') from (correctness.code.aux₃ hcorrect.1).2 exact ⟨ (correctness.code.aux₃ hcorrect.1).1, ⟨ hcorrect.2.1, correctness.env.aux₃ this hcorrect.2.1 hcorrect.2.2⟩⟩ | KrivineInstruction.Grab code => match env, stack with | closures, (KrivineClosure.pair c₀ e₀ :: stack) => simp [KrivineState.correct] at hcorrect simp [evalKrivineMachine, Option.get!] have h₁: allFreeVariablesBoundBy (List.length e₀) (undoInstruction c₀) from correctness.code.aux₁ _ _ _ hcorrect.2.2 have h₂: KrivineEnv.correct e₀ from correctness.env.aux₁ _ _ _ hcorrect.2.2 exact ⟨ correctness.code.aux₄ hcorrect.1, ⟨ correctness.env.aux₃ h₁ h₂ hcorrect.2.1, correctness.env.aux₂ hcorrect.2.2 ⟩ ⟩ | env, [] => simp [KrivineState.correct] at hcorrect simp [evalKrivineMachine, Option.get!] have evalKrivineMachine { code := KrivineInstruction.Grab code, env := env, stack := [] } = none from by rfl exact absurd this h_istransition -- Q5.4 theorem lemma₀ : SmallStepBetaReduction u v → SmallStepBetaReduction (List.foldl (λ f arg => LambdaTerm.app f (undoClosure arg)) u l) (List.foldl (λ f arg => LambdaTerm.app f (undoClosure arg)) v l) := by induction l generalizing u v with | nil => simp [List.foldl] exact λ h => h | cons hd tl tl_h => intro h apply tl_h simp [List.foldl] exact SmallStepBetaReduction.LeftContext _ _ _ h theorem lemma₁ (h₁ : C[0](u)) (h₂ : List.forall (λ t => C[0](t)) l) : SmallStepBetaReduction (LambdaTerm.app (LambdaTerm.lambda (t[1 ← l])) u) (t[0 ← u :: l]) := by rw [substRotate t h₁ h₂] apply SmallStepBetaReduction.Eval theorem closedOfCorrect {env : KrivineEnv} (correct : KrivineEnv.correct env) : List.forall (λ t => C[0](t)) (List.map undoClosure env) := by induction env using KrivineEnv.lateralInduction with | nil => simp [List.map, List.forall, List.foldr] | cons code env tail h_env h_tail => simp [List.map, List.forallCons, h_tail <| correctness.env.aux₂ correct] simp [undoClosureSpec] exact substAllByClosed (by rw [List.lengthMap undoClosure env] exact correctness.code.aux₁ code env tail correct) (h_env <| correctness.env.aux₁ _ _ _ correct) /- Nous avons rencontré un léger problème : nous avons dû modifier la question 5.4 qui était fausse en l'état (une transition de la machine de Krivine ne correspond pas toujours à une beta-reduction -- on le voit par exemple dans les cas où l'instruction à exécuter est `Access n` avec n > 0). Nous avons donc décidé de simplement montrer qu'une transition de la machine de Krivine correspond soit à une beta-reduction, soit à aucune opération modulo τ. -/ theorem simulationCorrectness (state₀ : KrivineState) (state₁ : KrivineState) (eval : evalKrivineMachine state₀ = state₁) (correct : KrivineState.correct state₀) : SmallStepBetaReduction (undo state₀) (undo state₁) ∨ undo state₀ = undo state₁ := by match state₀ with | KrivineState.mk code state stack => induction code with | Access n => match state with | [] => cases n with | zero => simp [evalKrivineMachine] at eval | succ n => simp [evalKrivineMachine] at eval | KrivineClosure.pair code recEnv :: closures => apply Or.inr cases n with | zero => simp [evalKrivineMachine] at eval apply Option.noConfusion eval intro eval rw [← eval] simp [undo, undoInstruction, batchSubstitute, batchSubstitute.aux, List.enumFrom, batchSubstitute.find] rw [undoClosureSpec] rfl | succ n => simp [evalKrivineMachine] at eval apply Option.noConfusion eval intro eval rw [← eval] simp [undo, undoInstruction, batchSubstitute, batchSubstitute.aux, List.enumFrom, batchSubstitute.find] suffices p : batchSubstitute.find (List.enumFrom 1 (List.map undoClosure closures)) 0 (Nat.succ n) = batchSubstitute.find (List.enumFrom 0 (List.map undoClosure closures)) 0 n by rw [p] apply batchSubstituteFindPop focus have p := correct.1 simp [List.length_cons, undoInstruction, allFreeVariablesBoundBy, allFreeVariablesBoundBy.aux] at p rw [List.lengthMap, Nat.zero_add] apply Nat.lt_of_succ_lt_succ exact p focus exact Nat.zeroLe n | Push c' c c'_h c_h => simp [evalKrivineMachine] at eval apply Option.noConfusion eval intro eval rw [← eval] simp [undo, undoInstruction, batchSubstitute, batchSubstitute.aux, undoClosureSpec, List.foldl] | Grab c c_h => apply Or.inl match stack with | [] => simp [evalKrivineMachine] at eval | KrivineClosure.pair code recEnv :: closures => simp [evalKrivineMachine] at eval apply Option.noConfusion eval intro eval rw [← eval] simp [undo, undoInstruction, batchSubstitute, batchSubstitute.aux, undoClosureSpec, List.foldl, List.map] simp [KrivineState.correct] at correct apply lemma₀ simp [batchSubstituteSwap] have p₁ := substAllByClosed (by rw [List.lengthMap undoClosure recEnv] exact correctness.code.aux₁ _ _ _ correct.2.2) (closedOfCorrect <| correctness.env.aux₁ _ _ _ correct.2.2) apply lemma₁ p₁ (closedOfCorrect correct.2.1) -- Q5.5 inductive EvalTC: KrivineState -> KrivineState -> Prop := | Rfl (u: KrivineState): EvalTC u u | Trans (t u v: KrivineState): evalKrivineMachine t = u -> EvalTC u v -> EvalTC t v /- Le vrai problème se pose à la dernière question : nous n'avons pas assez de lemmes pour montrer un théorème de correction vraiment puissant. En l'état, nous avons simplement montré qu'une chaîne de transitions de la machine de Krivine correspond à une chaîne de beta-reductions, c'est à dire une version itérée de 5.4. Nous aurions pu montrer un théorème plus puissant en renforçant des lemmes précédents. Le mieux aurait été de montrer que pour tout état `s` correct, s'il existe une transition de la machine de Krivine partant de `s`, alors il existe une chaîne de transitions `s = s₀ -> s₁ -> ... -> sₙ` telle que `τ(s₀) -> τ(sₙ)`. Ceci nous aurait permis d'exhiber une équivalence entre les exécutions du modèle du lambda calcul que l'on a dans le sujet et les exécutions de la machine de Krivine. -/ theorem simulationCorrectnessTC (u v : KrivineState) (h : EvalTC u v) (correct : KrivineState.correct u) : BetaReduction (undo u) (undo v) := by induction h with | Rfl u => apply BetaReduction.Rfl | Trans t u v t_h a a_h => have p := simulationCorrectness t u t_h correct have u_correct := transitionCorrectness t correct (by simp [t_h]) rw [t_h] at u_correct match p with | Or.inl p => exact BetaReduction.Trans (undo t) (undo u) (undo v) p (a_h u_correct) | Or.inr p => rw [p] exact a_h u_correct
fab288dee8885be0c533ba323a6f45c94a7e896f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/infoIssues.lean
7467dc329c2d6f3085d868096bb8872e99dcc24a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,050
lean
set_option trace.Elab.info true example (x y : Nat) (h : x = y) : 0 + x = y + 0 := by have := by exact h.symm -- --^ $/lean/plainGoal -- Good: ..., this : y = x |- 0 + x = y + 0 example (x : Nat) : x = 0 + (0 + (0 + x)) ∧ p := by constructor · cases x next => rfl -- Good: we get multiple states here as expected --v $/lean/plainGoal next => repeat rw [Nat.zero_add] --^ $/lean/plainGoal -- Bad? We still get all states except the one closed by implicit `rfl` --^ $/lean/plainGoal -- Good: ... |- p example (x : Nat) : x = 0 + (0 + (0 + x)) ∧ p := by constructor match x with | 0 => rfl -- Bad? We still get all states except the one closed by implicit `rfl` --v $/lean/plainGoal | y+1 => repeat rw [Nat.zero_add] --^ $/lean/plainGoal -- Good: we get the succ state here --^ $/lean/plainGoal -- Good: ... |- p
6158e8b8b9b0fa16bd48adb142c8c00cf634ec1c
c86b74188c4b7a462728b1abd659ab4e5828dd61
/stage0/src/Init/Notation.lean
95c86899ccd3b35b25fbadcc9646235e0fb07186
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,509
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 Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude -- DSL for specifying parser precedences and priorities namespace Lean.Parser.Syntax syntax:65 (name := addPrec) prec " + " prec:66 : prec syntax:65 (name := subPrec) prec " - " prec:66 : prec syntax:65 (name := addPrio) prio " + " prio:66 : prio syntax:65 (name := subPrio) prio " - " prio:66 : prio end Lean.Parser.Syntax macro "max" : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) macro "arg" : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...) macro "lead" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...) macro "(" p:prec ")" : prec => p macro "min" : prec => `(10) -- minimum precedence used in term parsers macro "min1" : prec => `(11) -- `(min+1) we can only `min+1` after `Meta.lean` /- `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`. We use `max_prec` to workaround bootstrapping issues. -/ macro "max_prec" : term => `(1024) macro "default" : prio => `(1000) macro "low" : prio => `(100) macro "mid" : prio => `(1000) macro "high" : prio => `(10000) macro "(" p:prio ")" : prio => p -- Basic notation for defining parsers syntax stx "+" : stx syntax stx "*" : stx syntax stx "?" : stx syntax:2 stx " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂)) /- Comma-separated sequence. -/ macro:max x:stx ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:max x:stx ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /- Comma-separated sequence with optional trailing comma. -/ macro:max x:stx ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:max x:stx ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro "!" x:stx : stx => `(stx| notFollowedBy($x)) syntax (name := rawNatLit) "nat_lit " num : term infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:55 " ||| " => HOr.hOr infixl:58 " ^^^ " => HXor.hXor infixl:60 " &&& " => HAnd.hAnd infixl:65 " + " => HAdd.hAdd infixl:65 " - " => HSub.hSub infixl:70 " * " => HMul.hMul infixl:70 " / " => HDiv.hDiv infixl:70 " % " => HMod.hMod infixl:75 " <<< " => HShiftLeft.hShiftLeft infixl:75 " >>> " => HShiftRight.hShiftRight infixr:80 " ^ " => HPow.hPow prefix:100 "-" => Neg.neg prefix:100 "~~~" => Complement.complement /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators. It addresses issue #382. -/ macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y) macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y) macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y) macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y) macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y) macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y) macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y) macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y) macro_rules | `($x <<< $y) => `(binop% HShiftLeft.hShiftLeft $x $y) macro_rules | `($x >>> $y) => `(binop% HShiftRight.hShiftRight $x $y) macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y) -- declare ASCII alternatives first so that the latter Unicode unexpander wins infix:50 " <= " => LE.le infix:50 " ≤ " => LE.le infix:50 " < " => LT.lt infix:50 " >= " => GE.ge infix:50 " ≥ " => GE.ge infix:50 " > " => GT.gt infix:50 " = " => Eq infix:50 " == " => BEq.beq infix:50 " ~= " => HEq infix:50 " ≅ " => HEq /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel% LE.le $x $y) macro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y) macro_rules | `($x < $y) => `(binrel% LT.lt $x $y) macro_rules | `($x > $y) => `(binrel% GT.gt $x $y) macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y) macro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y) macro_rules | `($x = $y) => `(binrel% Eq $x $y) macro_rules | `($x == $y) => `(binrel% BEq.beq $x $y) infixr:35 " /\\ " => And infixr:35 " ∧ " => And infixr:30 " \\/ " => Or infixr:30 " ∨ " => Or notation:max "¬" p:40 => Not p infixl:35 " && " => and infixl:30 " || " => or notation:max "!" b:40 => not b infixl:65 " ++ " => HAppend.hAppend infixr:67 " :: " => List.cons infixr:20 " <|> " => HOrElse.hOrElse infixr:60 " >> " => HAndThen.hAndThen infixl:55 " >>= " => Bind.bind infixl:60 " <*> " => Seq.seq infixl:60 " <* " => SeqLeft.seqLeft infixr:60 " *> " => SeqRight.seqRight infixr:100 " <$> " => Functor.map syntax (name := termDepIfThenElse) ppGroup(ppDedent("if " ident " : " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $h:ident : $c then $t:term else $e:term) => ``(dite $c (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppGroup(ppDedent("if " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $c then $t:term else $e:term) => ``(ite $c $t $e) macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat:term => $t | _ => $e) syntax:min term "<|" term:min : term macro_rules | `($f $args* <| $a) => let args := args.push a; `($f $args*) | `($f <| $a) => `($f $a) syntax:min term "|>" term:min1 : term macro_rules | `($a |> $f $args*) => let args := args.push a; `($f $args*) | `($a |> $f) => `($f $a) -- Haskell-like pipe <| -- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations. syntax:min term atomic("$" ws) term:min : term macro_rules | `($f $args* $ $a) => let args := args.push a; `($f $args*) | `($f $ $a) => `($f $a) syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p)) /- `without_expected_type t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `without_expected_type` is not effective in this case. -/ macro "without_expected_type " x:term : term => `(let aux := $x; aux) syntax "[" term,* "]" : term syntax "%[" term,* "|" term "]" : term -- auxiliary notation for creating big list literals namespace Lean macro_rules | `([ $elems,* ]) => do let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← ``(List.cons $(elems.elemsAndSeps[i]) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← ``(List.nil)) else `(%[ $elems,* | List.nil ]) -- TODO: should be `infix:50 " matches " => fun e p => match e with | p => true | _ => false` macro:50 e:term:51 " matches " p:term:51 : term => `(match $e:term with | $p:term => true | _ => false) namespace Parser.Tactic syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic syntax (name := intros) "intros " (colGt (ident <|> "_"))* : tactic syntax (name := rename) "rename " term " => " ident : tactic syntax (name := revert) "revert " (colGt ident)+ : tactic syntax (name := clear) "clear " (colGt ident)+ : tactic syntax (name := subst) "subst " (colGt ident)+ : tactic syntax (name := assumption) "assumption" : tactic syntax (name := contradiction) "contradiction" : tactic syntax (name := apply) "apply " term : tactic syntax (name := exact) "exact " term : tactic syntax (name := refine) "refine " term : tactic syntax (name := refine') "refine' " term : tactic syntax (name := constructor) "constructor" : tactic syntax (name := case) "case " ident (ident <|> "_")* " => " tacticSeq : tactic syntax (name := allGoals) "allGoals " tacticSeq : tactic syntax (name := focus) "focus " tacticSeq : tactic syntax (name := skip) "skip" : tactic syntax (name := done) "done" : tactic syntax (name := traceState) "traceState" : tactic syntax (name := failIfSuccess) "failIfSuccess " tacticSeq : tactic syntax (name := generalize) "generalize " atomic(ident " : ")? term:51 " = " ident : tactic syntax (name := paren) "(" tacticSeq ")" : tactic syntax (name := withReducible) "withReducible " tacticSeq : tactic syntax (name := withReducibleAndInstances) "withReducibleAndInstances " tacticSeq : tactic syntax (name := first) "first " withPosition((group(colGe "|" tacticSeq))+) : tactic syntax (name := rotateLeft) "rotateLeft" (num)? : tactic syntax (name := rotateRight) "rotateRight" (num)? : tactic macro "try " t:tacticSeq : tactic => `(first | $t | skip) macro:1 x:tactic " <;> " y:tactic:0 : tactic => `(tactic| focus ($x:tactic; allGoals $y:tactic)) syntax ("·" <|> ".") tacticSeq : tactic macro_rules | `(tactic| ·%$dot $ts:tacticSeq) => `(tactic| {%$dot ($ts:tacticSeq) }) macro "rfl" : tactic => `(exact rfl) macro "admit" : tactic => `(exact sorry) macro "inferInstance" : tactic => `(exact inferInstance) syntax locationWildcard := "*" syntax locationHyp := (colGt ident)+ ("⊢" <|> "|-")? -- TODO: delete syntax locationTargets := (colGt ident)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) syntax (name := change) "change " term (location)? : tactic syntax (name := changeWith) "change " term " with " term (location)? : tactic syntax rwRule := ("←" <|> "<-")? term syntax rwRuleSeq := "[" rwRule,+,? "]" syntax (name := rewriteSeq) "rewrite " rwRuleSeq (location)? : tactic syntax (name := erewriteSeq) "erewrite " rwRuleSeq (location)? : tactic syntax (name := rwSeq) "rw " rwRuleSeq (location)? : tactic syntax (name := erwSeq) "erw " rwRuleSeq (location)? : tactic def rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do -- We show the `rfl` state on `]` let seq := stx[1] let rbrak := seq[2] -- Replace `]` token with one without position information in the expanded tactic let seq := seq.setArg 2 (mkAtom "]") let tac := stx.setKind kind |>.setArg 0 (mkAtomFrom stx atom) |>.setArg 1 seq `(tactic| $tac; try (withReducible rfl%$rbrak)) @[macro rwSeq] def expandRwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.rewriteSeq "rewrite" @[macro erwSeq] def expandERwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.erewriteSeq "erewrite" syntax (name := injection) "injection " term (" with " (colGt (ident <|> "_"))+)? : tactic syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? term syntax simpErase := "-" ident syntax (name := simp) "simp " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? (location)? : tactic syntax (name := simpAll) "simp_all " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic -- Auxiliary macro for lifting have/suffices/let/... -- It makes sure the "continuation" `?_` is the main goal after refining macro "refineLift " e:term : tactic => `(focus (refine noImplicitLambda% $e; rotateRight)) macro "have " d:haveDecl : tactic => `(refineLift have $d:haveDecl; ?_) /- We use a priority > default, to avoid ambiguity with previous `have` notation -/ macro (priority := high) "have" x:ident " := " p:term : tactic => `(have $x:ident : _ := $p) macro "suffices " d:sufficesDecl : tactic => `(refineLift suffices $d:sufficesDecl; ?_) macro "let " d:letDecl : tactic => `(refineLift let $d:letDecl; ?_) macro "show " e:term : tactic => `(refineLift show $e:term from ?_) syntax (name := letrec) withPosition(atomic(group("let " &"rec ")) letRecDecls) : tactic macro_rules | `(tactic| let rec $d:letRecDecls) => `(tactic| refineLift let rec $d:letRecDecls; ?_) -- Similar to `refineLift`, but using `refine'` macro "refineLift' " e:term : tactic => `(focus (refine' noImplicitLambda% $e; rotateRight)) macro "have' " d:haveDecl : tactic => `(refineLift' have $d:haveDecl; ?_) macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x:ident : _ := $p) macro "let' " d:letDecl : tactic => `(refineLift' let $d:letDecl; ?_) syntax inductionAlt := "| " (group("@"? ident) <|> "_") (ident <|> "_")* " => " (hole <|> syntheticHole <|> tacticSeq) syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " ident+)? (inductionAlts)? : tactic syntax casesTarget := atomic(ident " : ")? term syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic syntax (name := existsIntro) "exists " term : tactic syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip) syntax "trivial" : tactic macro_rules | `(tactic| trivial) => `(tactic| assumption) macro_rules | `(tactic| trivial) => `(tactic| rfl) macro_rules | `(tactic| trivial) => `(tactic| contradiction) macro_rules | `(tactic| trivial) => `(tactic| apply True.intro) macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial) macro "unhygienic " t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq) end Tactic namespace Attr -- simp attribute syntax syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr end Attr end Parser end Lean macro "‹" type:term "›" : term => `((by assumption : $type))
d71041d2f15a0117e5530ced6356a64d8697062f
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/run/252.lean
1f2f1400973652561ac950ade554114ca1a8fd54
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
324
lean
open nat inductive tree (A : Type) | leaf : A → tree | node : tree → tree → tree #check tree.node definition size {A : Type} (t : tree A) : nat := tree.rec (λ a, 1) (λ t₁ t₂ n₁ n₂, n₁ + n₂) t #check size #reduce size (tree.node (tree.node (tree.leaf 0) (tree.leaf 1)) (tree.leaf 0))
68d459c1dcf292548248b7df09b92af08b500ef8
43390109ab88557e6090f3245c47479c123ee500
/src/M3P14/lqr.lean
2c7484ba66596fc1aaabf0f5b4139259fcc37fe6
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,314
lean
import tactic.ring import data.nat.prime import data.nat.modeq data.int.modeq import analysis.real import tactic.norm_num import algebra.group_power import M3P14.order import chris_hughes_various.zmod import M3P14.Problem_sheets.sheet1 import tactic.ring import logic.basic import data.int.basic open nat definition prime_int (p : ℤ) := prime(int.nat_abs p) theorem prime_int_to_nat {p : ℤ} (h : prime_int p) : prime (int.nat_abs p) := begin exact (show prime(int.nat_abs p), from h), end definition quadratic_res (a n : ℤ) := ∃ x : ℤ, a ≡ x^2 [ZMOD (int.nat_abs n)] --definition quadratic_res' (p : ℤ) (hp : prime_int p ∧ p ≠ 2) (a n : zmod p) := ∃ x : ℕ, a ≡ x^2 [ZMOD n] attribute [instance, priority 0] classical.prop_decidable noncomputable definition legendre_sym {p : ℤ} (a : ℤ) (H1 : prime_int p ∧ (int.nat_abs p) ≠ 2) : ℤ := if quadratic_res a p ∧ ¬ ((p : ℤ) ∣ a) then 1 else if ¬ quadratic_res a p then -1 else 0 theorem law_of_quadratic_reciprocity {p q : ℤ} (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) (hq : prime_int q ∧ (int.nat_abs q) ≠ 2) : (legendre_sym p hq)*(legendre_sym q hp) = (-1)^(int.nat_abs(((p-1)/2)*((q-1)/2))) := sorry theorem law_of_quadratic_reciprocity' {p q : ℤ} (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) (hq : prime_int q ∧ (int.nat_abs q) ≠ 2) : (legendre_sym p hq) = (legendre_sym q hp) * (-1)^(int.nat_abs(((p-1)/2)*((q-1)/2))):= sorry theorem legendre_sym_mul {p : ℤ} (a b : ℤ) (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) : legendre_sym (a*b) hp = (legendre_sym a hp)*(legendre_sym b hp) := sorry theorem legendre_sym_refl {p : ℤ} (a b : ℤ) (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) : (a ≡ b [ZMOD p] → legendre_sym a hp = legendre_sym b hp) := sorry theorem LQR_supplementary_2 {p : ℤ} (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) : legendre_sym 2 hp = (-1:ℤ)^(int.nat_abs((p^2-1)/8)) := sorry theorem legendre_one {p : ℤ} (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) : legendre_sym 1 hp = 1 := sorry theorem legendre_neg_one {p : ℤ} (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) : legendre_sym (-1) hp = (-1)^(int.nat_abs((p-1)/2)) := sorry theorem pow_two_eq_mul_self (x : ℕ) : x^2 = x * x := begin show 1*x*x=x*x,rw one_mul end theorem factorization_x_square_minus_one(x : ℕ) : x^2-1 = (x+1)*(x-1):= begin rw pow_two_eq_mul_self, cases x with t, norm_num, show (t+1) * (t+1) - 1 = (succ t + 1) * t, ring, end --theorem num_of_quad_res {p : ℕ} (hp : prime_int p ∧ p ≠ 2) : ∃ (A : set ℕ) [finset A], ∀ x : [1, (p-1)], (legendre_sym x hp = 1 ↔ x ∈ A) ∧ finset.card A = (p-1)/2 lemma int.mod_two_eq_zero_or_one (n : ℤ): n % 2 = 0 ∨ n % 2 = 1 := have h: n % 2 < 2 := abs_of_nonneg (show (2 : ℤ) ≥ 0, from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h1 : n % 2 ≥ 0 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h1 with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k+2 : ℕ) := λ h _, absurd h dec_trivial |(-[1+ a]) := λ _ h1, absurd h1 dec_trivial end lemma int.modeq.mod_modeq : ∀ (a n : ℤ), a % n ≡ a [ZMOD (int.nat_abs n)] := sorry lemma int.add_sub_cancel_left (n m : ℤ) : n + m - n = m := add_sub_cancel' n m lemma yet_to_prove (x : ℤ) (p : ℤ) (hp : prime_int p ∧ int.nat_abs p ≠ 2) : (x ^ int.nat_abs (p - 1)) = (int.nat_abs x) ^ (int.nat_abs p - 1) := sorry lemma odd_prime_int_is_odd {p : ℤ} (hp : prime_int p ∧ int.nat_abs p ≠ 2) : p % 2 = 1 := begin unfold prime_int at hp, have h1 : ¬ (p % 2 = 0), begin unfold prime at hp, intro, have h2 := int.dvd_of_mod_eq_zero a, have h3 := int.dvd_nat_abs.2 h2, have h4 : 2 ∣ (int.nat_abs p), from int.coe_nat_dvd.1 h3, have h5 := hp.1.2 2 h4, have h6 := or_iff_not_imp_left.1 h5 (show ¬ 2=1, by norm_num), have h7 : ¬ 2 = int.nat_abs p, rw eq_comm, exact hp.2, contradiction, end, have h2 : (p % 2 = 0) ∨ (p % 2 = 1), from int.mod_two_eq_zero_or_one p, exact or_iff_not_imp_left.1 h2 h1, end lemma p_minus_one_over_two (p : ℤ) (q : 2 ∣ int.nat_abs (p - 1)) : int.nat_abs ((p - 1) / 2) = int.nat_abs (p - 1) / 2 := begin cases q with d hd, have H : ∃ e, (p - 1) = 2 * e, cases (int.nat_abs_eq (p - 1)), existsi (d : ℤ), rw [h,hd], refl, existsi (- (d : ℤ)), rw [h,hd], rw int.coe_nat_mul, rw mul_neg_eq_neg_mul_symm,refl, cases H with e He, rw He, rw int.nat_abs_mul, rw int.mul_div_cancel_left, show _ = 2 * _ / _, rw nat.mul_div_cancel_left, exact dec_trivial, exact dec_trivial, end lemma two_dvd_p_minus_one {p : ℤ} (hp: prime_int p ∧ int.nat_abs p ≠ 2) : 2 ∣ int.nat_abs (p-1) := begin cases nat.mod_two_eq_zero_or_one (int.nat_abs p), have : (int.nat_abs p) % 2 ≡ int.nat_abs p [MOD 2], from nat.modeq.mod_modeq (int.nat_abs p) 2, have : 0 ≡ int.nat_abs p [MOD 2], from eq.subst h this, have : int.nat_abs p ≡ 0 [MOD 2], from nat.modeq.symm this, rw ← nat.modeq.modeq_zero_iff, exfalso, have h1 := hp.1.2 _ (nat.modeq.modeq_zero_iff.1 this), cases h1 with h3 h4, have h2: 2 ≠ 1, by norm_num, exact h2 h3, exact hp.2.symm h4, rw ← int.coe_nat_dvd, rw int.dvd_nat_abs, rw ← int.mod_add_div p 2, have : p % 2 = 1, from odd_prime_int_is_odd hp, rw this, rw int.add_sub_cancel_left, have r: 2 ≠ 0, by norm_num, exact dvd_mul_right _ _, end theorem euler_c_1 (a p : ℤ) (hp : prime_int p ∧ int.nat_abs p ≠ 2) (ha : ¬ p ∣ a) : quadratic_res a p → a^int.nat_abs((p-1)/2) ≡ 1 [ZMOD (int.nat_abs p)] := begin intro Hqr, cases Hqr with x hx, haveI : prime_int p := hp.1, haveI : pos_nat(int.nat_abs p) := sorry, rw ← zmod.eq_iff_modeq_int, rw ← zmod.eq_iff_modeq_int at hx, have q: 2 ∣ int.nat_abs(p-1), from two_dvd_p_minus_one hp, have h5 : int.nat_abs ((p-1)/2) = (int.nat_abs (p-1))/2, from p_minus_one_over_two p q, rw int.cast_pow, rw hx, rw int.cast_pow, rw ← pow_mul, rw h5, rw nat.mul_div_cancel' q, have h : prime (int.nat_abs p),{unfold prime_int at _inst; exact _inst}, have h1 : (int.nat_abs x)^((int.nat_abs p) -1) ≡ 1 [MOD (int.nat_abs p)], from fermat_little_theorem_extension (int.nat_abs x) (int.nat_abs p) h, have h2 : ↑(int.nat_abs x ^ (int.nat_abs p - 1)) ≡ ↑1 [ZMOD ↑(int.nat_abs p)], from int.modeq.coe_nat_modeq_iff.2 h1, have h3 : ↑(↑(int.nat_abs x ^ (int.nat_abs p - 1))) = ↑1, from zmod.eq_iff_modeq_int.2 h2, rw ← int.cast_pow, simp at h3, rw yet_to_prove _ _ hp, simp [h3], end lemma euler_c_2 (a p : ℤ) (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) (ha : ¬ p ∣ a) : ¬ (quadratic_res a p) → a^int.nat_abs((p-1)/2) ≡ -1 [ZMOD (int.nat_abs p)] := sorry theorem euler_criterion (p : ℤ) (a : ℤ) (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) (ha : ¬ p ∣ a) : a^int.nat_abs((p - 1) / 2) ≡ legendre_sym a hp [ZMOD (int.nat_abs p)] := begin unfold legendre_sym, split_ifs, exact euler_c_1 a p hp ha h.1, exfalso, have h8 : ¬quadratic_res a p, from not_and'.1 h (show ¬p ∣ a, from ha), from absurd h_1 h8, exact euler_c_2 a p hp ha h_1, end theorem not_prime_int_one : ¬(prime_int 1) := by unfold prime_int; exact dec_trivial theorem LQR_supplementary_1 {p : ℤ} (hp : prime_int p ∧ (int.nat_abs p) ≠ 2) (hpp : p ≥ 0): legendre_sym (-1:ℤ) hp = (-1:ℤ)^int.nat_abs((p-1)/2) := begin have h1 : ¬ ((p:ℤ)∣(-1:ℤ)), { intro h, have h2 : p = 1, from int.eq_one_of_dvd_one hpp (show ((p:ℤ)∣1), from int.dvd_nat_abs.2 h), exact not_prime_int_one (show prime_int 1, from eq.subst h2 hp.1), }, have h3 : (-1)^int.nat_abs((p - 1) / 2) ≡ legendre_sym (-1) hp [ZMOD (int.nat_abs p)] , from euler_criterion p (-1) hp h1, haveI : pos_nat(int.nat_abs p) := sorry, have h4:= zmod.eq_iff_modeq_int.2 h3, rw eq_comm, --exact ((int.coe_nat_eq_coe_nat_iff ((-1) ^ int.nat_abs ((p - 1) / 2)) (legendre_sym (-1) hp)).2 eq.symm(zmod.eq_iff_modeq_int.2 h6)), sorry, end #check int.coe_nat_eq #check int.coe_nat_eq_coe_nat_iff --theorem Jason_and_partly_Guy_did_it {p : ℕ} (hp : prime_int p ∧ p ≠ 2) : ∃ A : finset (zmod p), ∀ a : zmod p, (quadratic_res' a p ↔ a ∈ A) ∧ finset.card A = (p-1)/2 := sorry #check zmod.eq_iff_modeq_int theorem Guy_suggested_this_but_i_am_not_sure {p : ℕ} (hp : prime_int p ∧ p ≠ 2) : ∃ A : finset ℕ, ∀ a : ℕ, (¬quadratic_res a p ↔ a ∈ A) ∧ finset.card A = (p-1)/2 := sorry --Let p be an odd prime_int. Then there are exactly (p - 1) /2 quadratic residues modulo p and exactly (p - 1) /2 nonresidues modulo p. --theorem quad_res_sol {p : ℕ} (hp : prime_int p) : theorem minus_one_quad_res_of_p {p : ℕ} (hp : prime_int p ∧ p ≠ 2) : (p ≡ 1 [MOD 4] ↔ legendre_sym (-1 : ℤ) hp = 1) ∧ (p ≡ 3 [MOD 4] ↔ legendre_sym (-1 : ℤ) hp = (-1 : ℤ)) := sorry theorem quad_res_two (n : ℕ) : n % 8 = 1 ∨ n % 8 = 7 → ((n ^ 2 - 1) / 8 % 2 = 0) := begin intro H, have H2 := nat.mod_add_div n 8, cases H, { rw H at H2, rw ←H2, rw ←nat.dvd_iff_mod_eq_zero, suffices : ∀ t, 2 ∣ ((1 + 8 * t) ^ 2 - 1) / 8, exact this (n/8), intro t, existsi t+4*t*t, show (1 * (1 + 8 * t) * (1 + 8 * t) - 1) / 8 = 2 * (t + 4 * t * t), rw (show 1 * (1 + 8 * t) * (1 + 8 * t) = 8 * (2 * t + 8 * t * t) + 1, by ring), rw nat.add_sub_cancel, rw nat.mul_div_cancel_left _ (show 8 > 0, from dec_trivial), ring }, { rw H at H2, rw ←H2, rw ←nat.dvd_iff_mod_eq_zero, suffices : ∀ t, 2 ∣ ((7 + 8 * t) ^ 2 - 1) / 8, exact this (n/8), intro t, existsi 3+7*t+4*t*t, show (1 * (7 + 8 * t) * (7 + 8 * t) - 1) / 8 = 2 * (3 + 7 * t + 4 * t * t), rw (show 1 * (7 + 8 * t) * (7 + 8 * t) = 8 * (6 + 14 * t + 8 * t * t) + 1, by ring), rw nat.add_sub_cancel, rw nat.mul_div_cancel_left _ (show 8 > 0, from dec_trivial), ring } end theorem quad_nonres_two (n : ℕ) : n % 8 = 3 ∨ n % 8 = 5 → ((n ^ 2 - 1) / 8 % 2 = 1) := begin intro H, have H2 := nat.mod_add_div n 8, cases H, { rw H at H2, rw ←H2, suffices : ∀ t : ℕ, ((3 + 8 * t) ^ 2 - 1) / 8 % 2 = 1, exact this (n/8), intro t, have H3 : (1 + 2 * (4*t^2 + 3*t)) % 2 = 1, rw nat.add_mul_mod_self_left,exact dec_trivial, suffices : ((3 + 8 * t) ^ 2 - 1) / 8 = (1 + 2 * (4 * t ^ 2 + 3 * t)), rwa this, suffices : ((3 + 8 * t) ^ 2 - 1) = 8 * (1 + 2 * (4 * t ^ 2 + 3 * t)), rw this, rw nat.mul_div_cancel_left _ (show 8 > 0, from dec_trivial), ring }, { rw H at H2, rw ←H2, suffices : ∀ t : ℕ, ((5 + 8 * t) ^ 2 - 1) / 8 % 2 = 1, exact this (n/8), intro t, have H3 : (1 + 2 * (4*t^2 + 5*t + 1)) % 2 = 1, rw nat.add_mul_mod_self_left,exact dec_trivial, suffices : ((5 + 8 * t) ^ 2 - 1) / 8 = (1 + 2 * (4 * t ^ 2 + 5 * t + 1)), rwa this, suffices : ((5 + 8 * t) ^ 2 - 1) = 8 * (1 + 2 * (4 * t ^ 2 + 5 * t + 1)), rw this, rw nat.mul_div_cancel_left _ (show 8 > 0, from dec_trivial), ring } end theorem quad_res_two_int (n : ℤ) : n % 8 = (1:ℤ) ∨ n % 8 = (7:ℤ) → ((n ^ 2 - 1) / 8 % 2 = (0:ℤ)) := begin intro H, have H2 := int.mod_add_div n 8, cases H, { rw H at H2, rw ←H2, rw ←int.dvd_iff_mod_eq_zero, suffices : ∀ t, (2:ℤ) ∣ ((1 + 8 * t) ^ 2 - 1) / (8:ℤ), exact this (n/(8:ℤ)), intro t, existsi t+4*t*t, unfold has_pow.pow, unfold monoid.pow, rw (show (1 + 8 * t) * ((1 + 8 * t) * 1)= 8 * (2 * t + 8 * t * t) + 1, by ring), rw add_sub_cancel, rw int.mul_div_cancel_left _ (show (8:ℤ) ≠ 0, from dec_trivial), ring }, { rw H at H2, rw ←H2, rw ←int.dvd_iff_mod_eq_zero, suffices : ∀ t, (2:ℤ) ∣ ((7 + 8 * t) ^ 2 - 1) / 8, exact this (n/(8:ℤ)), intro t, existsi 3+7*t+4*t*t, unfold has_pow.pow, unfold monoid.pow, rw (show (7 + 8 * t) * ((7 + 8 * t) * 1) = 8 * (6 + 14 * t + 8 * t * t) + 1, by ring), rw add_sub_cancel, rw int.mul_div_cancel_left _ (show (8:ℤ) ≠ 0, from dec_trivial), ring, } end theorem quad_nonres_two_int (n : ℤ) : n % 8 = (3:ℤ) ∨ n % 8 = (5:ℤ) → ((n ^ 2 - 1) / 8 % 2 = (1:ℤ)) := begin intro H, have H2 := int.mod_add_div n (8:ℤ), cases H, { rw H at H2, rw ←H2, suffices : ∀ t : ℤ, ((3 + 8 * t) ^ 2 - 1) / 8 % 2 = (1:ℤ), exact this (n/(8:ℤ)), intro t, have H3 : (1 + 2 * (4*t^2 + 3*t)) % 2 = (1:ℤ), rw int.add_mul_mod_self_left,exact dec_trivial, suffices : ((3 + 8 * t) ^ 2 - 1) / 8 = (1 + 2 * (4 * t ^ 2 + 3 * t)), rwa this, suffices : ((3 + 8 * t) ^ 2 - 1) = 8 * (1 + 2 * (4 * t ^ 2 + 3 * t)), rw this, rw int.mul_div_cancel_left _ (show (8:ℤ) ≠ 0, from dec_trivial), ring }, { rw H at H2, rw ←H2, suffices : ∀ t : ℤ, ((5 + 8 * t) ^ 2 - 1) / 8 % 2 = (1:ℤ), exact this (n/(8:ℤ)), intro t, have H3 : (1 + 2 * (4*t^2 + 5*t + 1)) % 2 = 1, rw int.add_mul_mod_self_left,exact dec_trivial, suffices : ((5 + 8 * t) ^ 2 - 1) / 8 = (1 + 2 * (4 * t ^ 2 + 5 * t + 1)), rwa this, suffices : ((5 + 8 * t) ^ 2 - 1) = 8 * (1 + 2 * (4 * t ^ 2 + 5 * t + 1)), rw this, rw int.mul_div_cancel_left _ (show (8:ℤ) ≠ 0, from dec_trivial), ring } end
6ad806d89236381bff63867d4a4342c2f8ce6644
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/local_cache.lean
93851868d7c17b2f1ad98e552321b17b25ef3494
[ "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
7,340
lean
/- Copyright (c) 2019 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek -/ import tactic.norm_num namespace tactic namespace local_cache namespace internal variables {α : Type} [reflected α] [has_reflect α] meta def mk_full_namespace (ns : name) : name := `local_cache ++ ns meta def save_data (dn : name) (a : α) [reflected a] : tactic unit := tactic.add_decl $ mk_definition dn [] (reflect α) (reflect a) meta def load_data (dn : name) : tactic α := do e ← tactic.get_env, d ← e.get dn, tactic.eval_expr α d.value meta def poke_data (dn : name) : tactic bool := do e ← tactic.get_env, return (e.get dn).to_bool meta def run_once_under_name {α : Type} [reflected α] [has_reflect α] (t : tactic α) (cache_name : name) : tactic α := do load_data cache_name <|> do { a ← t, save_data cache_name a, return a } -- We maintain two separate caches with different scopes: -- one local to `begin ... end` or `by` blocks, and another -- for entire `def`/`lemma`s. meta structure cache_scope := -- Returns the name of the def used to store the contents of is cache, -- making a new one and recording this in private state if neccesary. (get_name : name → tactic name) -- Same as above but fails instead of making a new name, and never -- mutates state. (try_get_name : name → tactic name) -- Asks whether the namespace `ns` currently has a value-in-cache (present : name → tactic bool) -- Clear cache associated to namespace `ns` (clear : name → tactic unit) namespace block_local -- `mk_new` gives a way to generate a new name if no current one -- exists. private meta def get_name_aux (ns : name) (mk_new : options → name → tactic name) : tactic name := do o ← tactic.get_options, let opt := mk_full_namespace ns, match o.get_string opt "" with | "" := mk_new o opt | s := return $ name.from_components $ s.split (= '.') end meta def get_name (ns : name) : tactic name := get_name_aux ns $ λ o opt, do n ← mk_user_fresh_name, tactic.set_options $ o.set_string opt n.to_string, return n -- Like `get_name`, but fail if `ns` does not have a cached -- decl name (we create a new one above). meta def try_get_name (ns : name) : tactic name := get_name_aux ns $ λ o opt, fail format!"no cache for \"{ns}\"" meta def present (ns : name) : tactic bool := do o ← tactic.get_options, match o.get_string (mk_full_namespace ns) "" with | "" := return ff | s := return tt end meta def clear (ns : name) : tactic unit := do o ← tactic.get_options, set_options $ o.set_string (mk_full_namespace ns) "" end block_local namespace def_local -- Fowler-Noll-Vo hash function (FNV-1a) section fnv_a1 def FNV_OFFSET_BASIS := 0xcbf29ce484222325 def FNV_PRIME := 0x100000001b3 def RADIX := by apply_normed 2^64 def hash_byte (seed : ℕ) (c : char) : ℕ := let n : ℕ := c.to_nat in ((seed.lxor n) * FNV_PRIME) % RADIX def hash_string (s : string) : ℕ := s.to_list.foldl hash_byte FNV_OFFSET_BASIS end fnv_a1 meta def hash_context : tactic string := do ns ← open_namespaces, dn ← decl_name, let flat := ((list.cons dn ns).map to_string).foldl string.append "", return $ (to_string dn) ++ (to_string (hash_string flat)) meta def get_root_name (ns : name) : tactic name := do hc ← hash_context, return $ mk_full_namespace $ hc ++ ns meta def apply_tag (n : name) (tag : ℕ) : name := n ++ to_string format!"t{tag}" meta def mk_dead_name (n : name) : name := n ++ `dead meta def kill_name (n : name) : tactic unit := save_data (mk_dead_name n) () meta def is_name_dead (n : name) : tactic bool := do { witness : unit ← load_data $ mk_dead_name n, return true } <|> return false -- `get_with_status_tag_aux rn n` fails exactly when `rn ++ to_string n` does -- not exist. private meta def get_with_status_tag_aux (rn : name) : ℕ → tactic (ℕ × bool) | tag := do let n := apply_tag rn tag, present ← poke_data n, if ¬present then fail format!"{rn} never seen in cache!" else do is_dead ← is_name_dead n, if is_dead then get_with_status_tag_aux (tag + 1) <|> return (tag, false) else return (tag, true) -- Find the latest tag for the name `rn` and report whether it is alive. meta def get_tag_with_status (rn : name) : tactic (ℕ × bool) := get_with_status_tag_aux rn 0 meta def get_name (ns : name) : tactic name := do rn ← get_root_name ns, (tag, alive) ← get_tag_with_status rn <|> return (0, true), return $ apply_tag rn $ if alive then tag else tag + 1 meta def try_get_name (ns : name) : tactic name := do rn ← get_root_name ns, (tag, alive) ← get_tag_with_status rn, if alive then return $ apply_tag rn tag else fail format!"no cache for \"{ns}\"" meta def present (ns : name) : tactic bool := do rn ← get_root_name ns, (prod.snd <$> get_tag_with_status rn) <|> return false meta def clear (ns : name) : tactic unit := do { n ← try_get_name ns, kill_name n } <|> skip end def_local end internal open internal /-- This scope propogates the cache within a `begin ... end` or `by` block and its decendants. -/ meta def cache_scope.block_local : cache_scope := ⟨ block_local.get_name, block_local.try_get_name, block_local.present, block_local.clear ⟩ /-- This scope propogates the cache within an entire `def`/`lemma`. -/ meta def cache_scope.def_local : cache_scope := ⟨ def_local.get_name, def_local.try_get_name, def_local.present, def_local.clear ⟩ open cache_scope /-- Asks whether the namespace `ns` currently has a value-in-cache. -/ meta def present (ns : name) (s : cache_scope := block_local) : tactic bool := s.present ns /-- Clear cache associated to namespace `ns`. -/ meta def clear (ns : name) (s : cache_scope := block_local) : tactic unit := s.clear ns /-- Gets the (optionally present) value-in-cache for `ns`. -/ meta def get (ns : name) (α : Type) [reflected α] [has_reflect α] (s : cache_scope := block_local) : tactic (option α) := do dn ← some <$> s.try_get_name ns <|> return none, match dn with | none := return none | some dn := some <$> load_data dn end -- Note: we can't just use `<|>` on `load_data` since it will fail -- when a cached value is not present *as well as* when the type of -- `α` is just wrong. end local_cache open local_cache local_cache.internal /-- Using the namespace `ns` as its key, when called for the first time `run_once ns t` runs `t`, then saves and returns the result. Upon subsequent invocations in the same tactic block, with the scope of the caching being inherited by child tactic blocks) we return the cached result directly. You can configure the cached scope to be entire `def`/`lemma`s changing the optional cache_scope argument to `cache_scope.def_local`. Note: the caches backing each scope are different. If `α` is just `unit`, this means we just run `t` once each tactic block. -/ meta def run_once {α : Type} [reflected α] [has_reflect α] (ns : name) (t : tactic α) (s : cache_scope := cache_scope.block_local) : tactic α := s.get_name ns >>= run_once_under_name t end tactic
c42db3c086a19c1c35719005159c2863379de61e
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/polynomial/bernstein.lean
cd545d889dc7f3f602b4175e4ecb1fe76c710582
[ "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
16,839
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.polynomial.derivative import data.nat.choose.sum import ring_theory.polynomial.pochhammer import data.polynomial.algebra_map import linear_algebra.linear_independent import data.mv_polynomial.pderiv /-! # Bernstein polynomials The definition of the Bernstein polynomials ``` bernstein_polynomial (R : Type*) [comm_ring R] (n ν : ℕ) : R[X] := (choose n ν) * X^ν * (1 - X)^(n - ν) ``` and the fact that for `ν : fin (n+1)` these are linearly independent over `ℚ`. We prove the basic identities * `(finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1` * `(finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X` * `(finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2` ## Notes See also `analysis.special_functions.bernstein`, which defines the Bernstein approximations of a continuous function `f : C([0,1], ℝ)`, and shows that these converge uniformly to `f`. -/ noncomputable theory open nat (choose) open polynomial (X) open_locale big_operators polynomial variables (R : Type*) [comm_ring R] /-- `bernstein_polynomial R n ν` is `(choose n ν) * X^ν * (1 - X)^(n - ν)`. Although the coefficients are integers, it is convenient to work over an arbitrary commutative ring. -/ def bernstein_polynomial (n ν : ℕ) : R[X] := choose n ν * X^ν * (1 - X)^(n - ν) example : bernstein_polynomial ℤ 3 2 = 3 * X^2 - 3 * X^3 := begin norm_num [bernstein_polynomial, choose], ring, end namespace bernstein_polynomial lemma eq_zero_of_lt {n ν : ℕ} (h : n < ν) : bernstein_polynomial R n ν = 0 := by simp [bernstein_polynomial, nat.choose_eq_zero_of_lt h] section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map (f : R →+* S) (n ν : ℕ) : (bernstein_polynomial R n ν).map f = bernstein_polynomial S n ν := by simp [bernstein_polynomial] end lemma flip (n ν : ℕ) (h : ν ≤ n) : (bernstein_polynomial R n ν).comp (1-X) = bernstein_polynomial R n (n-ν) := by simp [bernstein_polynomial, h, tsub_tsub_assoc, mul_right_comm] lemma flip' (n ν : ℕ) (h : ν ≤ n) : bernstein_polynomial R n ν = (bernstein_polynomial R n (n-ν)).comp (1-X) := by simp [←flip _ _ _ h, polynomial.comp_assoc] lemma eval_at_0 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 0 = if ν = 0 then 1 else 0 := begin rw [bernstein_polynomial], split_ifs, { subst h, simp, }, { simp [zero_pow (nat.pos_of_ne_zero h)], }, end lemma eval_at_1 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 1 = if ν = n then 1 else 0 := begin rw [bernstein_polynomial], split_ifs, { subst h, simp, }, { obtain w | w := (n - ν).eq_zero_or_pos, { simp [nat.choose_eq_zero_of_lt ((tsub_eq_zero_iff_le.mp w).lt_of_ne (ne.symm h))] }, { simp [zero_pow w] } }, end. lemma derivative_succ_aux (n ν : ℕ) : (bernstein_polynomial R (n+1) (ν+1)).derivative = (n+1) * (bernstein_polynomial R n ν - bernstein_polynomial R n (ν + 1)) := begin rw [bernstein_polynomial], suffices : ↑((n + 1).choose (ν + 1)) * (↑(ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -(↑((n + 1).choose (ν + 1)) * X ^ (ν + 1) * (↑(n - ν) * (1 - X) ^ (n - ν - 1))) = ↑(n + 1) * (↑(n.choose ν) * X ^ ν * (1 - X) ^ (n - ν) - ↑(n.choose (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1))), { simpa only [polynomial.derivative_pow, ←sub_eq_add_neg, nat.succ_sub_succ_eq_sub, polynomial.derivative_mul, polynomial.derivative_nat_cast, zero_mul, nat.cast_add, algebra_map.coe_one, polynomial.derivative_X, mul_one, zero_add, polynomial.derivative_sub, polynomial.derivative_one, zero_sub, mul_neg, nat.sub_zero, ← nat.cast_succ, polynomial.C_eq_nat_cast], }, conv_rhs { rw mul_sub, }, -- We'll prove the two terms match up separately. refine congr (congr_arg has_sub.sub _) _, { simp only [←mul_assoc], refine congr (congr_arg (*) (congr (congr_arg (*) _) rfl)) rfl, -- Now it's just about binomial coefficients exact_mod_cast congr_arg (λ m : ℕ, (m : R[X])) (nat.succ_mul_choose_eq n ν).symm, }, { rw [← tsub_add_eq_tsub_tsub, ← mul_assoc, ← mul_assoc], congr' 1, rw [mul_comm, ←mul_assoc, ←mul_assoc], congr' 1, norm_cast, congr' 1, convert (nat.choose_mul_succ_eq n (ν + 1)).symm using 1, { convert mul_comm _ _ using 2, simp, }, { apply mul_comm, }, }, end lemma derivative_succ (n ν : ℕ) : (bernstein_polynomial R n (ν+1)).derivative = n * (bernstein_polynomial R (n-1) ν - bernstein_polynomial R (n-1) (ν+1)) := begin cases n, { simp [bernstein_polynomial], }, { rw nat.cast_succ, apply derivative_succ_aux, } end lemma derivative_zero (n : ℕ) : (bernstein_polynomial R n 0).derivative = -n * bernstein_polynomial R (n-1) 0 := by simp [bernstein_polynomial, polynomial.derivative_pow] lemma iterate_derivative_at_0_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 0 = 0 := begin cases ν, { rintro ⟨⟩, }, { rw nat.lt_succ_iff, induction k with k ih generalizing n ν, { simp [eval_at_0], }, { simp only [derivative_succ, int.coe_nat_eq_zero, mul_eq_zero, function.comp_app, function.iterate_succ, polynomial.iterate_derivative_sub, polynomial.iterate_derivative_nat_cast_mul, polynomial.eval_mul, polynomial.eval_nat_cast, polynomial.eval_sub], intro h, apply mul_eq_zero_of_right, rw [ih _ _ (nat.le_of_succ_le h), sub_zero], convert ih _ _ (nat.pred_le_pred h), exact (nat.succ_pred_eq_of_pos (k.succ_pos.trans_le h)).symm } }, end @[simp] lemma iterate_derivative_succ_at_0_eq_zero (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n (ν+1))).eval 0 = 0 := iterate_derivative_at_0_eq_zero_of_lt R n (lt_add_one ν) open polynomial @[simp] lemma iterate_derivative_at_0 (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 = (pochhammer R ν).eval (n - (ν - 1) : ℕ) := begin by_cases h : ν ≤ n, { induction ν with ν ih generalizing n h, { simp [eval_at_0], }, { have h' : ν ≤ n-1 := le_tsub_of_add_le_right h, simp only [derivative_succ, ih (n-1) h', iterate_derivative_succ_at_0_eq_zero, nat.succ_sub_succ_eq_sub, tsub_zero, sub_zero, iterate_derivative_sub, iterate_derivative_nat_cast_mul, eval_one, eval_mul, eval_add, eval_sub, eval_X, eval_comp, eval_nat_cast, function.comp_app, function.iterate_succ, pochhammer_succ_left], obtain rfl | h'' := ν.eq_zero_or_pos, { simp }, { have : n - 1 - (ν - 1) = n - ν, { rw ←nat.succ_le_iff at h'', rw [← tsub_add_eq_tsub_tsub, add_comm, tsub_add_cancel_of_le h''] }, rw [this, pochhammer_eval_succ], rw_mod_cast tsub_add_cancel_of_le (h'.trans n.pred_le) } } }, { simp only [not_le] at h, rw [tsub_eq_zero_iff_le.mpr (nat.le_pred_of_lt h), eq_zero_of_lt R h], simp [pos_iff_ne_zero.mp (pos_of_gt h)] }, end lemma iterate_derivative_at_0_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 ≠ 0 := begin simp only [int.coe_nat_eq_zero, bernstein_polynomial.iterate_derivative_at_0, ne.def, nat.cast_eq_zero], simp only [←pochhammer_eval_cast], norm_cast, apply ne_of_gt, obtain rfl|h' := nat.eq_zero_or_pos ν, { simp, }, { rw ← nat.succ_pred_eq_of_pos h' at h, exact pochhammer_pos _ _ (tsub_pos_of_lt (nat.lt_of_succ_le h)) } end /-! Rather than redoing the work of evaluating the derivatives at 1, we use the symmetry of the Bernstein polynomials. -/ lemma iterate_derivative_at_1_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < n - ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 1 = 0 := begin intro w, rw flip' _ _ _ (tsub_pos_iff_lt.mp (pos_of_gt w)).le, simp [polynomial.eval_comp, iterate_derivative_at_0_eq_zero_of_lt R n w], end @[simp] lemma iterate_derivative_at_1 (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 = (-1)^(n-ν) * (pochhammer R (n - ν)).eval (ν + 1) := begin rw flip' _ _ _ h, simp [polynomial.eval_comp, h], obtain rfl | h' := h.eq_or_lt, { simp, }, { congr, norm_cast, rw [← tsub_add_eq_tsub_tsub, tsub_tsub_cancel_of_le (nat.succ_le_iff.mpr h')] }, end lemma iterate_derivative_at_1_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 ≠ 0 := begin rw [bernstein_polynomial.iterate_derivative_at_1 _ _ _ h, ne.def, neg_one_pow_mul_eq_zero_iff, ←nat.cast_succ, ←pochhammer_eval_cast, ←nat.cast_zero, nat.cast_inj], exact (pochhammer_pos _ _ (nat.succ_pos ν)).ne', end open submodule lemma linear_independent_aux (n k : ℕ) (h : k ≤ n + 1): linear_independent ℚ (λ ν : fin k, bernstein_polynomial ℚ n ν) := begin induction k with k ih, { apply linear_independent_empty_type, }, { apply linear_independent_fin_succ'.mpr, fsplit, { exact ih (le_of_lt h), }, { -- The actual work! -- We show that the (n-k)-th derivative at 1 doesn't vanish, -- but vanishes for everything in the span. clear ih, simp only [nat.succ_eq_add_one, add_le_add_iff_right] at h, simp only [fin.coe_last, fin.init_def], dsimp, apply not_mem_span_of_apply_not_mem_span_image ((@polynomial.derivative ℚ _)^(n-k)), simp only [not_exists, not_and, submodule.mem_map, submodule.span_image], intros p m, apply_fun (polynomial.eval (1 : ℚ)), simp only [linear_map.pow_apply], -- The right hand side is nonzero, -- so it will suffice to show the left hand side is always zero. suffices : (polynomial.derivative^[n-k] p).eval 1 = 0, { rw [this], exact (iterate_derivative_at_1_ne_zero ℚ n k h).symm, }, apply span_induction m, { simp, rintro ⟨a, w⟩, simp only [fin.coe_mk], rw [iterate_derivative_at_1_eq_zero_of_lt ℚ n ((tsub_lt_tsub_iff_left_of_le h).mpr w)] }, { simp, }, { intros x y hx hy, simp [hx, hy], }, { intros a x h, simp [h], }, }, }, end /-- The Bernstein polynomials are linearly independent. We prove by induction that the collection of `bernstein_polynomial n ν` for `ν = 0, ..., k` are linearly independent. The inductive step relies on the observation that the `(n-k)`-th derivative, evaluated at 1, annihilates `bernstein_polynomial n ν` for `ν < k`, but has a nonzero value at `ν = k`. -/ lemma linear_independent (n : ℕ) : linear_independent ℚ (λ ν : fin (n+1), bernstein_polynomial ℚ n ν) := linear_independent_aux n (n+1) le_rfl lemma sum (n : ℕ) : ∑ ν in finset.range (n + 1), bernstein_polynomial R n ν = 1 := calc ∑ ν in finset.range (n + 1), bernstein_polynomial R n ν = (X + (1 - X)) ^ n : by { rw add_pow, simp only [bernstein_polynomial, mul_comm, mul_assoc, mul_left_comm] } ... = 1 : by simp open polynomial open mv_polynomial lemma sum_smul (n : ℕ) : ∑ ν in finset.range (n + 1), ν • bernstein_polynomial R n ν = n • X := begin -- We calculate the `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { rw [pderiv_X], refl, }, have pderiv_tt_y : pderiv tt y = 0, { rw [pderiv_X], refl, }, let e : bool → R[X] := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: transitivity aeval e (pderiv tt ((x + y) ^ n)) * X, -- On the left hand side we'll use the binomial theorem, then simplify. { -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, k • bernstein_polynomial R n k = ↑k * polynomial.X ^ (k - 1) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X, { rintro (_|k), { simp, }, { rw [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, rw [add_pow, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: refine finset.sum_congr rfl (λ k hk, (w k).trans _), simp only [pderiv_tt_x, pderiv_tt_y, algebra.id.smul_eq_mul, nsmul_eq_mul, e, bool.cond_tt, bool.cond_ff, add_zero, mul_one, mul_zero, smul_zero, mv_polynomial.aeval_X, mv_polynomial.pderiv_mul, derivation.leibniz_pow, derivation.map_coe_nat, map_nat_cast, map_pow, map_mul], }, { rw [(pderiv tt).leibniz_pow, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp only [algebra.id.smul_eq_mul, nsmul_eq_mul, map_nat_cast, map_pow, map_add, map_mul, e, bool.cond_tt, bool.cond_ff, mv_polynomial.aeval_X, add_sub_cancel'_right, one_pow, add_zero, mul_one] }, end lemma sum_mul_smul (n : ℕ) : ∑ ν in finset.range (n + 1), (ν * (ν-1)) • bernstein_polynomial R n ν = (n * (n-1)) • X^2 := begin -- We calculate the second `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { rw [pderiv_X], refl, }, have pderiv_tt_y : pderiv tt y = 0, { rw [pderiv_X], refl, }, let e : bool → R[X] := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the second `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: transitivity aeval e (pderiv tt (pderiv tt ((x + y) ^ n))) * X ^ 2, -- On the left hand side we'll use the binomial theorem, then simplify. { -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, (k * (k-1)) • bernstein_polynomial R n k = ↑(n.choose k) * ((1 - polynomial.X) ^ (n - k) * (↑k * (↑(k-1) * polynomial.X ^ (k - 1 - 1)))) * polynomial.X^2, { rintro (_|_|k), { simp, }, { simp, }, { rw [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, rw [add_pow, (pderiv tt).map_sum, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: refine finset.sum_congr rfl (λ k hk, (w k).trans _), simp only [pderiv_tt_x, pderiv_tt_y, algebra.id.smul_eq_mul, nsmul_eq_mul, e, bool.cond_tt, bool.cond_ff, add_zero, zero_add, mul_zero, smul_zero, mul_one, mv_polynomial.aeval_X, mv_polynomial.pderiv_X_self, mv_polynomial.pderiv_X_of_ne, derivation.leibniz_pow, derivation.leibniz, derivation.map_coe_nat, map_nat_cast, map_pow, map_mul, map_add], }, -- On the right hand side, we'll just simplify. { simp only [pderiv_one, pderiv_mul, (pderiv _).leibniz_pow, (pderiv _).map_coe_nat, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y, algebra.id.smul_eq_mul, add_zero, mul_one, derivation.map_smul_of_tower, map_nsmul, map_pow, map_add, e, bool.cond_tt, bool.cond_ff, mv_polynomial.aeval_X, add_sub_cancel'_right, one_pow, smul_smul, smul_one_mul] }, end /-- A certain linear combination of the previous three identities, which we'll want later. -/ lemma variance (n : ℕ) : ∑ ν in finset.range (n+1), (n • polynomial.X - ν)^2 * bernstein_polynomial R n ν = n • polynomial.X * (1 - polynomial.X) := begin have p : (finset.range (n+1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) + (1 - (2 * n) • polynomial.X) * (finset.range (n+1)).sum (λ ν, ν • bernstein_polynomial R n ν) + (n^2 • X^2) * (finset.range (n+1)).sum (λ ν, bernstein_polynomial R n ν) = _ := rfl, conv at p { to_lhs, rw [finset.mul_sum, finset.mul_sum, ←finset.sum_add_distrib, ←finset.sum_add_distrib], simp only [←nat_cast_mul], simp only [←mul_assoc], simp only [←add_mul], }, conv at p { to_rhs, rw [sum, sum_smul, sum_mul_smul, ←nat_cast_mul], }, calc _ = _ : finset.sum_congr rfl (λ k m, _) ... = _ : p ... = _ : _, { congr' 1, simp only [←nat_cast_mul] with push_cast, cases k; { simp, ring, }, }, { simp only [←nat_cast_mul] with push_cast, cases n, { simp, }, { simp, ring, }, }, end end bernstein_polynomial
36ebd97bbf5373f5e8fdc699837908e12212dc45
4fa161becb8ce7378a709f5992a594764699e268
/src/data/real/cardinality.lean
e029837a3c492297c2fa20febe5801882b8e86d2
[ "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
4,897
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The cardinality of the reals. -/ import set_theory.ordinal import analysis.specific_limits import data.rat.denumerable open nat set noncomputable theory namespace cardinal variables {c : ℝ} {f g : ℕ → bool} {n : ℕ} def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n := by simp [cantor_function_aux, h] @[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 := by simp [cantor_function_aux, h] lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n := by { cases h' : f n; simp [h'], apply pow_nonneg h } lemma cantor_function_aux_eq (h : f n = g n) : cantor_function_aux c f n = cantor_function_aux c g n := by simp [cantor_function_aux, h] lemma cantor_function_aux_succ (f : ℕ → bool) : (λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n := by { ext n, cases h : f (n + 1); simp [h, pow_succ] } lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : summable (cantor_function_aux c f) := begin apply (summable_geometric_of_lt_1 h1 h2).summable_of_eq_zero_or_self, intro n, cases h : f n; simp [h] end def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑' n, cantor_function_aux c f n lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) : cantor_function c f ≤ cantor_function c g := begin apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2), intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1], replace h3 : g n = tt := h3 n h, simp [h, h3] end lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) := begin rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)], rw [cantor_function_aux_succ, tsum_mul_left _ (summable_cantor_function _ h1 h2)], refl end lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool} (hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) : cantor_function c f < cantor_function c g := begin have h3 : c < 1, { apply lt_trans h2, norm_num }, induction n with n ih generalizing f g, { let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n, have hf_max : ∀n, f n → f_max n, { intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl }, let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n, have hg_min : ∀n, g_min n → g n, { intros n hn, cases n, rw [gn], apply rfl, contradiction }, apply lt_of_le_of_lt (cantor_function_le (le_of_lt h1) h3 hf_max), apply lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min), have : c / (1 - c) < 1, { rw [div_lt_one_iff_lt, lt_sub_iff_add_lt], { convert add_lt_add h2 h2, norm_num }, rwa sub_pos }, convert this, { rw [cantor_function_succ _ (le_of_lt h1) h3, div_eq_mul_inv, ←tsum_geometric_of_lt_1 (le_of_lt h1) h3], apply zero_add }, { apply tsum_eq_single 0, intros n hn, cases n, contradiction, refl, apply_instance }}, rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3], rw [hn 0 $ zero_lt_succ n], apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ succ_lt_succ hk) fn gn end lemma cantor_function_injective (h1 : 0 < c) (h2 : c < 1 / 2) : function.injective (cantor_function c) := begin intros f g hfg, classical, by_contra h, revert hfg, have : ∃n, f n ≠ g n, { rw [←not_forall], intro h', apply h, ext, apply h' }, let n := nat.find this, have hn : ∀ (k : ℕ), k < n → f k = g k, { intros k hk, apply of_not_not, exact nat.find_min this hk }, cases fn : f n, { apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _, apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this }, { apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn, apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this } end lemma mk_real : mk ℝ = 2 ^ omega.{0} := begin apply le_antisymm, { dsimp [real], apply le_trans mk_quotient_le, apply le_trans (mk_subtype_le _), rw [←power_def, mk_nat, mk_rat, power_self_eq (le_refl _)] }, { convert mk_le_of_injective (cantor_function_injective _ _), rw [←power_def, mk_bool, mk_nat], exact 1 / 3, norm_num, norm_num } end lemma not_countable_real : ¬ countable (set.univ : set ℝ) := by { rw [countable_iff, not_le, mk_univ, mk_real], apply cantor } end cardinal
a021d6d58cb1eaebca89f4de2bb1c22d61e1767f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebraic_geometry/structure_sheaf.lean
3d9efa691ae631e6cb4ba8d3b8d13c76d9d072c3
[ "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
48,780
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import algebraic_geometry.prime_spectrum.basic import algebra.category.CommRing.colimits import algebra.category.CommRing.limits import topology.sheaves.local_predicate import ring_theory.localization import ring_theory.subring.basic /-! # The structure sheaf on `prime_spectrum R`. We define the structure sheaf on `Top.of (prime_spectrum R)`, for a commutative ring `R` and prove basic properties about it. We define this as a subsheaf of the sheaf of dependent functions into the localizations, cut out by the condition that the function must be locally equal to a ratio of elements of `R`. Because the condition "is equal to a fraction" passes to smaller open subsets, the subset of functions satisfying this condition is automatically a subpresheaf. Because the condition "is locally equal to a fraction" is local, it is also a subsheaf. (It may be helpful to refer back to `topology.sheaves.sheaf_of_functions`, where we show that dependent functions into any type family form a sheaf, and also `topology.sheaves.local_predicate`, where we characterise the predicates which pick out sub-presheaves and sub-sheaves of these sheaves.) We also set up the ring structure, obtaining `structure_sheaf R : sheaf CommRing (Top.of (prime_spectrum R))`. We then construct two basic isomorphisms, relating the structure sheaf to the underlying ring `R`. First, `structure_sheaf.stalk_iso` gives an isomorphism between the stalk of the structure sheaf at a point `p` and the localization of `R` at the prime ideal `p`. Second, `structure_sheaf.basic_open_iso` gives an isomorphism between the structure sheaf on `basic_open f` and the localization of `R` at the submonoid of powers of `f`. ## References * [Robin Hartshorne, *Algebraic Geometry*][Har77] -/ universe u noncomputable theory variables (R : Type u) [comm_ring R] open Top open topological_space open category_theory open opposite namespace algebraic_geometry /-- The prime spectrum, just as a topological space. -/ def prime_spectrum.Top : Top := Top.of (prime_spectrum R) namespace structure_sheaf /-- The type family over `prime_spectrum R` consisting of the localization over each point. -/ @[derive [comm_ring, local_ring]] def localizations (P : prime_spectrum.Top R) : Type u := localization.at_prime P.as_ideal instance (P : prime_spectrum.Top R) : inhabited (localizations R P) := ⟨1⟩ instance (U : opens (prime_spectrum.Top R)) (x : U) : algebra R (localizations R x) := localization.algebra instance (U : opens (prime_spectrum.Top R)) (x : U) : is_localization.at_prime (localizations R x) (x : prime_spectrum.Top R).as_ideal := localization.is_localization variables {R} /-- The predicate saying that a dependent function on an open `U` is realised as a fixed fraction `r / s` in each of the stalks (which are localizations at various prime ideals). -/ def is_fraction {U : opens (prime_spectrum.Top R)} (f : Π x : U, localizations R x) : Prop := ∃ (r s : R), ∀ x : U, ¬ (s ∈ x.1.as_ideal) ∧ f x * algebra_map _ _ s = algebra_map _ _ r lemma is_fraction.eq_mk' {U : opens (prime_spectrum.Top R)} {f : Π x : U, localizations R x} (hf : is_fraction f) : ∃ (r s : R) , ∀ x : U, ∃ (hs : s ∉ x.1.as_ideal), f x = is_localization.mk' (localization.at_prime _) r (⟨s, hs⟩ : (x : prime_spectrum.Top R).as_ideal.prime_compl) := begin rcases hf with ⟨r, s, h⟩, refine ⟨r, s, λ x, ⟨(h x).1, (is_localization.mk'_eq_iff_eq_mul.mpr _).symm⟩⟩, exact (h x).2.symm, end variables (R) /-- The predicate `is_fraction` is "prelocal", in the sense that if it holds on `U` it holds on any open subset `V` of `U`. -/ def is_fraction_prelocal : prelocal_predicate (localizations R) := { pred := λ U f, is_fraction f, res := by { rintro V U i f ⟨r, s, w⟩, exact ⟨r, s, λ x, w (i x)⟩ } } /-- We will define the structure sheaf as the subsheaf of all dependent functions in `Π x : U, localizations R x` consisting of those functions which can locally be expressed as a ratio of (the images in the localization of) elements of `R`. Quoting Hartshorne: For an open set $U ⊆ Spec A$, we define $𝒪(U)$ to be the set of functions $s : U → ⨆_{𝔭 ∈ U} A_𝔭$, such that $s(𝔭) ∈ A_𝔭$ for each $𝔭$, and such that $s$ is locally a quotient of elements of $A$: to be precise, we require that for each $𝔭 ∈ U$, there is a neighborhood $V$ of $𝔭$, contained in $U$, and elements $a, f ∈ A$, such that for each $𝔮 ∈ V, f ∉ 𝔮$, and $s(𝔮) = a/f$ in $A_𝔮$. Now Hartshorne had the disadvantage of not knowing about dependent functions, so we replace his circumlocution about functions into a disjoint union with `Π x : U, localizations x`. -/ def is_locally_fraction : local_predicate (localizations R) := (is_fraction_prelocal R).sheafify @[simp] lemma is_locally_fraction_pred {U : opens (prime_spectrum.Top R)} (f : Π x : U, localizations R x) : (is_locally_fraction R).pred f = ∀ x : U, ∃ (V) (m : x.1 ∈ V) (i : V ⟶ U), ∃ (r s : R), ∀ y : V, ¬ (s ∈ y.1.as_ideal) ∧ f (i y : U) * algebra_map _ _ s = algebra_map _ _ r := rfl /-- The functions satisfying `is_locally_fraction` form a subring. -/ def sections_subring (U : (opens (prime_spectrum.Top R))ᵒᵖ) : subring (Π x : unop U, localizations R x) := { carrier := { f | (is_locally_fraction R).pred f }, zero_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 0, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, one_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 1, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, add_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * sb + rb * sa, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [add_mul, ring_hom.map_add, pi.add_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_assoc], congr' 2, rw [mul_comm], refl, } end, neg_mem' := begin intros a ha x, rcases ha x with ⟨V, m, i, r, s, w⟩, refine ⟨V, m, i, -r, s, _⟩, intro y, rcases w y with ⟨nm, w⟩, fsplit, { exact nm, }, { simp only [ring_hom.map_neg, pi.neg_apply], erw [←w], simp only [neg_mul_eq_neg_mul_symm], } end, mul_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * rb, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [pi.mul_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_left_comm, mul_assoc, mul_comm], refl, } end, } end structure_sheaf open structure_sheaf /-- The structure sheaf (valued in `Type`, not yet `CommRing`) is the subsheaf consisting of functions satisfying `is_locally_fraction`. -/ def structure_sheaf_in_Type : sheaf (Type u) (prime_spectrum.Top R):= subsheaf_to_Types (is_locally_fraction R) instance comm_ring_structure_sheaf_in_Type_obj (U : (opens (prime_spectrum.Top R))ᵒᵖ) : comm_ring ((structure_sheaf_in_Type R).1.obj U) := (sections_subring R U).to_comm_ring open _root_.prime_spectrum /-- The structure presheaf, valued in `CommRing`, constructed by dressing up the `Type` valued structure presheaf. -/ @[simps] def structure_presheaf_in_CommRing : presheaf CommRing (prime_spectrum.Top R) := { obj := λ U, CommRing.of ((structure_sheaf_in_Type R).1.obj U), map := λ U V i, { to_fun := ((structure_sheaf_in_Type R).1.map i), map_zero' := rfl, map_add' := λ x y, rfl, map_one' := rfl, map_mul' := λ x y, rfl, }, } /-- Some glue, verifying that that structure presheaf valued in `CommRing` agrees with the `Type` valued structure presheaf. -/ def structure_presheaf_comp_forget : structure_presheaf_in_CommRing R ⋙ (forget CommRing) ≅ (structure_sheaf_in_Type R).1 := nat_iso.of_components (λ U, iso.refl _) (by tidy) open Top.presheaf /-- The structure sheaf on $Spec R$, valued in `CommRing`. This is provided as a bundled `SheafedSpace` as `Spec.SheafedSpace R` later. -/ def structure_sheaf : sheaf CommRing (prime_spectrum.Top R) := ⟨structure_presheaf_in_CommRing R, -- We check the sheaf condition under `forget CommRing`. (is_sheaf_iff_is_sheaf_comp _ _).mpr (is_sheaf_of_iso (structure_presheaf_comp_forget R).symm (structure_sheaf_in_Type R).property)⟩ namespace structure_sheaf @[simp] lemma res_apply (U V : opens (prime_spectrum.Top R)) (i : V ⟶ U) (s : (structure_sheaf R).1.obj (op U)) (x : V) : ((structure_sheaf R).1.map i.op s).1 x = (s.1 (i x) : _) := rfl /- Notation in this comment X = Spec R OX = structure sheaf In the following we construct an isomorphism between OX_p and R_p given any point p corresponding to a prime ideal in R. We do this via 8 steps: 1. def const (f g : R) (V) (hv : V ≤ D_g) : OX(V) [for api] 2. def to_open (U) : R ⟶ OX(U) 3. [2] def to_stalk (p : Spec R) : R ⟶ OX_p 4. [2] def to_basic_open (f : R) : R_f ⟶ OX(D_f) 5. [3] def localization_to_stalk (p : Spec R) : R_p ⟶ OX_p 6. def open_to_localization (U) (p) (hp : p ∈ U) : OX(U) ⟶ R_p 7. [6] def stalk_to_fiber_ring_hom (p : Spec R) : OX_p ⟶ R_p 8. [5,7] def stalk_iso (p : Spec R) : OX_p ≅ R_p In the square brackets we list the dependencies of a construction on the previous steps. -/ /-- The section of `structure_sheaf R` on an open `U` sending each `x ∈ U` to the element `f/g` in the localization of `R` at `x`. -/ def const (f g : R) (U : opens (prime_spectrum.Top R)) (hu : ∀ x ∈ U, g ∈ (x : prime_spectrum.Top R).as_ideal.prime_compl) : (structure_sheaf R).1.obj (op U) := ⟨λ x, is_localization.mk' _ f ⟨g, hu x x.2⟩, λ x, ⟨U, x.2, 𝟙 _, f, g, λ y, ⟨hu y y.2, is_localization.mk'_spec _ _ _⟩⟩⟩ @[simp] lemma const_apply (f g : R) (U : opens (prime_spectrum.Top R)) (hu : ∀ x ∈ U, g ∈ (x : prime_spectrum.Top R).as_ideal.prime_compl) (x : U) : (const R f g U hu).1 x = is_localization.mk' _ f ⟨g, hu x x.2⟩ := rfl lemma const_apply' (f g : R) (U : opens (prime_spectrum.Top R)) (hu : ∀ x ∈ U, g ∈ (x : prime_spectrum.Top R).as_ideal.prime_compl) (x : U) (hx : g ∈ (as_ideal (x : prime_spectrum.Top R)).prime_compl) : (const R f g U hu).1 x = is_localization.mk' _ f ⟨g, hx⟩ := rfl lemma exists_const (U) (s : (structure_sheaf R).1.obj (op U)) (x : prime_spectrum.Top R) (hx : x ∈ U) : ∃ (V : opens (prime_spectrum.Top R)) (hxV : x ∈ V) (i : V ⟶ U) (f g : R) hg, const R f g V hg = (structure_sheaf R).1.map i.op s := let ⟨V, hxV, iVU, f, g, hfg⟩ := s.2 ⟨x, hx⟩ in ⟨V, hxV, iVU, f, g, λ y hyV, (hfg ⟨y, hyV⟩).1, subtype.eq $ funext $ λ y, is_localization.mk'_eq_iff_eq_mul.2 $ eq.symm $ (hfg y).2⟩ @[simp] lemma res_const (f g : R) (U hu V hv i) : (structure_sheaf R).1.map i (const R f g U hu) = const R f g V hv := rfl lemma res_const' (f g : R) (V hv) : (structure_sheaf R).1.map (hom_of_le hv).op (const R f g (basic_open g) (λ _, id)) = const R f g V hv := rfl lemma const_zero (f : R) (U hu) : const R 0 f U hu = 0 := subtype.eq $ funext $ λ x, is_localization.mk'_eq_iff_eq_mul.2 $ by erw [ring_hom.map_zero, subtype.val_eq_coe, subring.coe_zero, pi.zero_apply, zero_mul] lemma const_self (f : R) (U hu) : const R f f U hu = 1 := subtype.eq $ funext $ λ x, is_localization.mk'_self _ _ lemma const_one (U) : const R 1 1 U (λ p _, submonoid.one_mem _) = 1 := const_self R 1 U _ lemma const_add (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ + const R f₂ g₂ U hu₂ = const R (f₁ * g₂ + f₂ * g₁) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert is_localization.mk'_add f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_mul (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ * const R f₂ g₂ U hu₂ = const R (f₁ * f₂) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert is_localization.mk'_mul _ f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_ext {f₁ f₂ g₁ g₂ : R} {U hu₁ hu₂} (h : f₁ * g₂ = f₂ * g₁) : const R f₁ g₁ U hu₁ = const R f₂ g₂ U hu₂ := subtype.eq $ funext $ λ x, is_localization.mk'_eq_of_eq h.symm lemma const_congr {f₁ f₂ g₁ g₂ : R} {U hu} (hf : f₁ = f₂) (hg : g₁ = g₂) : const R f₁ g₁ U hu = const R f₂ g₂ U (hg ▸ hu) := by substs hf hg lemma const_mul_rev (f g : R) (U hu₁ hu₂) : const R f g U hu₁ * const R g f U hu₂ = 1 := by rw [const_mul, const_congr R rfl (mul_comm g f), const_self] lemma const_mul_cancel (f g₁ g₂ : R) (U hu₁ hu₂) : const R f g₁ U hu₁ * const R g₁ g₂ U hu₂ = const R f g₂ U hu₂ := by { rw [const_mul, const_ext], rw mul_assoc } lemma const_mul_cancel' (f g₁ g₂ : R) (U hu₁ hu₂) : const R g₁ g₂ U hu₂ * const R f g₁ U hu₁ = const R f g₂ U hu₂ := by rw [mul_comm, const_mul_cancel] /-- The canonical ring homomorphism interpreting an element of `R` as a section of the structure sheaf. -/ def to_open (U : opens (prime_spectrum.Top R)) : CommRing.of R ⟶ (structure_sheaf R).1.obj (op U) := { to_fun := λ f, ⟨λ x, algebra_map R _ f, λ x, ⟨U, x.2, 𝟙 _, f, 1, λ y, ⟨(ideal.ne_top_iff_one _).1 y.1.2.1, by { rw [ring_hom.map_one, mul_one], refl } ⟩⟩⟩, map_one' := subtype.eq $ funext $ λ x, ring_hom.map_one _, map_mul' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_mul _ _ _, map_zero' := subtype.eq $ funext $ λ x, ring_hom.map_zero _, map_add' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_add _ _ _ } @[simp] lemma to_open_res (U V : opens (prime_spectrum.Top R)) (i : V ⟶ U) : to_open R U ≫ (structure_sheaf R).1.map i.op = to_open R V := rfl @[simp] lemma to_open_apply (U : opens (prime_spectrum.Top R)) (f : R) (x : U) : (to_open R U f).1 x = algebra_map _ _ f := rfl lemma to_open_eq_const (U : opens (prime_spectrum.Top R)) (f : R) : to_open R U f = const R f 1 U (λ x _, (ideal.ne_top_iff_one _).1 x.2.1) := subtype.eq $ funext $ λ x, eq.symm $ is_localization.mk'_one _ f /-- The canonical ring homomorphism interpreting an element of `R` as an element of the stalk of `structure_sheaf R` at `x`. -/ def to_stalk (x : prime_spectrum.Top R) : CommRing.of R ⟶ (structure_sheaf R).1.stalk x := (to_open R ⊤ ≫ (structure_sheaf R).1.germ ⟨x, ⟨⟩⟩ : _) @[simp] lemma to_open_germ (U : opens (prime_spectrum.Top R)) (x : U) : to_open R U ≫ (structure_sheaf R).1.germ x = to_stalk R x := by { rw [← to_open_res R ⊤ U (hom_of_le le_top : U ⟶ ⊤), category.assoc, presheaf.germ_res], refl } @[simp] lemma germ_to_open (U : opens (prime_spectrum.Top R)) (x : U) (f : R) : (structure_sheaf R).1.germ x (to_open R U f) = to_stalk R x f := by { rw ← to_open_germ, refl } lemma germ_to_top (x : prime_spectrum.Top R) (f : R) : (structure_sheaf R).1.germ (⟨x, trivial⟩ : (⊤ : opens (prime_spectrum.Top R))) (to_open R ⊤ f) = to_stalk R x f := rfl lemma is_unit_to_basic_open_self (f : R) : is_unit (to_open R (basic_open f) f) := is_unit_of_mul_eq_one _ (const R 1 f (basic_open f) (λ _, id)) $ by rw [to_open_eq_const, const_mul_rev] lemma is_unit_to_stalk (x : prime_spectrum.Top R) (f : x.as_ideal.prime_compl) : is_unit (to_stalk R x (f : R)) := by { erw ← germ_to_open R (basic_open (f : R)) ⟨x, f.2⟩ (f : R), exact ring_hom.is_unit_map _ (is_unit_to_basic_open_self R f) } /-- The canonical ring homomorphism from the localization of `R` at `p` to the stalk of the structure sheaf at the point `p`. -/ def localization_to_stalk (x : prime_spectrum.Top R) : CommRing.of (localization.at_prime x.as_ideal) ⟶ (structure_sheaf R).1.stalk x := show localization.at_prime x.as_ideal →+* _, from is_localization.lift (is_unit_to_stalk R x) @[simp] lemma localization_to_stalk_of (x : prime_spectrum.Top R) (f : R) : localization_to_stalk R x (algebra_map _ (localization _) f) = to_stalk R x f := is_localization.lift_eq _ f @[simp] lemma localization_to_stalk_mk' (x : prime_spectrum.Top R) (f : R) (s : (as_ideal x).prime_compl) : localization_to_stalk R x (is_localization.mk' _ f s : localization _) = (structure_sheaf R).1.germ (⟨x, s.2⟩ : basic_open (s : R)) (const R f s (basic_open s) (λ _, id)) := (is_localization.lift_mk'_spec _ _ _ _).2 $ by erw [← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← ring_hom.map_mul, to_open_eq_const, to_open_eq_const, const_mul_cancel'] /-- The ring homomorphism that takes a section of the structure sheaf of `R` on the open set `U`, implemented as a subtype of dependent functions to localizations at prime ideals, and evaluates the section on the point corresponding to a given prime ideal. -/ def open_to_localization (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) : (structure_sheaf R).1.obj (op U) ⟶ CommRing.of (localization.at_prime x.as_ideal) := { to_fun := λ s, (s.1 ⟨x, hx⟩ : _), map_one' := rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, map_add' := λ _ _, rfl } @[simp] lemma coe_open_to_localization (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) : (open_to_localization R U x hx : (structure_sheaf R).1.obj (op U) → localization.at_prime x.as_ideal) = (λ s, (s.1 ⟨x, hx⟩ : _)) := rfl lemma open_to_localization_apply (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) (s : (structure_sheaf R).1.obj (op U)) : open_to_localization R U x hx s = (s.1 ⟨x, hx⟩ : _) := rfl /-- The ring homomorphism from the stalk of the structure sheaf of `R` at a point corresponding to a prime ideal `p` to the localization of `R` at `p`, formed by gluing the `open_to_localization` maps. -/ def stalk_to_fiber_ring_hom (x : prime_spectrum.Top R) : (structure_sheaf R).1.stalk x ⟶ CommRing.of (localization.at_prime x.as_ideal) := limits.colimit.desc (((open_nhds.inclusion x).op) ⋙ (structure_sheaf R).1) { X := _, ι := { app := λ U, open_to_localization R ((open_nhds.inclusion _).obj (unop U)) x (unop U).2, } } @[simp] lemma germ_comp_stalk_to_fiber_ring_hom (U : opens (prime_spectrum.Top R)) (x : U) : (structure_sheaf R).1.germ x ≫ stalk_to_fiber_ring_hom R x = open_to_localization R U x x.2 := limits.colimit.ι_desc _ _ @[simp] lemma stalk_to_fiber_ring_hom_germ' (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) (s : (structure_sheaf R).1.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).1.germ ⟨x, hx⟩ s) = (s.1 ⟨x, hx⟩ : _) := ring_hom.ext_iff.1 (germ_comp_stalk_to_fiber_ring_hom R U ⟨x, hx⟩ : _) s @[simp] lemma stalk_to_fiber_ring_hom_germ (U : opens (prime_spectrum.Top R)) (x : U) (s : (structure_sheaf R).1.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).1.germ x s) = s.1 x := by { cases x, exact stalk_to_fiber_ring_hom_germ' R U _ _ _ } @[simp] lemma to_stalk_comp_stalk_to_fiber_ring_hom (x : prime_spectrum.Top R) : to_stalk R x ≫ stalk_to_fiber_ring_hom R x = (algebra_map _ _ : R →+* localization _) := by { erw [to_stalk, category.assoc, germ_comp_stalk_to_fiber_ring_hom], refl } @[simp] lemma stalk_to_fiber_ring_hom_to_stalk (x : prime_spectrum.Top R) (f : R) : stalk_to_fiber_ring_hom R x (to_stalk R x f) = algebra_map _ (localization _) f := ring_hom.ext_iff.1 (to_stalk_comp_stalk_to_fiber_ring_hom R x) _ /-- The ring isomorphism between the stalk of the structure sheaf of `R` at a point `p` corresponding to a prime ideal in `R` and the localization of `R` at `p`. -/ @[simps] def stalk_iso (x : prime_spectrum.Top R) : (structure_sheaf R).1.stalk x ≅ CommRing.of (localization.at_prime x.as_ideal) := { hom := stalk_to_fiber_ring_hom R x, inv := localization_to_stalk R x, hom_inv_id' := (structure_sheaf R).1.stalk_hom_ext $ λ U hxU, begin ext s, simp only [comp_apply], rw [id_apply, stalk_to_fiber_ring_hom_germ'], obtain ⟨V, hxV, iVU, f, g, hg, hs⟩ := exists_const _ _ s x hxU, erw [← res_apply R U V iVU s ⟨x, hxV⟩, ← hs, const_apply, localization_to_stalk_mk'], refine (structure_sheaf R).1.germ_ext V hxV (hom_of_le hg) iVU _, erw [← hs, res_const'] end, inv_hom_id' := @is_localization.ring_hom_ext R _ x.as_ideal.prime_compl (localization.at_prime x.as_ideal) _ _ (localization.at_prime x.as_ideal) _ _ (ring_hom.comp (stalk_to_fiber_ring_hom R x) (localization_to_stalk R x)) (ring_hom.id (localization.at_prime _)) $ by { ext f, simp only [ring_hom.comp_apply, ring_hom.id_apply, localization_to_stalk_of, stalk_to_fiber_ring_hom_to_stalk] } } instance (x : prime_spectrum R) : is_iso (stalk_to_fiber_ring_hom R x) := is_iso.of_iso (stalk_iso R x) instance (x : prime_spectrum R) : is_iso (localization_to_stalk R x) := is_iso.of_iso (stalk_iso R x).symm @[simp, reassoc] lemma stalk_to_fiber_ring_hom_localization_to_stalk (x : prime_spectrum.Top R) : stalk_to_fiber_ring_hom R x ≫ localization_to_stalk R x = 𝟙 _ := (stalk_iso R x).hom_inv_id @[simp, reassoc] lemma localization_to_stalk_stalk_to_fiber_ring_hom (x : prime_spectrum.Top R) : localization_to_stalk R x ≫ stalk_to_fiber_ring_hom R x = 𝟙 _ := (stalk_iso R x).inv_hom_id /-- The canonical ring homomorphism interpreting `s ∈ R_f` as a section of the structure sheaf on the basic open defined by `f ∈ R`. -/ def to_basic_open (f : R) : localization.away f →+* (structure_sheaf R).1.obj (op $ basic_open f) := is_localization.away.lift f (is_unit_to_basic_open_self R f) @[simp] lemma to_basic_open_mk' (s f : R) (g : submonoid.powers s) : to_basic_open R s (is_localization.mk' (localization.away s) f g) = const R f g (basic_open s) (λ x hx, submonoid.powers_subset hx g.2) := (is_localization.lift_mk'_spec _ _ _ _).2 $ by rw [to_open_eq_const, to_open_eq_const, const_mul_cancel'] @[simp] lemma localization_to_basic_open (f : R) : ring_hom.comp (to_basic_open R f) (algebra_map R (localization.away f)) = to_open R (basic_open f) := ring_hom.ext $ λ g, by rw [to_basic_open, is_localization.away.lift, ring_hom.comp_apply, is_localization.lift_eq] @[simp] lemma to_basic_open_to_map (s f : R) : to_basic_open R s (algebra_map R (localization.away s) f) = const R f 1 (basic_open s) (λ _ _, submonoid.one_mem _) := (is_localization.lift_eq _ _).trans $ to_open_eq_const _ _ _ -- The proof here follows the argument in Hartshorne's Algebraic Geometry, Proposition II.2.2. lemma to_basic_open_injective (f : R) : function.injective (to_basic_open R f) := begin intros s t h_eq, obtain ⟨a, ⟨b, hb⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers f) s, obtain ⟨c, ⟨d, hd⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers f) t, simp only [to_basic_open_mk'] at h_eq, rw is_localization.eq, -- We know that the fractions `a/b` and `c/d` are equal as sections of the structure sheaf on -- `basic_open f`. We need to show that they agree as elements in the localization of `R` at `f`. -- This amounts showing that `a * d * r = c * b * r`, for some power `r = f ^ n` of `f`. -- We define `I` as the ideal of *all* elements `r` satisfying the above equation. let I : ideal R := { carrier := {r : R | a * d * r = c * b * r}, zero_mem' := by simp only [set.mem_set_of_eq, mul_zero], add_mem' := λ r₁ r₂ hr₁ hr₂, by { dsimp at hr₁ hr₂ ⊢, simp only [mul_add, hr₁, hr₂] }, smul_mem' := λ r₁ r₂ hr₂, by { dsimp at hr₂ ⊢, simp only [mul_comm r₁ r₂, ← mul_assoc, hr₂] }}, -- Our claim now reduces to showing that `f` is contained in the radical of `I` suffices : f ∈ I.radical, { cases this with n hn, exact ⟨⟨f ^ n, n, rfl⟩, hn⟩ }, rw [← vanishing_ideal_zero_locus_eq_radical, mem_vanishing_ideal], intros p hfp, contrapose hfp, rw [mem_zero_locus, set.not_subset], have := congr_fun (congr_arg subtype.val h_eq) ⟨p,hfp⟩, rw [const_apply, const_apply, is_localization.eq] at this, cases this with r hr, exact ⟨r.1, hr, r.2⟩ end /- Auxiliary lemma for surjectivity of `to_basic_open`. Every section can locally be represented on basic opens `basic_opens g` as a fraction `f/g` -/ lemma locally_const_basic_open (U : opens (prime_spectrum.Top R)) (s : (structure_sheaf R).1.obj (op U)) (x : U) : ∃ (f g : R) (i : basic_open g ⟶ U), x.1 ∈ basic_open g ∧ const R f g (basic_open g) (λ y hy, hy) = (structure_sheaf R).1.map i.op s := begin -- First, any section `s` can be represented as a fraction `f/g` on some open neighborhood of `x` -- and we may pass to a `basic_open h`, since these form a basis obtain ⟨V, (hxV : x.1 ∈ V.1), iVU, f, g, (hVDg : V ⊆ basic_open g), s_eq⟩ := exists_const R U s x.1 x.2, obtain ⟨_, ⟨h, rfl⟩, hxDh, (hDhV : basic_open h ⊆ V)⟩ := is_topological_basis_basic_opens.exists_subset_of_mem_open hxV V.2, -- The problem is of course, that `g` and `h` don't need to coincide. -- But, since `basic_open h ≤ basic_open g`, some power of `h` must be a multiple of `g` cases (basic_open_le_basic_open_iff h g).mp (set.subset.trans hDhV hVDg) with n hn, -- Actually, we will need a *nonzero* power of `h`. -- This is because we will need the equality `basic_open (h ^ n) = basic_open h`, which only -- holds for a nonzero power `n`. We therefore artificially increase `n` by one. replace hn := ideal.mul_mem_left (ideal.span {g}) h hn, rw [← pow_succ, ideal.mem_span_singleton'] at hn, cases hn with c hc, have basic_opens_eq := basic_open_pow h (n+1) (by linarith), have i_basic_open := eq_to_hom basic_opens_eq ≫ hom_of_le hDhV, -- We claim that `(f * c) / h ^ (n+1)` is our desired representation use [f * c, h ^ (n+1), i_basic_open ≫ iVU, (basic_opens_eq.symm.le : _) hxDh], rw [op_comp, functor.map_comp, comp_apply, ← s_eq, res_const], -- Note that the last rewrite here generated an additional goal, which was a parameter -- of `res_const`. We prove this goal first swap, { intros y hy, rw basic_opens_eq at hy, exact (set.subset.trans hDhV hVDg : _) hy }, -- All that is left is a simple calculation apply const_ext, rw [mul_assoc f c g, hc], end /- Auxiliary lemma for surjectivity of `to_basic_open`. A local representation of a section `s` as fractions `a i / h i` on finitely many basic opens `basic_open (h i)` can be "normalized" in such a way that `a i * h j = h i * a j` for all `i, j` -/ lemma normalize_finite_fraction_representation (U : opens (prime_spectrum.Top R)) (s : (structure_sheaf R).1.obj (op U)) {ι : Type*} (t : finset ι) (a h : ι → R) (iDh : Π i : ι, basic_open (h i) ⟶ U) (h_cover : U.1 ⊆ ⋃ i ∈ t, (basic_open (h i)).1) (hs : ∀ i : ι, const R (a i) (h i) (basic_open (h i)) (λ y hy, hy) = (structure_sheaf R).1.map (iDh i).op s) : ∃ (a' h' : ι → R) (iDh' : Π i : ι, (basic_open (h' i)) ⟶ U), (U.1 ⊆ ⋃ i ∈ t, (basic_open (h' i)).1) ∧ (∀ i j ∈ t, a' i * h' j = h' i * a' j) ∧ (∀ i ∈ t, (structure_sheaf R).1.map (iDh' i).op s = const R (a' i) (h' i) (basic_open (h' i)) (λ y hy, hy)) := begin -- First we show that the fractions `(a i * h j) / (h i * h j)` and `(h i * a j) / (h i * h j)` -- coincide in the localization of `R` at `h i * h j` have fractions_eq : ∀ (i j : ι), is_localization.mk' (localization.away _) (a i * h j) ⟨h i * h j, submonoid.mem_powers _⟩ = is_localization.mk' _ (h i * a j) ⟨h i * h j, submonoid.mem_powers _⟩, { intros i j, let D := basic_open (h i * h j), let iDi : D ⟶ basic_open (h i) := hom_of_le (basic_open_mul_le_left _ _), let iDj : D ⟶ basic_open (h j) := hom_of_le (basic_open_mul_le_right _ _), -- Crucially, we need injectivity of `to_basic_open` apply to_basic_open_injective R (h i * h j), rw [to_basic_open_mk', to_basic_open_mk'], simp only [set_like.coe_mk], -- Here, both sides of the equation are equal to a restriction of `s` transitivity, convert congr_arg ((structure_sheaf R).1.map iDj.op) (hs j).symm using 1, convert congr_arg ((structure_sheaf R).1.map iDi.op) (hs i) using 1, swap, all_goals { rw res_const, apply const_ext, ring }, -- The remaining two goals were generated during the rewrite of `res_const` -- These can be solved immediately exacts [basic_open_mul_le_right _ _, basic_open_mul_le_left _ _] }, -- From the equality in the localization, we obtain for each `(i,j)` some power `(h i * h j) ^ n` -- which equalizes `a i * h j` and `h i * a j` have exists_power : ∀ (i j : ι), ∃ n : ℕ, a i * h j * (h i * h j) ^ n = h i * a j * (h i * h j) ^ n, { intros i j, obtain ⟨⟨c, n, rfl⟩, hc⟩ := is_localization.eq.mp (fractions_eq i j), use (n+1), rw pow_succ, dsimp at hc, convert hc using 1 ; ring }, let n := λ (p : ι × ι), (exists_power p.1 p.2).some, have n_spec := λ (p : ι × ι), (exists_power p.fst p.snd).some_spec, -- We need one power `(h i * h j) ^ N` that works for *all* pairs `(i,j)` -- Since there are only finitely many indices involved, we can pick the supremum. let N := (t.product t).sup n, have basic_opens_eq : ∀ i : ι, basic_open ((h i) ^ (N+1)) = basic_open (h i) := λ i, basic_open_pow _ _ (by linarith), -- Expanding the fraction `a i / h i` by the power `(h i) ^ N` gives the desired normalization refine ⟨(λ i, a i * (h i) ^ N), (λ i, (h i) ^ (N + 1)), (λ i, eq_to_hom (basic_opens_eq i) ≫ iDh i), _, _, _⟩, { simpa only [basic_opens_eq] using h_cover }, { intros i hi j hj, -- Here we need to show that our new fractions `a i / h i` satisfy the normalization condition -- Of course, the power `N` we used to expand the fractions might be bigger than the power -- `n (i, j)` which was originally chosen. We denote their difference by `k` have n_le_N : n (i, j) ≤ N := finset.le_sup (finset.mem_product.mpr ⟨hi, hj⟩), cases nat.le.dest n_le_N with k hk, simp only [← hk, pow_add, pow_one], -- To accommodate for the difference `k`, we multiply both sides of the equation `n_spec (i, j)` -- by `(h i * h j) ^ k` convert congr_arg (λ z, z * (h i * h j) ^ k) (n_spec (i, j)) using 1 ; { simp only [n, mul_pow], ring } }, -- Lastly, we need to show that the new fractions still represent our original `s` intros i hi, rw [op_comp, functor.map_comp, comp_apply, ← hs, res_const], -- additional goal spit out by `res_const` swap, exact (basic_opens_eq i).le, apply const_ext, rw pow_succ, ring end open_locale classical open_locale big_operators -- The proof here follows the argument in Hartshorne's Algebraic Geometry, Proposition II.2.2. lemma to_basic_open_surjective (f : R) : function.surjective (to_basic_open R f) := begin intro s, -- In this proof, `basic_open f` will play two distinct roles: Firstly, it is an open set in the -- prime spectrum. Secondly, it is used as an indexing type for various families of objects -- (open sets, ring elements, ...). In order to make the distinction clear, we introduce a type -- alias `ι` that is used whenever we want think of it as an indexing type. let ι : Type u := basic_open f, -- First, we pick some cover of basic opens, on which we can represent `s` as a fraction choose a' h' iDh' hxDh' s_eq' using locally_const_basic_open R (basic_open f) s, -- Since basic opens are compact, we can pass to a finite subcover obtain ⟨t, ht_cover'⟩ := (is_compact_basic_open f).elim_finite_subcover (λ (i : ι), (basic_open (h' i)).1) (λ i, is_open_basic_open) (λ x hx, _), swap, { -- Here, we need to show that our basic opens actually form a cover of `basic_open f` rw set.mem_Union, exact ⟨⟨x,hx⟩, hxDh' ⟨x, hx⟩⟩ }, -- We use the normalization lemma from above to obtain the relation `a i * h j = h i * a j` obtain ⟨a, h, iDh, ht_cover, ah_ha, s_eq⟩ := normalize_finite_fraction_representation R (basic_open f) s t a' h' iDh' ht_cover' s_eq', clear s_eq' iDh' hxDh' ht_cover' a' h', -- Next we show that some power of `f` is a linear combination of the `h i` obtain ⟨n, hn⟩ : f ∈ (ideal.span (h '' ↑t)).radical, { rw [← vanishing_ideal_zero_locus_eq_radical, zero_locus_span], simp_rw [subtype.val_eq_coe, basic_open_eq_zero_locus_compl] at ht_cover, rw set.compl_subset_comm at ht_cover, -- Why doesn't `simp_rw` do this? simp_rw [set.compl_Union, compl_compl, ← zero_locus_Union, ← finset.set_bUnion_coe, ← set.image_eq_Union ] at ht_cover, apply vanishing_ideal_anti_mono ht_cover, exact subset_vanishing_ideal_zero_locus {f} (set.mem_singleton f) }, replace hn := ideal.mul_mem_left _ f hn, erw [←pow_succ, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨b, b_supp, hb⟩, rw finsupp.total_apply_of_mem_supported R b_supp at hb, dsimp at hb, -- Finally, we have all the ingredients. -- We claim that our preimage is given by `(∑ (i : ι) in t, b i * a i) / f ^ (n+1)` use is_localization.mk' (localization.away f) (∑ (i : ι) in t, b i * a i) (⟨f ^ (n+1), n+1, rfl⟩ : submonoid.powers _), rw to_basic_open_mk', -- Since the structure sheaf is a sheaf, we can show the desired equality locally. -- Annoyingly, `sheaf.eq_of_locally_eq` requires an open cover indexed by a *type*, so we need to -- coerce our finset `t` to a type first. let tt := ((t : set (basic_open f)) : Type u), apply (structure_sheaf R).eq_of_locally_eq' (λ i : tt, basic_open (h i)) (basic_open f) (λ i : tt, iDh i), { -- This feels a little redundant, since already have `ht_cover` as a hypothesis -- Unfortunately, `ht_cover` uses a bounded union over the set `t`, while here we have the -- Union indexed by the type `tt`, so we need some boilerplate to translate one to the other intros x hx, erw topological_space.opens.mem_supr, have := ht_cover hx, rw [← finset.set_bUnion_coe, set.mem_Union₂] at this, rcases this with ⟨i, i_mem, x_mem⟩, use [i, i_mem] }, rintro ⟨i, hi⟩, dsimp, change (structure_sheaf R).1.map _ _ = (structure_sheaf R).1.map _ _, rw [s_eq i hi, res_const], -- Again, `res_const` spits out an additional goal swap, { intros y hy, change y ∈ basic_open (f ^ (n+1)), rw basic_open_pow f (n+1) (by linarith), exact (le_of_hom (iDh i) : _) hy }, -- The rest of the proof is just computation apply const_ext, rw [← hb, finset.sum_mul, finset.mul_sum], apply finset.sum_congr rfl, intros j hj, rw [mul_assoc, ah_ha j hj i hi], ring end instance is_iso_to_basic_open (f : R) : is_iso (show CommRing.of _ ⟶ _, from to_basic_open R f) := begin haveI : is_iso ((forget CommRing).map (show CommRing.of _ ⟶ _, from to_basic_open R f)) := (is_iso_iff_bijective _).mpr ⟨to_basic_open_injective R f, to_basic_open_surjective R f⟩, exact is_iso_of_reflects_iso _ (forget CommRing), end /-- The ring isomorphism between the structure sheaf on `basic_open f` and the localization of `R` at the submonoid of powers of `f`. -/ def basic_open_iso (f : R) : (structure_sheaf R).1.obj (op (basic_open f)) ≅ CommRing.of (localization.away f) := (as_iso (show CommRing.of _ ⟶ _, from to_basic_open R f)).symm instance stalk_algebra (p : prime_spectrum R) : algebra R ((structure_sheaf R).val.stalk p) := (to_stalk R p).to_algebra @[simp] lemma stalk_algebra_map (p : prime_spectrum R) (r : R) : algebra_map R ((structure_sheaf R).val.stalk p) r = to_stalk R p r := rfl /-- Stalk of the structure sheaf at a prime p as localization of R -/ instance is_localization.to_stalk (p : prime_spectrum R) : is_localization.at_prime ((structure_sheaf R).val.stalk p) p.as_ideal := begin convert (is_localization.is_localization_iff_of_ring_equiv _ (stalk_iso R p).symm .CommRing_iso_to_ring_equiv).mp localization.is_localization, apply algebra.algebra_ext, intro _, rw stalk_algebra_map, congr' 1, erw iso.eq_comp_inv, exact to_stalk_comp_stalk_to_fiber_ring_hom R p, end instance open_algebra (U : (opens (prime_spectrum R))ᵒᵖ) : algebra R ((structure_sheaf R).val.obj U) := (to_open R (unop U)).to_algebra @[simp] lemma open_algebra_map (U : (opens (prime_spectrum R))ᵒᵖ) (r : R) : algebra_map R ((structure_sheaf R).val.obj U) r = to_open R (unop U) r := rfl /-- Sections of the structure sheaf of Spec R on a basic open as localization of R -/ instance is_localization.to_basic_open (r : R) : is_localization.away r ((structure_sheaf R).val.obj (op $ basic_open r)) := begin convert (is_localization.is_localization_iff_of_ring_equiv _ (basic_open_iso R r).symm .CommRing_iso_to_ring_equiv).mp localization.is_localization, apply algebra.algebra_ext, intro x, congr' 1, exact (localization_to_basic_open R r).symm end instance to_basic_open_epi (r : R) : epi (to_open R (basic_open r)) := ⟨λ S f g h, by { refine is_localization.ring_hom_ext _ _, swap 5, exact is_localization.to_basic_open R r, exact h }⟩ @[elementwise] lemma to_global_factors : to_open R ⊤ = (CommRing.of_hom (algebra_map R (localization.away (1 : R)))) ≫ (to_basic_open R (1 : R)) ≫ (structure_sheaf R).1.map (eq_to_hom (basic_open_one.symm)).op := begin change to_open R ⊤ = (to_basic_open R 1).comp _ ≫ _, unfold CommRing.of_hom, rw [localization_to_basic_open R, to_open_res], end instance is_iso_to_global : is_iso (to_open R ⊤) := begin let hom := CommRing.of_hom (algebra_map R (localization.away (1 : R))), haveI : is_iso hom := is_iso.of_iso ((is_localization.at_one R (localization.away (1 : R))).to_ring_equiv.to_CommRing_iso), rw to_global_factors R, apply_instance end /-- The ring isomorphism between the ring `R` and the global sections `Γ(X, 𝒪ₓ)`. -/ @[simps] def global_sections_iso : CommRing.of R ≅ (structure_sheaf R).1.obj (op ⊤) := as_iso (to_open R ⊤) @[simp] lemma global_sections_iso_hom (R : CommRing) : (global_sections_iso R).hom = to_open R ⊤ := rfl @[simp, reassoc, elementwise] lemma to_stalk_stalk_specializes {R : Type*} [comm_ring R] {x y : prime_spectrum R} (h : x ⤳ y) : to_stalk R y ≫ (structure_sheaf R).val.stalk_specializes h = to_stalk R x := by { dsimp [ to_stalk], simpa } @[simp, reassoc, elementwise] lemma localization_to_stalk_stalk_specializes {R : Type*} [comm_ring R] {x y : prime_spectrum R} (h : x ⤳ y) : structure_sheaf.localization_to_stalk R y ≫ (structure_sheaf R).val.stalk_specializes h = CommRing.of_hom (prime_spectrum.localization_map_of_specializes h) ≫ structure_sheaf.localization_to_stalk R x := begin apply is_localization.ring_hom_ext y.as_ideal.prime_compl, any_goals { dsimp, apply_instance }, erw ring_hom.comp_assoc, conv_rhs { erw ring_hom.comp_assoc }, dsimp [CommRing.of_hom, localization_to_stalk, prime_spectrum.localization_map_of_specializes], rw [is_localization.lift_comp, is_localization.lift_comp, is_localization.lift_comp], exact to_stalk_stalk_specializes h end @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_to_fiber {R : Type*} [comm_ring R] {x y : prime_spectrum R} (h : x ⤳ y) : (structure_sheaf R).val.stalk_specializes h ≫ structure_sheaf.stalk_to_fiber_ring_hom R x = structure_sheaf.stalk_to_fiber_ring_hom R y ≫ prime_spectrum.localization_map_of_specializes h := begin change _ ≫ (structure_sheaf.stalk_iso R x).hom = (structure_sheaf.stalk_iso R y).hom ≫ _, rw [← iso.eq_comp_inv, category.assoc, ← iso.inv_comp_eq], exact localization_to_stalk_stalk_specializes h, end section comap variables {R} {S : Type u} [comm_ring S] {P : Type u} [comm_ring P] /-- Given a ring homomorphism `f : R →+* S`, an open set `U` of the prime spectrum of `R` and an open set `V` of the prime spectrum of `S`, such that `V ⊆ (comap f) ⁻¹' U`, we can push a section `s` on `U` to a section on `V`, by composing with `localization.local_ring_hom _ _ f` from the left and `comap f` from the right. Explicitly, if `s` evaluates on `comap f p` to `a / b`, its image on `V` evaluates on `p` to `f(a) / f(b)`. At the moment, we work with arbitrary dependent functions `s : Π x : U, localizations R x`. Below, we prove the predicate `is_locally_fraction` is preserved by this map, hence it can be extended to a morphism between the structure sheaves of `R` and `S`. -/ def comap_fun (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (s : Π x : U, localizations R x) (y : V) : localizations S y := localization.local_ring_hom (prime_spectrum.comap f y.1).as_ideal _ f rfl (s ⟨(prime_spectrum.comap f y.1), hUV y.2⟩ : _) lemma comap_fun_is_locally_fraction (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (s : Π x : U, localizations R x) (hs : (is_locally_fraction R).to_prelocal_predicate.pred s) : (is_locally_fraction S).to_prelocal_predicate.pred (comap_fun f U V hUV s) := begin rintro ⟨p, hpV⟩, -- Since `s` is locally fraction, we can find a neighborhood `W` of `prime_spectrum.comap f p` -- in `U`, such that `s = a / b` on `W`, for some ring elements `a, b : R`. rcases hs ⟨prime_spectrum.comap f p, hUV hpV⟩ with ⟨W, m, iWU, a, b, h_frac⟩, -- We claim that we can write our new section as the fraction `f a / f b` on the neighborhood -- `(comap f) ⁻¹ W ⊓ V` of `p`. refine ⟨opens.comap (comap f) W ⊓ V, ⟨m, hpV⟩, opens.inf_le_right _ _, f a, f b, _⟩, rintro ⟨q, ⟨hqW, hqV⟩⟩, specialize h_frac ⟨prime_spectrum.comap f q, hqW⟩, refine ⟨h_frac.1, _⟩, dsimp only [comap_fun], erw [← localization.local_ring_hom_to_map ((prime_spectrum.comap f q).as_ideal), ← ring_hom.map_mul, h_frac.2, localization.local_ring_hom_to_map], refl, end /-- For a ring homomorphism `f : R →+* S` and open sets `U` and `V` of the prime spectra of `R` and `S` such that `V ⊆ (comap f) ⁻¹ U`, the induced ring homomorphism from the structure sheaf of `R` at `U` to the structure sheaf of `S` at `V`. Explicitly, this map is given as follows: For a point `p : V`, if the section `s` evaluates on `p` to the fraction `a / b`, its image on `V` evaluates on `p` to the fraction `f(a) / f(b)`. -/ def comap (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) : (structure_sheaf R).1.obj (op U) →+* (structure_sheaf S).1.obj (op V) := { to_fun := λ s, ⟨comap_fun f U V hUV s.1, comap_fun_is_locally_fraction f U V hUV s.1 s.2⟩, map_one' := subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_one, pi.one_apply, ring_hom.map_one], refl }, map_zero' := subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_zero, pi.zero_apply, ring_hom.map_zero], refl }, map_add' := λ s t, subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_add, pi.add_apply, ring_hom.map_add], refl }, map_mul' := λ s t, subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_mul, pi.mul_apply, ring_hom.map_mul], refl } } @[simp] lemma comap_apply (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (s : (structure_sheaf R).1.obj (op U)) (p : V) : (comap f U V hUV s).1 p = localization.local_ring_hom (prime_spectrum.comap f p.1).as_ideal _ f rfl (s.1 ⟨(prime_spectrum.comap f p.1), hUV p.2⟩ : _) := rfl lemma comap_const (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (a b : R) (hb : ∀ x : prime_spectrum R, x ∈ U → b ∈ x.as_ideal.prime_compl) : comap f U V hUV (const R a b U hb) = const S (f a) (f b) V (λ p hpV, hb (prime_spectrum.comap f p) (hUV hpV)) := subtype.eq $ funext $ λ p, begin rw [comap_apply, const_apply, const_apply], erw localization.local_ring_hom_mk', refl, end /-- For an inclusion `i : V ⟶ U` between open sets of the prime spectrum of `R`, the comap of the identity from OO_X(U) to OO_X(V) equals as the restriction map of the structure sheaf. This is a generalization of the fact that, for fixed `U`, the comap of the identity from OO_X(U) to OO_X(U) is the identity. -/ lemma comap_id_eq_map (U V : opens (prime_spectrum.Top R)) (iVU : V ⟶ U) : comap (ring_hom.id R) U V (λ p hpV, le_of_hom iVU $ by rwa prime_spectrum.comap_id) = (structure_sheaf R).1.map iVU.op := ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, begin rw comap_apply, -- Unfortunately, we cannot use `localization.local_ring_hom_id` here, because -- `prime_spectrum.comap (ring_hom.id R) p` is not *definitionally* equal to `p`. Instead, we use -- that we can write `s` as a fraction `a/b` in a small neighborhood around `p`. Since -- `prime_spectrum.comap (ring_hom.id R) p` equals `p`, it is also contained in the same -- neighborhood, hence `s` equals `a/b` there too. obtain ⟨W, hpW, iWU, h⟩ := s.2 (iVU p), obtain ⟨a, b, h'⟩ := h.eq_mk', obtain ⟨hb₁, s_eq₁⟩ := h' ⟨p, hpW⟩, obtain ⟨hb₂, s_eq₂⟩ := h' ⟨prime_spectrum.comap (ring_hom.id _) p.1, by rwa prime_spectrum.comap_id⟩, dsimp only at s_eq₁ s_eq₂, erw [s_eq₂, localization.local_ring_hom_mk', ← s_eq₁, ← res_apply], end /-- The comap of the identity is the identity. In this variant of the lemma, two open subsets `U` and `V` are given as arguments, together with a proof that `U = V`. This is be useful when `U` and `V` are not definitionally equal. -/ lemma comap_id (U V : opens (prime_spectrum.Top R)) (hUV : U = V) : comap (ring_hom.id R) U V (λ p hpV, by rwa [hUV, prime_spectrum.comap_id]) = eq_to_hom (show (structure_sheaf R).1.obj (op U) = _, by rw hUV) := by erw [comap_id_eq_map U V (eq_to_hom hUV.symm), eq_to_hom_op, eq_to_hom_map] @[simp] lemma comap_id' (U : opens (prime_spectrum.Top R)) : comap (ring_hom.id R) U U (λ p hpU, by rwa prime_spectrum.comap_id) = ring_hom.id _ := by { rw comap_id U U rfl, refl } lemma comap_comp (f : R →+* S) (g : S →+* P) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (W : opens (prime_spectrum.Top P)) (hUV : ∀ p ∈ V, prime_spectrum.comap f p ∈ U) (hVW : ∀ p ∈ W, prime_spectrum.comap g p ∈ V) : comap (g.comp f) U W (λ p hpW, hUV (prime_spectrum.comap g p) (hVW p hpW)) = (comap g V W hVW).comp (comap f U V hUV) := ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, begin rw comap_apply, erw localization.local_ring_hom_comp _ (prime_spectrum.comap g p.1).as_ideal, -- refl works here, because `prime_spectrum.comap (g.comp f) p` is defeq to -- `prime_spectrum.comap f (prime_spectrum.comap g p)` refl, end @[elementwise, reassoc] lemma to_open_comp_comap (f : R →+* S) (U : opens (prime_spectrum.Top R)) : to_open R U ≫ comap f U (opens.comap (prime_spectrum.comap f) U) (λ _, id) = CommRing.of_hom f ≫ to_open S _ := ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, begin simp_rw [comp_apply, comap_apply, subtype.val_eq_coe], erw localization.local_ring_hom_to_map, refl, end end comap end structure_sheaf end algebraic_geometry
8ab6f886e4e3bab681161573b1f7943f0d6214a7
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/category_theory/limits/shapes/equalizers.lean
d9f152f6611fe4546582285f6c55c2ee317c95fc
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
27,249
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.epi_mono import category_theory.limits.shapes.finite_limits /-! # Equalizers and coequalizers This file defines (co)equalizers as special cases of (co)limits. An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`. A coequalizer is the dual concept. ## Main definitions * `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams * `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`. * a `fork` is a cone over a parallel pair. * there is really only one interesting morphism in a fork: the arrow from the vertex of the fork to the domain of f and g. It is called `fork.ι`. * an `equalizer` is now just a `limit (parallel_pair f g)` Each of these has a dual. ## Main statements * `equalizer.ι_mono` states that every equalizer map is a monomorphism * `is_limit_cone_parallel_pair_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ open category_theory namespace category_theory.limits local attribute [tidy] tactic.case_bash universes v u /-- The type of objects for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type v | zero | one instance fintype_walking_parallel_pair : fintype walking_parallel_pair := { elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset, complete := λ x, by { cases x; simp } } open walking_parallel_pair /-- The type family of morphisms for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq] inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type v | left : walking_parallel_pair_hom zero one | right : walking_parallel_pair_hom zero one | id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X /-- Satisfying the inhabited linter -/ instance : inhabited (walking_parallel_pair_hom zero one) := { default := walking_parallel_pair_hom.left } open walking_parallel_pair_hom instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') := { elems := walking_parallel_pair.rec_on j (walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset [left, right].to_finset) (walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset), complete := by tidy } /-- Composition of morphisms in the indexing diagram for (co)equalizers. -/ def walking_parallel_pair_hom.comp : Π (X Y Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z), walking_parallel_pair_hom X Z | _ _ _ (id _) h := h | _ _ _ left (id one) := left | _ _ _ right (id one) := right . instance walking_parallel_pair_hom_category : small_category.{v} walking_parallel_pair := { hom := walking_parallel_pair_hom, id := walking_parallel_pair_hom.id, comp := walking_parallel_pair_hom.comp } instance : fin_category.{v} walking_parallel_pair.{v} := { } @[simp] lemma walking_parallel_pair_hom_id (X : walking_parallel_pair.{v}) : walking_parallel_pair_hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] variables {X Y : C} /-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with common domain and codomain. -/ def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C := { obj := λ x, match x with | zero := X | one := Y end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, left := f | _, _, right := g end, -- `tidy` can cope with this, but it's too slow: map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }. @[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl @[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl @[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl @[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl @[simp] lemma parallel_pair_functor_obj {F : walking_parallel_pair.{v} ⥤ C} (j : walking_parallel_pair.{v}) : (parallel_pair (F.map left) (F.map right)).obj j = F.obj j := begin cases j; refl end /-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a `parallel_pair` -/ def diagram_iso_parallel_pair (F : walking_parallel_pair.{v} ⥤ C) : F ≅ parallel_pair (F.map left) (F.map right) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/ abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g) /-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/ abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g) variables {f g : X ⟶ Y} @[simp, reassoc] lemma fork.app_zero_left (s : fork f g) : (s.π).app zero ≫ f = (s.π).app one := by rw [←s.w left, parallel_pair_map_left] @[simp, reassoc] lemma fork.app_zero_right (s : fork f g) : (s.π).app zero ≫ g = (s.π).app one := by rw [←s.w right, parallel_pair_map_right] @[simp, reassoc] lemma cofork.left_app_one (s : cofork f g) : f ≫ (s.ι).app one = (s.ι).app zero := by rw [←s.w left, parallel_pair_map_left] @[simp, reassoc] lemma cofork.right_app_one (s : cofork f g) : g ≫ (s.ι).app one = (s.ι).app zero := by rw [←s.w right, parallel_pair_map_right] /-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`. -/ def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g := { X := P, π := { app := λ X, begin cases X, exact ι, exact ι ≫ f, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, { dsimp, simp, }, -- TODO If someone could decipher why these aren't done on the previous line, that would be great { exact w }, { dsimp, simp, }, -- TODO idem end } } /-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying `f ≫ π = g ≫ π`. -/ def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g := { X := P, ι := { app := λ X, begin cases X, exact f ≫ π, exact π, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, { dsimp, simp, }, -- TODO idem { exact w.symm }, { dsimp, simp, }, -- TODO idem end } } @[simp] lemma fork.of_ι_app_zero {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app zero = ι := rfl @[simp] lemma fork.of_ι_app_one {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app one = ι ≫ f := rfl @[simp] lemma cofork.of_π_app_zero {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).ι.app zero = f ≫ π := rfl @[simp] lemma cofork.of_π_app_one {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).ι.app one = π := rfl /-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X` and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the shorter name `fork.ι t`. -/ abbreviation fork.ι (t : fork f g) := t.π.app zero /-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms `t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is interesting, and we give it the shorter name `cofork.π t`. -/ abbreviation cofork.π (t : cofork f g) := t.ι.app one @[simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork.ι (fork.of_ι ι w) = ι := rfl @[simp] lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork.π (cofork.of_π π w) = π := rfl lemma fork.condition (t : fork f g) : (fork.ι t) ≫ f = (fork.ι t) ≫ g := begin erw [t.w left, ← t.w right], refl end lemma cofork.condition (t : cofork f g) : f ≫ (cofork.π t) = g ≫ (cofork.π t) := begin erw [t.w left, ← t.w right], refl end /-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the first map -/ lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : ∀ (j : walking_parallel_pair), k ≫ s.π.app j = l ≫ s.π.app j | zero := h | one := by rw [←fork.app_zero_left, reassoc_of h] /-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for the second map -/ lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair), s.ι.app j ≫ k = s.ι.app j ≫ l | zero := by simp only [←cofork.left_app_one, category.assoc, h] | one := h lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l := hs.hom_ext $ fork.equalizer_ext _ h lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l := hs.hom_ext $ cofork.coequalizer_ext _ h /-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩ /-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def fork.is_limit.mk (t : fork f g) (lift : Π (s : fork f g), s.X ⟶ t.X) (fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s) (uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_parallel_pair, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $ by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl, uniq' := uniq } /-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def cofork.is_colimit.mk (t : cofork f g) (desc : Π (s : cofork f g), t.X ⟶ s.X) (fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s) (uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_parallel_pair, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_parallel_pair.cases_on j (by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s), uniq' := uniq } /-- This is a helper construction that can be useful when verifying that a category has all equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`, we get a cone on `F`. If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cone.of_fork {F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } /-- This is a helper construction that can be useful when verifying that a category has all coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cocone.of_cofork {F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } @[simp] lemma cone.of_fork_π {F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) (j) : (cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cofork_ι {F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) (j) : (cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on `F.map left` and `F.map right`. -/ def fork.of_cone {F : walking_parallel_pair.{v} ⥤ C} (t : cone F) : fork (F.map left) (F.map right) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } /-- Given `F : walking_parallel_pair.{v} ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on `F.map left` and `F.map right`. -/ def cofork.of_cocone {F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma fork.of_cone_π {F : walking_parallel_pair.{v} ⥤ C} (t : cone F) (j) : (fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) (j) : (cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl variables (f g) section variables [has_limit (parallel_pair f g)] /-- If we have chosen an equalizer of `f` and `g`, we can access the corresponding object by saying `equalizer f g`. -/ abbreviation equalizer := limit (parallel_pair f g) /-- If we have chosen an equalizer of `f` and `g`, we can access the inclusion `equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/ abbreviation equalizer.ι : equalizer f g ⟶ X := limit.π (parallel_pair f g) zero @[simp] lemma equalizer.ι.fork : fork.ι (limit.cone (parallel_pair f g)) = equalizer.ι f g := rfl @[simp] lemma equalizer.ι.eq_app_zero : (limit.cone (parallel_pair f g)).π.app zero = equalizer.ι f g := rfl @[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g := fork.condition $ limit.cone $ parallel_pair f g variables {f g} /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g` via `equalizer.lift : W ⟶ equalizer f g`. -/ abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g := limit.lift (parallel_pair f g) (fork.of_ι k h) @[simp, reassoc] lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : equalizer.lift k h ≫ equalizer.ι f g = k := limit.lift_π _ _ /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g` satisfying `l ≫ equalizer.ι f g = k`. -/ def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} := ⟨equalizer.lift k h, equalizer.lift_ι _ _⟩ /-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer map. -/ @[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g} (h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l := fork.is_limit.hom_ext (limit.is_limit _) h /-- An equalizer morphism is a monomorphism -/ instance equalizer.ι_mono : mono (equalizer.ι f g) := { right_cancellation := λ Z h k w, equalizer.hom_ext w } end section variables {f g} /-- The equalizer morphism in any limit cone is a monomorphism. -/ lemma mono_of_is_limit_parallel_pair {c : cone (parallel_pair f g)} (i : is_limit c) : mono (fork.ι c) := { right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w } end section variables {f g} /-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/ def id_fork (h : f = g) : fork f g := fork.of_ι (𝟙 X) $ h ▸ rfl /-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/ def is_limit_id_fork (h : f = g) : is_limit (id_fork h) := fork.is_limit.mk _ (λ s, fork.ι s) (λ s, category.comp_id _) (λ s m h, by { convert h zero, exact (category.comp_id _).symm }) /-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : cone (parallel_pair f g)} (h : is_limit c) : is_iso (c.π.app zero) := is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀ /-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def equalizer.ι_of_eq [has_limit (parallel_pair f g)] (h : f = g) : is_iso (equalizer.ι f g) := is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _ /-- Every equalizer of `(f, f)` is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_self {c : cone (parallel_pair f f)} (h : is_limit c) : is_iso (c.π.app zero) := is_iso_limit_cone_parallel_pair_of_eq rfl h /-- An equalizer that is an epimorphism is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_epi {c : cone (parallel_pair f g)} (h : is_limit c) [epi (c.π.app zero)] : is_iso (c.π.app zero) := is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h end /-- The equalizer of `(f, f)` is an isomorphism. -/ def equalizer.ι_of_self [has_limit (parallel_pair f f)] : is_iso (equalizer.ι f f) := equalizer.ι_of_eq rfl section variables [has_colimit (parallel_pair f g)] /-- If we have chosen a coequalizer of `f` and `g`, we can access the corresponding object by saying `coequalizer f g`. -/ abbreviation coequalizer := colimit (parallel_pair f g) /-- If we have chosen a coequalizer of `f` and `g`, we can access the corresponding projection by saying `coequalizer.π f g`. -/ abbreviation coequalizer.π : Y ⟶ coequalizer f g := colimit.ι (parallel_pair f g) one @[simp] lemma coequalizer.π.cofork : cofork.π (colimit.cocone (parallel_pair f g)) = coequalizer.π f g := rfl @[simp] lemma coequalizer.π.eq_app_one : (colimit.cocone (parallel_pair f g)).ι.app one = coequalizer.π f g := rfl @[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g := cofork.condition $ colimit.cocone $ parallel_pair f g variables {f g} /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f` and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/ abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W := colimit.desc (parallel_pair f g) (cofork.of_π k h) @[simp, reassoc] lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer.π f g ≫ coequalizer.desc k h = k := colimit.ι_desc _ _ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/ def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} := ⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩ /-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer map -/ @[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W} (h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l := cofork.is_colimit.hom_ext (colimit.is_colimit _) h /-- A coequalizer morphism is an epimorphism -/ instance coequalizer.π_epi : epi (coequalizer.π f g) := { left_cancellation := λ Z h k w, coequalizer.hom_ext w } end section variables {f g} /-- The coequalizer morphism in any colimit cocone is an epimorphism. -/ lemma epi_of_is_colimit_parallel_pair {c : cocone (parallel_pair f g)} (i : is_colimit c) : epi (c.ι.app one) := { left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w } end section variables {f g} /-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/ def id_cofork (h : f = g) : cofork f g := cofork.of_π (𝟙 Y) $ h ▸ rfl /-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/ def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) := cofork.is_colimit.mk _ (λ s, cofork.π s) (λ s, category.id_comp _) (λ s m h, by { convert h one, exact (category.id_comp _).symm }) /-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cocone (parallel_pair f g)} (h : is_colimit c) : is_iso (c.ι.app one) := is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h /-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def coequalizer.π_of_eq [has_colimit (parallel_pair f g)] (h : f = g) : is_iso (coequalizer.π f g) := is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _ /-- Every coequalizer of `(f, f)` is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_self {c : cocone (parallel_pair f f)} (h : is_colimit c) : is_iso (c.ι.app one) := is_iso_colimit_cocone_parallel_pair_of_eq rfl h /-- A coequalizer that is a monomorphism is an isomorphism. -/ def is_iso_limit_cocone_parallel_pair_of_epi {c : cocone (parallel_pair f g)} (h : is_colimit c) [mono (c.ι.app one)] : is_iso (c.ι.app one) := is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h end /-- The coequalizer of `(f, f)` is an isomorphism. -/ def coequalizer.π_of_self [has_colimit (parallel_pair f f)] : is_iso (coequalizer.π f f) := coequalizer.π_of_eq rfl variables (C) /-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/ class has_equalizers := (has_limits_of_shape : has_limits_of_shape.{v} walking_parallel_pair C) /-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/ class has_coequalizers := (has_colimits_of_shape : has_colimits_of_shape.{v} walking_parallel_pair C) attribute [instance] has_equalizers.has_limits_of_shape has_coequalizers.has_colimits_of_shape /-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/ def has_equalizers_of_has_finite_limits [has_finite_limits.{v} C] : has_equalizers.{v} C := { has_limits_of_shape := infer_instance } /-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all coequalizers -/ def has_coequalizers_of_has_finite_colimits [has_finite_colimits.{v} C] : has_coequalizers.{v} C := { has_colimits_of_shape := infer_instance } /-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/ def has_equalizers_of_has_limit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm } } /-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/ def has_coequalizers_of_has_colimit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) } } section -- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. variables {C} [split_mono f] /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. Here we build the cone, and show in `split_mono_equalizes` that it is a limit cone. -/ def cone_of_split_mono : cone (parallel_pair (𝟙 Y) (retraction f ≫ f)) := fork.of_ι f (by tidy) @[simp] lemma cone_of_split_mono_π_app_zero : (cone_of_split_mono f).π.app zero = f := rfl @[simp] lemma cone_of_split_mono_π_app_one : (cone_of_split_mono f).π.app one = f ≫ 𝟙 Y := rfl /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. -/ def split_mono_equalizes {X Y : C} (f : X ⟶ Y) [split_mono f] : is_limit (cone_of_split_mono f) := { lift := λ s, s.π.app zero ≫ retraction f, fac' := λ s, begin rintros (⟨⟩|⟨⟩), { rw [cone_of_split_mono_π_app_zero], erw [category.assoc, ← s.π.naturality right, s.π.naturality left, category.comp_id], }, { erw [cone_of_split_mono_π_app_one, category.comp_id, category.assoc, ← s.π.naturality right, category.id_comp], } end, uniq' := λ s m w, begin rw ←(w zero), simp, end, } end section -- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. variables {C} [split_epi f] /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. Here we build the cocone, and show in `split_epi_coequalizes` that it is a colimit cocone. -/ def cocone_of_split_epi : cocone (parallel_pair (𝟙 X) (f ≫ section_ f)) := cofork.of_π f (by tidy) @[simp] lemma cocone_of_split_epi_ι_app_one : (cocone_of_split_epi f).ι.app one = f := rfl @[simp] lemma cocone_of_split_epi_ι_app_zero : (cocone_of_split_epi f).ι.app zero = 𝟙 X ≫ f := rfl /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. -/ def split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [split_epi f] : is_colimit (cocone_of_split_epi f) := { desc := λ s, section_ f ≫ s.ι.app one, fac' := λ s, begin rintros (⟨⟩|⟨⟩), { erw [cocone_of_split_epi_ι_app_zero, category.assoc, category.id_comp, ←category.assoc, s.ι.naturality right, functor.const.obj_map, category.comp_id], }, { erw [cocone_of_split_epi_ι_app_one, ←category.assoc, s.ι.naturality right, ←s.ι.naturality left, category.id_comp] } end, uniq' := λ s m w, begin rw ←(w one), simp, end, } end end category_theory.limits
253bdf14057266863695716492abf3b802c42b0d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/opaque_hint_bug.lean
9c1e5d5ef08c5f3ecd03a3e12e15fd716abbb715
[ "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
236
lean
inductive List (T : Type) : Type | nil {} : List | cons : T → List → List section variable {T : Type} definition concat (s t : List T) : List T := List.rec t (fun x l u, List.cons x u) s attribute [reducible] concat end
076e3dd569dee54eac98e98ebb509e652df0d387
cbcb0199842f03e7606d4e43666573fc15dd07a5
/src/topology/instances/real.lean
94975644004b86d98fb86cbfcd94f9ff3fba4658
[ "Apache-2.0" ]
permissive
truonghoangle/mathlib
a6a7c14b3767ec71156239d8ea97f6921fe79627
673bae584febcd830c2c9256eb7e7a81e27ed303
refs/heads/master
1,590,347,998,944
1,559,728,860,000
1,559,728,860,000
187,431,971
0
0
null
1,558,238,525,000
1,558,238,525,000
null
UTF-8
Lean
false
false
18,874
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 The real numbers ℝ. They are constructed as the topological completion of ℚ. With the following steps: (1) prove that ℚ forms a uniform space. (2) subtraction and addition are uniform continuous functions in this space (3) for multiplication and inverse this only holds on bounded subsets (4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction) (5) extend the uniform continuous functions along the completion (6) proof field properties using the principle of extension of identities TODO generalizations: * topological groups & rings * order topologies * Archimedean fields -/ import topology.metric_space.basic topology.algebra.uniform_group topology.algebra.ring tactic.linarith noncomputable theory open classical set lattice filter topological_space metric local attribute [instance] prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), simpa using (@int.cast_le ℝ _ _ 0).2 (int.lt_add_one_iff.1 $ (@int.cast_lt ℝ _ (abs (a - b)) 1).1 $ by simpa using h) end theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ne_empty_iff_exists_mem.2 ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.uniform_continuous_iff.2 $ by simp [(∘)]; exact ((uniform_continuous_fst.comp uniform_continuous_of_rat).prod_mk (uniform_continuous_snd.comp uniform_continuous_of_rat)).comp real.uniform_continuous_add theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : orderable_topology ℚ := induced_orderable_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) := by rw ← abs_pos_iff at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma real.continuous_inv' : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, (continuous_iff_continuous_at.mp continuous_subtype_val _).comp (real.tendsto_inv hr) lemma real.continuous_inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv'.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (r₁0 : 0 < r₁) (r₂0 : 0 < r₂) (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 r₁0 r₂0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (λ x, id)) (mem_nhds_sets (is_open_prod (real.continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (real.continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩, rcases h with ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, refine ⟨_, ⟨i, _, rfl⟩, _⟩, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [ge, sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end -- TODO(Mario): Generalize to first-countable uniform spaces? instance : complete_space ℝ := ⟨λ f cf, begin let g : ℕ → {ε:ℝ//ε>0} := λ n, ⟨n.to_pnat'⁻¹, inv_pos (nat.cast_pos.2 n.to_pnat'.pos)⟩, choose S hS hS_dist using show ∀n:ℕ, ∃t ∈ f.sets, ∀ x y ∈ t, dist x y < g n, from assume n, let ⟨t, tf, h⟩ := (metric.cauchy_iff.1 cf).2 (g n).1 (g n).2 in ⟨t, tf, h⟩, let F : ℕ → set ℝ := λn, ⋂i≤n, S i, have hF : ∀n, F n ∈ f.sets := assume n, Inter_mem_sets (finite_le_nat n) (λ i _, hS i), have hF_dist : ∀n, ∀ x y ∈ F n, dist x y < g n := assume n x y hx hy, have F n ⊆ S n := bInter_subset_of_mem (le_refl n), (hS_dist n) _ _ (this hx) (this hy), choose G hG using assume n:ℕ, inhabited_of_mem_sets cf.1 (hF n), have hg : ∀ ε > 0, ∃ n, ∀ j ≥ n, (g j : ℝ) < ε, { intros ε ε0, cases exists_nat_gt ε⁻¹ with n hn, refine ⟨n, λ j nj, _⟩, have hj := lt_of_lt_of_le hn (nat.cast_le.2 nj), have j0 := lt_trans (inv_pos ε0) hj, have jε := (inv_lt j0 ε0).2 hj, rwa ← pnat.to_pnat'_coe (nat.cast_pos.1 j0) at jε }, let c : cau_seq ℝ abs, { refine ⟨λ n, G n, λ ε ε0, _⟩, cases hg _ ε0 with n hn, refine ⟨n, λ j jn, _⟩, have : F j ⊆ F n := bInter_subset_bInter_left (λ i h, @le_trans _ _ i n j h jn), exact lt_trans (hF_dist n _ _ (this (hG j)) (hG n)) (hn _ $ le_refl _) }, refine ⟨cau_seq.lim c, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, cases exists_forall_ge_and (hg _ $ half_pos ε0) (cau_seq.equiv_lim c _ $ half_pos ε0) with n hn, cases hn _ (le_refl _) with h₁ h₂, refine sets_of_superset _ (hF n) (subset.trans _ $ subset.trans (ball_half_subset (G n) h₂) hε), exact λ x h, lt_trans ((hF_dist n) x (G n) h (hG n)) h₁ end⟩ lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩ lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top := tendsto_coe_nat_real_at_top_iff.2 tendsto_id lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩ lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top := tendsto_coe_int_real_at_top_iff.2 tendsto_id section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ne_empty_iff_exists_mem.2 ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } open real lemma real.intermediate_value {f : ℝ → ℝ} {a b t : ℝ} (hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x))) (ha : f a ≤ t) (hb : t ≤ f b) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t := let x := real.Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} in have hx₁ : ∃ y, ∀ g ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}, g ≤ y := ⟨b, λ _ h, h.2.2⟩, have hx₂ : ∃ y, y ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} := ⟨a, ha, le_refl _, hab⟩, have hax : a ≤ x, from le_Sup _ hx₁ ⟨ha, le_refl _, hab⟩, have hxb : x ≤ b, from (Sup_le _ hx₂ hx₁).2 (λ _ h, h.2.2), ⟨x, hax, hxb, eq_of_forall_dist_le $ λ ε ε0, let ⟨δ, hδ0, hδ⟩ := metric.tendsto_nhds_nhds.1 (hf _ hax hxb) ε ε0 in (le_total t (f x)).elim (λ h, le_of_not_gt $ λ hfε, begin rw [dist_eq, abs_of_nonneg (sub_nonneg.2 h)] at hfε, refine mt (Sup_le {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} hx₂ hx₁).2 (not_le_of_gt (sub_lt_self x (half_pos hδ0))) (λ g hg, le_of_not_gt (λ hgδ, not_lt_of_ge hg.1 (lt_trans (lt_sub.1 hfε) (sub_lt_of_sub_lt (lt_of_le_of_lt (le_abs_self _) _))))), rw abs_sub, exact hδ (abs_sub_lt_iff.2 ⟨lt_of_le_of_lt (sub_nonpos.2 (le_Sup _ hx₁ hg)) hδ0, by simp only [x] at *; linarith⟩) end) (λ h, le_of_not_gt $ λ hfε, begin rw [dist_eq, abs_of_nonpos (sub_nonpos.2 h)] at hfε, exact mt (le_Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}) (λ h : ∀ k, k ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} → k ≤ x, not_le_of_gt ((lt_add_iff_pos_left x).2 (half_pos hδ0)) (h _ ⟨le_trans (le_sub_iff_add_le.2 (le_trans (le_abs_self _) (le_of_lt (hδ $ by rw [dist_eq, add_sub_cancel, abs_of_nonneg (le_of_lt (half_pos hδ0))]; exact half_lt_self hδ0)))) (by linarith), le_trans hax (le_of_lt ((lt_add_iff_pos_left _).2 (half_pos hδ0))), le_of_not_gt (λ hδy, not_lt_of_ge hb (lt_of_le_of_lt (show f b ≤ f b - f x - ε + t, by linarith) (add_lt_of_neg_of_le (sub_neg_of_lt (lt_of_le_of_lt (le_abs_self _) (@hδ b (abs_sub_lt_iff.2 ⟨by simp only [x] at *; linarith, by linarith⟩)))) (le_refl _))))⟩)) hx₁ end)⟩ lemma real.intermediate_value' {f : ℝ → ℝ} {a b t : ℝ} (hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x))) (ha : t ≤ f a) (hb : f b ≤ t) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t := let ⟨x, hx₁, hx₂, hx₃⟩ := @real.intermediate_value (λ x, - f x) a b (-t) (λ x hax hxb, tendsto_neg (hf x hax hxb)) (neg_le_neg ha) (neg_le_neg hb) hab in ⟨x, hx₁, hx₂, neg_inj hx₃⟩ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm x hx, hM x hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ end
9074bcbada485b36c12f5597ad4587fa6e9b1d91
63abd62053d479eae5abf4951554e1064a4c45b4
/src/number_theory/pell.lean
df9991d0e5882e5cd54904611541827b78e3039b
[ "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
37,106
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.modeq import data.zsqrtd.basic import tactic.omega namespace pell open nat section parameters {a : ℕ} (a1 : 1 < a) include a1 private def d := a*a - 1 @[simp] theorem d_pos : 0 < d := nat.sub_pos_of_lt (mul_lt_mul a1 (le_of_lt a1) dec_trivial dec_trivial : 1*1<a*a) /-- The Pell sequences, defined together in mutual recursion. -/ -- TODO(lint): Fix double namespace issue @[nolint dup_namespace] def pell : ℕ → ℕ × ℕ := λn, nat.rec_on n (1, 0) (λn xy, (xy.1*a + d*xy.2, xy.1 + xy.2*a)) /-- The Pell `x` sequence. -/ def xn (n : ℕ) : ℕ := (pell n).1 /-- The Pell `y` sequence. -/ def yn (n : ℕ) : ℕ := (pell n).2 @[simp] theorem pell_val (n : ℕ) : pell n = (xn n, yn n) := show pell n = ((pell n).1, (pell n).2), from match pell n with (a, b) := rfl end @[simp] theorem xn_zero : xn 0 = 1 := rfl @[simp] theorem yn_zero : yn 0 = 0 := rfl @[simp] theorem xn_succ (n : ℕ) : xn (n+1) = xn n * a + d * yn n := rfl @[simp] theorem yn_succ (n : ℕ) : yn (n+1) = xn n + yn n * a := rfl @[simp] theorem xn_one : xn 1 = a := by simp @[simp] theorem yn_one : yn 1 = 1 := by simp def xz (n : ℕ) : ℤ := xn n def yz (n : ℕ) : ℤ := yn n def az : ℤ := a theorem asq_pos : 0 < a*a := le_trans (le_of_lt a1) (by have := @nat.mul_le_mul_left 1 a a (le_of_lt a1); rwa mul_one at this) theorem dz_val : ↑d = az*az - 1 := have 1 ≤ a*a, from asq_pos, show ↑(a*a - 1) = _, by rw int.coe_nat_sub this; refl @[simp] theorem xz_succ (n : ℕ) : xz (n+1) = xz n * az + ↑d * yz n := rfl @[simp] theorem yz_succ (n : ℕ) : yz (n+1) = xz n + yz n * az := rfl /-- The Pell sequence can also be viewed as an element of `ℤ√d` -/ def pell_zd (n : ℕ) : ℤ√d := ⟨xn n, yn n⟩ @[simp] theorem pell_zd_re (n : ℕ) : (pell_zd n).re = xn n := rfl @[simp] theorem pell_zd_im (n : ℕ) : (pell_zd n).im = yn n := rfl /-- The property of being a solution to the Pell equation, expressed as a property of elements of `ℤ√d`. -/ def is_pell : ℤ√d → Prop | ⟨x, y⟩ := x*x - d*y*y = 1 theorem is_pell_nat {x y : ℕ} : is_pell ⟨x, y⟩ ↔ x*x - d*y*y = 1 := ⟨λh, int.coe_nat_inj (by rw int.coe_nat_sub (int.le_of_coe_nat_le_coe_nat $ int.le.intro_sub h); exact h), λh, show ((x*x : ℕ) - (d*y*y:ℕ) : ℤ) = 1, by rw [← int.coe_nat_sub $ le_of_lt $ nat.lt_of_sub_eq_succ h, h]; refl⟩ theorem is_pell_norm : Π {b : ℤ√d}, is_pell b ↔ b * b.conj = 1 | ⟨x, y⟩ := by simp [zsqrtd.ext, is_pell, mul_comm]; ring theorem is_pell_mul {b c : ℤ√d} (hb : is_pell b) (hc : is_pell c) : is_pell (b * c) := is_pell_norm.2 (by simp [mul_comm, mul_left_comm, zsqrtd.conj_mul, pell.is_pell_norm.1 hb, pell.is_pell_norm.1 hc]) theorem is_pell_conj : ∀ {b : ℤ√d}, is_pell b ↔ is_pell b.conj | ⟨x, y⟩ := by simp [is_pell, zsqrtd.conj] @[simp] theorem pell_zd_succ (n : ℕ) : pell_zd (n+1) = pell_zd n * ⟨a, 1⟩ := by simp [zsqrtd.ext] theorem is_pell_one : is_pell ⟨a, 1⟩ := show az*az-d*1*1=1, by simp [dz_val]; ring theorem is_pell_pell_zd : ∀ (n : ℕ), is_pell (pell_zd n) | 0 := rfl | (n+1) := let o := is_pell_one in by simp; exact pell.is_pell_mul (is_pell_pell_zd n) o @[simp] theorem pell_eqz (n : ℕ) : xz n * xz n - d * yz n * yz n = 1 := is_pell_pell_zd n @[simp] theorem pell_eq (n : ℕ) : xn n * xn n - d * yn n * yn n = 1 := let pn := pell_eqz n in have h : (↑(xn n * xn n) : ℤ) - ↑(d * yn n * yn n) = 1, by repeat {rw int.coe_nat_mul}; exact pn, have hl : d * yn n * yn n ≤ xn n * xn n, from int.le_of_coe_nat_le_coe_nat $ int.le.intro $ add_eq_of_eq_sub' $ eq.symm h, int.coe_nat_inj (by rw int.coe_nat_sub hl; exact h) instance dnsq : zsqrtd.nonsquare d := ⟨λn h, have n*n + 1 = a*a, by rw ← h; exact nat.succ_pred_eq_of_pos (asq_pos a1), have na : n < a, from nat.mul_self_lt_mul_self_iff.2 (by rw ← this; exact nat.lt_succ_self _), have (n+1)*(n+1) ≤ n*n + 1, by rw this; exact nat.mul_self_le_mul_self na, have n+n ≤ 0, from @nat.le_of_add_le_add_right (n*n + 1) _ _ (by ring at this ⊢; assumption), ne_of_gt d_pos $ by rw nat.eq_zero_of_le_zero (le_trans (nat.le_add_left _ _) this) at h; exact h⟩ theorem xn_ge_a_pow : ∀ (n : ℕ), a^n ≤ xn n | 0 := le_refl 1 | (n+1) := by simp [pow_succ']; exact le_trans (nat.mul_le_mul_right _ (xn_ge_a_pow n)) (nat.le_add_right _ _) theorem n_lt_a_pow : ∀ (n : ℕ), n < a^n | 0 := nat.le_refl 1 | (n+1) := begin have IH := n_lt_a_pow n, have : a^n + a^n ≤ a^n * a, { rw ← mul_two, exact nat.mul_le_mul_left _ a1 }, simp [pow_succ'], refine lt_of_lt_of_le _ this, exact add_lt_add_of_lt_of_le IH (lt_of_le_of_lt (nat.zero_le _) IH) end theorem n_lt_xn (n) : n < xn n := lt_of_lt_of_le (n_lt_a_pow n) (xn_ge_a_pow n) theorem x_pos (n) : 0 < xn n := lt_of_le_of_lt (nat.zero_le n) (n_lt_xn n) lemma eq_pell_lem : ∀n (b:ℤ√d), 1 ≤ b → is_pell b → b ≤ pell_zd n → ∃n, b = pell_zd n | 0 b := λh1 hp hl, ⟨0, @zsqrtd.le_antisymm _ dnsq _ _ hl h1⟩ | (n+1) b := λh1 hp h, have a1p : (0:ℤ√d) ≤ ⟨a, 1⟩, from trivial, have am1p : (0:ℤ√d) ≤ ⟨a, -1⟩, from show (_:nat) ≤ _, by simp; exact nat.pred_le _, have a1m : (⟨a, 1⟩ * ⟨a, -1⟩ : ℤ√d) = 1, from is_pell_norm.1 is_pell_one, if ha : (⟨↑a, 1⟩ : ℤ√d) ≤ b then let ⟨m, e⟩ := eq_pell_lem n (b * ⟨a, -1⟩) (by rw ← a1m; exact mul_le_mul_of_nonneg_right ha am1p) (is_pell_mul hp (is_pell_conj.1 is_pell_one)) (by have t := mul_le_mul_of_nonneg_right h am1p; rwa [pell_zd_succ, mul_assoc, a1m, mul_one] at t) in ⟨m+1, by rw [show b = b * ⟨a, -1⟩ * ⟨a, 1⟩, by rw [mul_assoc, eq.trans (mul_comm _ _) a1m]; simp, pell_zd_succ, e]⟩ else suffices ¬1 < b, from ⟨0, show b = 1, from (or.resolve_left (lt_or_eq_of_le h1) this).symm⟩, λh1l, by cases b with x y; exact have bm : (_*⟨_,_⟩ :ℤ√(d a1)) = 1, from pell.is_pell_norm.1 hp, have y0l : (0:ℤ√(d a1)) < ⟨x - x, y - -y⟩, from sub_lt_sub h1l $ λ(hn : (1:ℤ√(d a1)) ≤ ⟨x, -y⟩), by have t := mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1); rw [bm, mul_one] at t; exact h1l t, have yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩, from show (⟨x, y⟩ - ⟨x, -y⟩ : ℤ√(d a1)) < ⟨a, 1⟩ - ⟨a, -1⟩, from sub_lt_sub (by exact ha) $ λ(hn : (⟨x, -y⟩ : ℤ√(d a1)) ≤ ⟨a, -1⟩), by have t := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1)) a1p; rw [bm, one_mul, mul_assoc, eq.trans (mul_comm _ _) a1m, mul_one] at t; exact ha t, by simp at y0l; simp at yl2; exact match y, y0l, (yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩) with | 0, y0l, yl2 := y0l (le_refl 0) | (y+1 : ℕ), y0l, yl2 := yl2 (zsqrtd.le_of_le_le (le_refl 0) (let t := int.coe_nat_le_coe_nat_of_le (nat.succ_pos y) in add_le_add t t)) | -[1+y], y0l, yl2 := y0l trivial end theorem eq_pell_zd (b : ℤ√d) (b1 : 1 ≤ b) (hp : is_pell b) : ∃n, b = pell_zd n := let ⟨n, h⟩ := @zsqrtd.le_arch d b in eq_pell_lem n b b1 hp $ zsqrtd.le_trans h $ by rw zsqrtd.coe_nat_val; exact zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ le_of_lt $ n_lt_xn _ _) (int.coe_zero_le _) theorem eq_pell {x y : ℕ} (hp : x*x - d*y*y = 1) : ∃n, x = xn n ∧ y = yn n := have (1:ℤ√d) ≤ ⟨x, y⟩, from match x, hp with | 0, (hp : 0 - _ = 1) := by rw nat.zero_sub at hp; contradiction | (x+1), hp := zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ nat.succ_pos x) (int.coe_zero_le _) end, let ⟨m, e⟩ := eq_pell_zd ⟨x, y⟩ this (is_pell_nat.2 hp) in ⟨m, match x, y, e with ._, ._, rfl := ⟨rfl, rfl⟩ end⟩ theorem pell_zd_add (m) : ∀ n, pell_zd (m + n) = pell_zd m * pell_zd n | 0 := (mul_one _).symm | (n+1) := by rw[← add_assoc, pell_zd_succ, pell_zd_succ, pell_zd_add n, ← mul_assoc] theorem xn_add (m n) : xn (m + n) = xn m * xn n + d * yn m * yn n := by injection (pell_zd_add _ m n) with h _; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem yn_add (m n) : yn (m + n) = xn m * yn n + yn m * xn n := by injection (pell_zd_add _ m n) with _ h; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem pell_zd_sub {m n} (h : n ≤ m) : pell_zd (m - n) = pell_zd m * (pell_zd n).conj := let t := pell_zd_add n (m - n) in by rw [nat.add_sub_of_le h] at t; rw [t, mul_comm (pell_zd _ n) _, mul_assoc, (is_pell_norm _).1 (is_pell_pell_zd _ _), mul_one] theorem xz_sub {m n} (h : n ≤ m) : xz (m - n) = xz m * xz n - d * yz m * yz n := by injection (pell_zd_sub _ h) with h _; repeat {rw ← neg_mul_eq_mul_neg at h}; exact h theorem yz_sub {m n} (h : n ≤ m) : yz (m - n) = xz n * yz m - xz m * yz n := by injection (pell_zd_sub a1 h) with _ h; repeat {rw ← neg_mul_eq_mul_neg at h}; rw [add_comm, mul_comm] at h; exact h theorem xy_coprime (n) : (xn n).coprime (yn n) := nat.coprime_of_dvd' $ λk kp kx ky, let p := pell_eq n in by rw ← p; exact nat.dvd_sub (le_of_lt $ nat.lt_of_sub_eq_succ p) (dvd_mul_of_dvd_right kx _) (dvd_mul_of_dvd_right ky _) theorem y_increasing {m} : Π {n}, m < n → yn m < yn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have yn m ≤ yn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ y_increasing hl) (λe, by rw e), by simp; refine lt_of_le_of_lt _ (nat.lt_add_of_pos_left $ x_pos a1 n); rw ← mul_one (yn a1 m); exact mul_le_mul this (le_of_lt a1) (nat.zero_le _) (nat.zero_le _) theorem x_increasing {m} : Π {n}, m < n → xn m < xn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have xn m ≤ xn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ x_increasing hl) (λe, by rw e), by simp; refine lt_of_lt_of_le (lt_of_le_of_lt this _) (nat.le_add_right _ _); have t := nat.mul_lt_mul_of_pos_left a1 (x_pos a1 n); rwa mul_one at t theorem yn_ge_n : Π n, n ≤ yn n | 0 := nat.zero_le _ | (n+1) := show n < yn (n+1), from lt_of_le_of_lt (yn_ge_n n) (y_increasing $ nat.lt_succ_self n) theorem y_mul_dvd (n) : ∀k, yn n ∣ yn (n * k) | 0 := dvd_zero _ | (k+1) := by rw [nat.mul_succ, yn_add]; exact dvd_add (dvd_mul_left _ _) (dvd_mul_of_dvd_left (y_mul_dvd k) _) theorem y_dvd_iff (m n) : yn m ∣ yn n ↔ m ∣ n := ⟨λh, nat.dvd_of_mod_eq_zero $ (nat.eq_zero_or_pos _).resolve_right $ λhp, have co : nat.coprime (yn m) (xn (m * (n / m))), from nat.coprime.symm $ (xy_coprime _).coprime_dvd_right (y_mul_dvd m (n / m)), have m0 : 0 < m, from m.eq_zero_or_pos.resolve_left $ λe, by rw [e, nat.mod_zero] at hp; rw [e] at h; exact have 0 < yn a1 n, from y_increasing _ hp, ne_of_lt (y_increasing a1 hp) (eq_zero_of_zero_dvd h).symm, by rw [← nat.mod_add_div n m, yn_add] at h; exact not_le_of_gt (y_increasing _ $ nat.mod_lt n m0) (nat.le_of_dvd (y_increasing _ hp) $ co.dvd_of_dvd_mul_right $ (nat.dvd_add_iff_right $ dvd_mul_of_dvd_right (y_mul_dvd _ _ _) _).2 h), λ⟨k, e⟩, by rw e; apply y_mul_dvd⟩ theorem xy_modeq_yn (n) : ∀k, xn (n * k) ≡ (xn n)^k [MOD (yn n)^2] ∧ yn (n * k) ≡ k * (xn n)^(k-1) * yn n [MOD (yn n)^3] | 0 := by constructor; simp | (k+1) := let ⟨hx, hy⟩ := xy_modeq_yn k in have L : xn (n * k) * xn n + d * yn (n * k) * yn n ≡ xn n^k * xn n + 0 [MOD yn n^2], from modeq.modeq_add (modeq.modeq_mul_right _ hx) $ modeq.modeq_zero_iff.2 $ by rw pow_succ'; exact mul_dvd_mul_right (dvd_mul_of_dvd_right (modeq.modeq_zero_iff.1 $ (hy.modeq_of_dvd_of_modeq $ by simp [pow_succ']).trans $ modeq.modeq_zero_iff.2 $ by simp [-mul_comm, -mul_assoc]) _) _, have R : xn (n * k) * yn n + yn (n * k) * xn n ≡ xn n^k * yn n + k * xn n^k * yn n [MOD yn n^3], from modeq.modeq_add (by rw pow_succ'; exact modeq.modeq_mul_right' _ hx) $ have k * xn n^(k - 1) * yn n * xn n = k * xn n^k * yn n, by clear _let_match; cases k with k; simp [pow_succ', mul_comm, mul_left_comm], by rw ← this; exact modeq.modeq_mul_right _ hy, by rw [nat.add_sub_cancel, nat.mul_succ, xn_add, yn_add, pow_succ' (xn _ n), nat.succ_mul, add_comm (k * xn _ n^k) (xn _ n^k), right_distrib]; exact ⟨L, R⟩ theorem ysq_dvd_yy (n) : yn n * yn n ∣ yn (n * yn n) := modeq.modeq_zero_iff.1 $ ((xy_modeq_yn n (yn n)).right.modeq_of_dvd_of_modeq $ by simp [pow_succ]).trans (modeq.modeq_zero_iff.2 $ by simp [mul_dvd_mul_left, mul_assoc]) theorem dvd_of_ysq_dvd {n t} (h : yn n * yn n ∣ yn t) : yn n ∣ t := have nt : n ∣ t, from (y_dvd_iff n t).1 $ dvd_of_mul_left_dvd h, n.eq_zero_or_pos.elim (λn0, by rw n0; rw n0 at nt; exact nt) $ λ(n0l : 0 < n), let ⟨k, ke⟩ := nt in have yn n ∣ k * (xn n)^(k-1), from nat.dvd_of_mul_dvd_mul_right (y_increasing n0l) $ modeq.modeq_zero_iff.1 $ by have xm := (xy_modeq_yn a1 n k).right; rw ← ke at xm; exact (xm.modeq_of_dvd_of_modeq $ by simp [pow_succ]).symm.trans (modeq.modeq_zero_iff.2 h), by rw ke; exact dvd_mul_of_dvd_right (((xy_coprime _ _).pow_left _).symm.dvd_of_dvd_mul_right this) _ theorem pell_zd_succ_succ (n) : pell_zd (n + 2) + pell_zd n = (2 * a : ℕ) * pell_zd (n + 1) := have (1:ℤ√d) + ⟨a, 1⟩ * ⟨a, 1⟩ = ⟨a, 1⟩ * (2 * a), by { rw zsqrtd.coe_nat_val, change (⟨_,_⟩:ℤ√(d a1))=⟨_,_⟩, rw dz_val, change az a1 with a, rw zsqrtd.ext, dsimp, split; ring }, by simpa [mul_add, mul_comm, mul_left_comm, add_comm] using congr_arg (* pell_zd a1 n) this theorem xy_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) ∧ yn (n + 2) + yn n = (2 * a) * yn (n + 1) := begin have := pell_zd_succ_succ a1 n, unfold pell_zd at this, rw [← int.cast_coe_nat, zsqrtd.smul_val] at this, injection this with h₁ h₂, split; apply int.coe_nat_inj; [simpa using h₁, simpa using h₂] end theorem xn_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) := (xy_succ_succ n).1 theorem yn_succ_succ (n) : yn (n + 2) + yn n = (2 * a) * yn (n + 1) := (xy_succ_succ n).2 theorem xz_succ_succ (n) : xz (n + 2) = (2 * a : ℕ) * xz (n + 1) - xz n := eq_sub_of_add_eq $ by delta xz; rw [← int.coe_nat_add, ← int.coe_nat_mul, xn_succ_succ] theorem yz_succ_succ (n) : yz (n + 2) = (2 * a : ℕ) * yz (n + 1) - yz n := eq_sub_of_add_eq $ by delta yz; rw [← int.coe_nat_add, ← int.coe_nat_mul, yn_succ_succ] theorem yn_modeq_a_sub_one : ∀ n, yn n ≡ n [MOD a-1] | 0 := by simp | 1 := by simp | (n+2) := modeq.modeq_add_cancel_right (yn_modeq_a_sub_one n) $ have 2*(n+1) = n+2+n, by ring, by rw [yn_succ_succ, ← this]; refine modeq.modeq_mul (modeq.modeq_mul_left 2 (_ : a ≡ 1 [MOD a-1])) (yn_modeq_a_sub_one (n+1)); exact (modeq.modeq_of_dvd $ by rw [int.coe_nat_sub $ le_of_lt a1]; apply dvd_refl).symm theorem yn_modeq_two : ∀ n, yn n ≡ n [MOD 2] | 0 := by simp | 1 := by simp | (n+2) := modeq.modeq_add_cancel_right (yn_modeq_two n) $ have 2*(n+1) = n+2+n, by ring, by rw [yn_succ_succ, ← this]; refine modeq.modeq_mul _ (yn_modeq_two (n+1)); exact modeq.trans (modeq.modeq_zero_iff.2 $ by simp) (modeq.modeq_zero_iff.2 $ by simp).symm lemma x_sub_y_dvd_pow_lem (y2 y1 y0 yn1 yn0 xn1 xn0 ay a2 : ℤ) : (a2 * yn1 - yn0) * ay + y2 - (a2 * xn1 - xn0) = y2 - a2 * y1 + y0 + a2 * (yn1 * ay + y1 - xn1) - (yn0 * ay + y0 - xn0) := by ring theorem x_sub_y_dvd_pow (y : ℕ) : ∀ n, (2*a*y - y*y - 1 : ℤ) ∣ yz n * (a - y) + ↑(y^n) - xz n | 0 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | 1 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | (n+2) := have (2*a*y - y*y - 1 : ℤ) ∣ ↑(y^(n + 2)) - ↑(2 * a) * ↑(y^(n + 1)) + ↑(y^n), from ⟨-↑(y^n), by simp [pow_succ, mul_add, int.coe_nat_mul, show ((2:ℕ):ℤ) = 2, from rfl, mul_comm, mul_left_comm]; ring ⟩, by rw [xz_succ_succ, yz_succ_succ, x_sub_y_dvd_pow_lem a1 ↑(y^(n+2)) ↑(y^(n+1)) ↑(y^n)]; exact dvd_sub (dvd_add this $ dvd_mul_of_dvd_right (x_sub_y_dvd_pow (n+1)) _) (x_sub_y_dvd_pow n) theorem xn_modeq_x2n_add_lem (n j) : xn n ∣ d * yn n * (yn n * xn j) + xn j := have h1 : d * yn n * (yn n * xn j) + xn j = (d * yn n * yn n + 1) * xn j, by simp [add_mul, mul_assoc], have h2 : d * yn n * yn n + 1 = xn n * xn n, by apply int.coe_nat_inj; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; exact add_eq_of_eq_sub' (eq.symm $ pell_eqz _ _), by rw h2 at h1; rw [h1, mul_assoc]; exact dvd_mul_right _ _ theorem xn_modeq_x2n_add (n j) : xn (2 * n + j) + xn j ≡ 0 [MOD xn n] := by rw [two_mul, add_assoc, xn_add, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_right (xn a1 n) (xn a1 (n + j))) $ by rw [yn_add, left_distrib, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_of_dvd_right (dvd_mul_right _ _) _) $ modeq.modeq_zero_iff.2 $ xn_modeq_x2n_add_lem _ _ _ lemma xn_modeq_x2n_sub_lem {n j} (h : j ≤ n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := have h1 : xz n ∣ ↑d * yz n * yz (n - j) + xz j, by rw [yz_sub _ h, mul_sub_left_distrib, sub_add_eq_add_sub]; exact dvd_sub (by delta xz; delta yz; repeat {rw ← int.coe_nat_add <|> rw ← int.coe_nat_mul}; rw mul_comm (xn a1 j) (yn a1 n); exact int.coe_nat_dvd.2 (xn_modeq_x2n_add_lem _ _ _)) (dvd_mul_of_dvd_right (dvd_mul_right _ _) _), by rw [two_mul, nat.add_sub_assoc h, xn_add, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_right _ _) $ modeq.modeq_zero_iff.2 $ int.coe_nat_dvd.1 $ by simpa [xz, yz] using h1 theorem xn_modeq_x2n_sub {n j} (h : j ≤ 2 * n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := (le_total j n).elim xn_modeq_x2n_sub_lem (λjn, have 2 * n - j + j ≤ n + j, by rw [nat.sub_add_cancel h, two_mul]; exact nat.add_le_add_left jn _, let t := xn_modeq_x2n_sub_lem (nat.le_of_add_le_add_right this) in by rwa [nat.sub_sub_self h, add_comm] at t) theorem xn_modeq_x4n_add (n j) : xn (4 * n + j) ≡ xn j [MOD xn n] := modeq.modeq_add_cancel_right (modeq.refl $ xn (2 * n + j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_add _ _ _).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, add_assoc]; apply xn_modeq_x2n_add theorem xn_modeq_x4n_sub {n j} (h : j ≤ 2 * n) : xn (4 * n - j) ≡ xn j [MOD xn n] := have h' : j ≤ 2*n, from le_trans h (by rw nat.succ_mul; apply nat.le_add_left), modeq.modeq_add_cancel_right (modeq.refl $ xn (2 * n - j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_sub _ h).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, nat.add_sub_assoc h']; apply xn_modeq_x2n_add theorem eq_of_xn_modeq_lem1 {i n} : Π {j}, i < j → j < n → xn i % xn n < xn j % xn n | 0 ij _ := absurd ij (nat.not_lt_zero _) | (j+1) ij jn := suffices xn j % xn n < xn (j + 1) % xn n, from (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem1 h (le_of_lt jn)) this) (λh, by rw h; exact this), by rw [nat.mod_eq_of_lt (x_increasing _ (nat.lt_of_succ_lt jn)), nat.mod_eq_of_lt (x_increasing _ jn)]; exact x_increasing _ (nat.lt_succ_self _) theorem eq_of_xn_modeq_lem2 {n} (h : 2 * xn n = xn (n + 1)) : a = 2 ∧ n = 0 := by rw [xn_succ, mul_comm] at h; exact have n = 0, from n.eq_zero_or_pos.resolve_right $ λnp, ne_of_lt (lt_of_le_of_lt (nat.mul_le_mul_left _ a1) (nat.lt_add_of_pos_right $ mul_pos (d_pos a1) (y_increasing a1 np))) h, by cases this; simp at h; exact ⟨h.symm, rfl⟩ theorem eq_of_xn_modeq_lem3 {i n} (npos : 0 < n) : Π {j}, i < j → j ≤ 2 * n → j ≠ n → ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2) → xn i % xn n < xn j % xn n | 0 ij _ _ _ := absurd ij (nat.not_lt_zero _) | (j+1) ij j2n jnn ntriv := have lem2 : ∀k > n, k ≤ 2*n → (↑(xn k % xn n) : ℤ) = xn n - xn (2 * n - k), from λk kn k2n, let k2nl := lt_of_add_lt_add_right $ show 2*n-k+k < n+k, by {rw nat.sub_add_cancel, rw two_mul; exact (add_lt_add_left kn n), exact k2n } in have xle : xn (2 * n - k) ≤ xn n, from le_of_lt $ x_increasing k2nl, suffices xn k % xn n = xn n - xn (2 * n - k), by rw [this, int.coe_nat_sub xle], by { rw ← nat.mod_eq_of_lt (nat.sub_lt (x_pos a1 n) (x_pos a1 (2 * n - k))), apply modeq.modeq_add_cancel_right (modeq.refl (xn a1 (2 * n - k))), rw [nat.sub_add_cancel xle], have t := xn_modeq_x2n_sub_lem a1 (le_of_lt k2nl), rw nat.sub_sub_self k2n at t, exact t.trans (modeq.modeq_zero_iff.2 $ dvd_refl _).symm }, (lt_trichotomy j n).elim (λ (jn : j < n), eq_of_xn_modeq_lem1 ij (lt_of_le_of_ne jn jnn)) $ λo, o.elim (λ (jn : j = n), by { cases jn, apply int.lt_of_coe_nat_lt_coe_nat, rw [lem2 (n+1) (nat.lt_succ_self _) j2n, show 2 * n - (n + 1) = n - 1, by rw[two_mul, ← nat.sub_sub, nat.add_sub_cancel]], refine lt_sub_left_of_add_lt (int.coe_nat_lt_coe_nat_of_lt _), cases (lt_or_eq_of_le $ nat.le_of_succ_le_succ ij) with lin ein, { rw nat.mod_eq_of_lt (x_increasing _ lin), have ll : xn a1 (n-1) + xn a1 (n-1) ≤ xn a1 n, { rw [← two_mul, mul_comm, show xn a1 n = xn a1 (n-1+1), by rw [nat.sub_add_cancel npos], xn_succ], exact le_trans (nat.mul_le_mul_left _ a1) (nat.le_add_right _ _) }, have npm : (n-1).succ = n := nat.succ_pred_eq_of_pos npos, have il : i ≤ n - 1 := by apply nat.le_of_succ_le_succ; rw npm; exact lin, cases lt_or_eq_of_le il with ill ile, { exact lt_of_lt_of_le (nat.add_lt_add_left (x_increasing a1 ill) _) ll }, { rw ile, apply lt_of_le_of_ne ll, rw ← two_mul, exact λe, ntriv $ let ⟨a2, s1⟩ := @eq_of_xn_modeq_lem2 _ a1 (n-1) (by rw[nat.sub_add_cancel npos]; exact e) in have n1 : n = 1, from le_antisymm (nat.le_of_sub_eq_zero s1) npos, by rw [ile, a2, n1]; exact ⟨rfl, rfl, rfl, rfl⟩ } }, { rw [ein, nat.mod_self, add_zero], exact x_increasing _ (nat.pred_lt $ ne_of_gt npos) } }) (λ (jn : j > n), have lem1 : j ≠ n → xn j % xn n < xn (j + 1) % xn n → xn i % xn n < xn (j + 1) % xn n, from λjn s, (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem3 h (le_of_lt j2n) jn $ λ⟨a1, n1, i0, j2⟩, by rw [n1, j2] at j2n; exact absurd j2n dec_trivial) s) (λh, by rw h; exact s), lem1 (ne_of_gt jn) $ int.lt_of_coe_nat_lt_coe_nat $ by { rw [lem2 j jn (le_of_lt j2n), lem2 (j+1) (nat.le_succ_of_le jn) j2n], refine sub_lt_sub_left (int.coe_nat_lt_coe_nat_of_lt $ x_increasing _ _) _, rw [nat.sub_succ], exact nat.pred_lt (ne_of_gt $ nat.sub_pos_of_lt j2n) }) theorem eq_of_xn_modeq_le {i j n} (npos : 0 < n) (ij : i ≤ j) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2)) : i = j := (lt_or_eq_of_le ij).resolve_left $ λij', if jn : j = n then by { refine ne_of_gt _ h, rw [jn, nat.mod_self], have x0 : 0 < xn a1 0 % xn a1 n := by rw [nat.mod_eq_of_lt (x_increasing a1 npos)]; exact dec_trivial, cases i with i, exact x0, rw jn at ij', exact lt_trans x0 (eq_of_xn_modeq_lem3 _ npos (nat.succ_pos _) (le_trans ij j2n) (ne_of_lt ij') $ λ⟨a1, n1, _, i2⟩, by rw [n1, i2] at ij'; exact absurd ij' dec_trivial) } else ne_of_lt (eq_of_xn_modeq_lem3 npos ij' j2n jn ntriv) h theorem eq_of_xn_modeq {i j n} (npos : 0 < n) (i2n : i ≤ 2 * n) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : a = 2 → n = 1 → (i = 0 → j ≠ 2) ∧ (i = 2 → j ≠ 0)) : i = j := (le_total i j).elim (λij, eq_of_xn_modeq_le npos ij j2n h $ λ⟨a2, n1, i0, j2⟩, (ntriv a2 n1).left i0 j2) (λij, (eq_of_xn_modeq_le npos ij i2n h.symm $ λ⟨a2, n1, j0, i2⟩, (ntriv a2 n1).right i2 j0).symm) theorem eq_of_xn_modeq' {i j n} (ipos : 0 < i) (hin : i ≤ n) (j4n : j ≤ 4 * n) (h : xn j ≡ xn i [MOD xn n]) : j = i ∨ j + i = 4 * n := have i2n : i ≤ 2*n, by apply le_trans hin; rw two_mul; apply nat.le_add_left, have npos : 0 < n, from lt_of_lt_of_le ipos hin, (le_or_gt j (2 * n)).imp (λj2n : j ≤ 2 * n, eq_of_xn_modeq npos j2n i2n h $ λa2 n1, ⟨λj0 i2, by rw [n1, i2] at hin; exact absurd hin dec_trivial, λj2 i0, ne_of_gt ipos i0⟩) (λj2n : 2 * n < j, suffices i = 4*n - j, by rw [this, nat.add_sub_of_le j4n], have j42n : 4*n - j ≤ 2*n, from @nat.le_of_add_le_add_right j _ _ $ by rw [nat.sub_add_cancel j4n, show 4*n = 2*n + 2*n, from right_distrib 2 2 n]; exact nat.add_le_add_left (le_of_lt j2n) _, eq_of_xn_modeq npos i2n j42n (h.symm.trans $ let t := xn_modeq_x4n_sub j42n in by rwa [nat.sub_sub_self j4n] at t) (λa2 n1, ⟨λi0, absurd i0 (ne_of_gt ipos), λi2, by rw[n1, i2] at hin; exact absurd hin dec_trivial⟩)) theorem modeq_of_xn_modeq {i j n} (ipos : 0 < i) (hin : i ≤ n) (h : xn j ≡ xn i [MOD xn n]) : j ≡ i [MOD 4 * n] ∨ j + i ≡ 0 [MOD 4 * n] := let j' := j % (4 * n) in have n4 : 0 < 4 * n, from mul_pos dec_trivial (lt_of_lt_of_le ipos hin), have jl : j' < 4 * n, from nat.mod_lt _ n4, have jj : j ≡ j' [MOD 4 * n], by delta modeq; rw nat.mod_eq_of_lt jl, have ∀j q, xn (j + 4 * n * q) ≡ xn j [MOD xn n], begin intros j q, induction q with q IH, { simp }, rw[nat.mul_succ, ← add_assoc, add_comm], exact modeq.trans (xn_modeq_x4n_add _ _ _) IH end, or.imp (λ(ji : j' = i), by rwa ← ji) (λ(ji : j' + i = 4 * n), (modeq.modeq_add jj (modeq.refl _)).trans $ by rw ji; exact modeq.modeq_zero_iff.2 (dvd_refl _)) (eq_of_xn_modeq' ipos hin (le_of_lt jl) $ (modeq.symm (by rw ← nat.mod_add_div j (4*n); exact this j' _)).trans h) end theorem xy_modeq_of_modeq {a b c} (a1 : 1 < a) (b1 : 1 < b) (h : a ≡ b [MOD c]) : ∀ n, xn a1 n ≡ xn b1 n [MOD c] ∧ yn a1 n ≡ yn b1 n [MOD c] | 0 := by constructor; refl | 1 := by simp; exact ⟨h, modeq.refl 1⟩ | (n+2) := ⟨ modeq.modeq_add_cancel_right (xy_modeq_of_modeq n).left $ by rw [xn_succ_succ a1, xn_succ_succ b1]; exact modeq.modeq_mul (modeq.modeq_mul_left _ h) (xy_modeq_of_modeq (n+1)).left, modeq.modeq_add_cancel_right (xy_modeq_of_modeq n).right $ by rw [yn_succ_succ a1, yn_succ_succ b1]; exact modeq.modeq_mul (modeq.modeq_mul_left _ h) (xy_modeq_of_modeq (n+1)).right⟩ theorem matiyasevic {a k x y} : (∃ a1 : 1 < a, xn a1 k = x ∧ yn a1 k = y) ↔ 1 < a ∧ k ≤ y ∧ (x = 1 ∧ y = 0 ∨ ∃ (u v s t b : ℕ), x * x - (a * a - 1) * y * y = 1 ∧ u * u - (a * a - 1) * v * v = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ b ≡ 1 [MOD 4 * y] ∧ b ≡ a [MOD u] ∧ 0 < v ∧ y * y ∣ v ∧ s ≡ x [MOD u] ∧ t ≡ k [MOD 4 * y]) := ⟨λ⟨a1, hx, hy⟩, by rw [← hx, ← hy]; refine ⟨a1, (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact ⟨le_refl _, or.inl ⟨rfl, rfl⟩⟩) (λkpos, _)⟩; exact let x := xn a1 k, y := yn a1 k, m := 2 * (k * y), u := xn a1 m, v := yn a1 m in have ky : k ≤ y, from yn_ge_n a1 k, have yv : y * y ∣ v, from dvd_trans (ysq_dvd_yy a1 k) $ (y_dvd_iff _ _ _).2 $ dvd_mul_left _ _, have uco : nat.coprime u (4 * y), from have 2 ∣ v, from modeq.modeq_zero_iff.1 $ (yn_modeq_two _ _).trans $ modeq.modeq_zero_iff.2 (dvd_mul_right _ _), have nat.coprime u 2, from (xy_coprime a1 m).coprime_dvd_right this, (this.mul_right this).mul_right $ (xy_coprime _ _).coprime_dvd_right (dvd_of_mul_left_dvd yv), let ⟨b, ba, bm1⟩ := modeq.chinese_remainder uco a 1 in have m1 : 1 < m, from have 0 < k * y, from mul_pos kpos (y_increasing a1 kpos), nat.mul_le_mul_left 2 this, have vp : 0 < v, from y_increasing a1 (lt_trans zero_lt_one m1), have b1 : 1 < b, from have xn a1 1 < u, from x_increasing a1 m1, have a < u, by simp at this; exact this, lt_of_lt_of_le a1 $ by delta modeq at ba; rw nat.mod_eq_of_lt this at ba; rw ← ba; apply nat.mod_le, let s := xn b1 k, t := yn b1 k in have sx : s ≡ x [MOD u], from (xy_modeq_of_modeq b1 a1 ba k).left, have tk : t ≡ k [MOD 4 * y], from have 4 * y ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact modeq.dvd_of_modeq bm1.symm, modeq.modeq_of_dvd_of_modeq this $ yn_modeq_a_sub_one _ _, ⟨ky, or.inr ⟨u, v, s, t, b, pell_eq _ _, pell_eq _ _, pell_eq _ _, b1, bm1, ba, vp, yv, sx, tk⟩⟩, λ⟨a1, ky, o⟩, ⟨a1, match o with | or.inl ⟨x1, y0⟩ := by rw y0 at ky; rw [nat.eq_zero_of_le_zero ky, x1, y0]; exact ⟨rfl, rfl⟩ | or.inr ⟨u, v, s, t, b, xy, uv, st, b1, rem⟩ := match x, y, eq_pell a1 xy, u, v, eq_pell a1 uv, s, t, eq_pell b1 st, rem, ky with | ._, ._, ⟨i, rfl, rfl⟩, ._, ._, ⟨n, rfl, rfl⟩, ._, ._, ⟨j, rfl, rfl⟩, ⟨(bm1 : b ≡ 1 [MOD 4 * yn a1 i]), (ba : b ≡ a [MOD xn a1 n]), (vp : 0 < yn a1 n), (yv : yn a1 i * yn a1 i ∣ yn a1 n), (sx : xn b1 j ≡ xn a1 i [MOD xn a1 n]), (tk : yn b1 j ≡ k [MOD 4 * yn a1 i])⟩, (ky : k ≤ yn a1 i) := (nat.eq_zero_or_pos i).elim (λi0, by simp [i0] at ky; rw [i0, ky]; exact ⟨rfl, rfl⟩) $ λipos, suffices i = k, by rw this; exact ⟨rfl, rfl⟩, by clear _x o rem xy uv st _match _match _fun_match; exact have iln : i ≤ n, from le_of_not_gt $ λhin, not_lt_of_ge (nat.le_of_dvd vp (dvd_of_mul_left_dvd yv)) (y_increasing a1 hin), have yd : 4 * yn a1 i ∣ 4 * n, from mul_dvd_mul_left _ $ dvd_of_ysq_dvd a1 yv, have jk : j ≡ k [MOD 4 * yn a1 i], from have 4 * yn a1 i ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact modeq.dvd_of_modeq bm1.symm, (modeq.modeq_of_dvd_of_modeq this (yn_modeq_a_sub_one b1 _)).symm.trans tk, have ki : k + i < 4 * yn a1 i, from lt_of_le_of_lt (add_le_add ky (yn_ge_n a1 i)) $ by rw ← two_mul; exact nat.mul_lt_mul_of_pos_right dec_trivial (y_increasing a1 ipos), have ji : j ≡ i [MOD 4 * n], from have xn a1 j ≡ xn a1 i [MOD xn a1 n], from (xy_modeq_of_modeq b1 a1 ba j).left.symm.trans sx, (modeq_of_xn_modeq a1 ipos iln this).resolve_right $ λ (ji : j + i ≡ 0 [MOD 4 * n]), not_le_of_gt ki $ nat.le_of_dvd (lt_of_lt_of_le ipos $ nat.le_add_left _ _) $ modeq.modeq_zero_iff.1 $ (modeq.modeq_add jk.symm (modeq.refl i)).trans $ modeq.modeq_of_dvd_of_modeq yd ji, by have : i % (4 * yn a1 i) = k % (4 * yn a1 i) := (modeq.modeq_of_dvd_of_modeq yd ji).symm.trans jk; rwa [nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_left _ _) ki), nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_right _ _) ki)] at this end end⟩⟩ lemma eq_pow_of_pell_lem {a y k} (a1 : 1 < a) (ypos : 0 < y) : 0 < k → y^k < a → (↑(y^k) : ℤ) < 2*a*y - y*y - 1 := have y < a → a + (y*y + 1) ≤ 2*a*y, begin intro ya, induction y with y IH, exact absurd ypos (lt_irrefl _), cases nat.eq_zero_or_pos y with y0 ypos, { rw y0, simpa [two_mul], }, { rw [nat.mul_succ, nat.mul_succ, nat.succ_mul y], have : y + nat.succ y ≤ 2 * a, { change y + y < 2 * a, rw ← two_mul, exact mul_lt_mul_of_pos_left (nat.lt_of_succ_lt ya) dec_trivial }, have := add_le_add (IH ypos (nat.lt_of_succ_lt ya)) this, convert this using 1, ring } end, λk0 yak, lt_of_lt_of_le (int.coe_nat_lt_coe_nat_of_lt yak) $ by rw sub_sub; apply le_sub_right_of_add_le; apply int.coe_nat_le_coe_nat_of_le; have y1 := nat.pow_le_pow_of_le_right ypos k0; simp at y1; exact this (lt_of_le_of_lt y1 yak) theorem eq_pow_of_pell {m n k} : (n^k = m ↔ k = 0 ∧ m = 1 ∨ 0 < k ∧ (n = 0 ∧ m = 0 ∨ 0 < n ∧ ∃ (w a t z : ℕ) (a1 : 1 < a), xn a1 k ≡ yn a1 k * (a - n) + m [MOD t] ∧ 2 * a * n = t + (n * n + 1) ∧ m < t ∧ n ≤ w ∧ k ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)) := ⟨λe, by rw ← e; refine (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact or.inl ⟨rfl, rfl⟩) (λkpos, or.inr ⟨kpos, _⟩); refine (nat.eq_zero_or_pos n).elim (λn0, by rw [n0, zero_pow kpos]; exact or.inl ⟨rfl, rfl⟩) (λnpos, or.inr ⟨npos, _⟩); exact let w := _root_.max n k in have nw : n ≤ w, from le_max_left _ _, have kw : k ≤ w, from le_max_right _ _, have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let a := xn w1 w in have a1 : 1 < a, from x_increasing w1 wpos, let x := xn a1 k, y := yn a1 k in let ⟨z, ze⟩ := show w ∣ yn w1 w, from modeq.modeq_zero_iff.1 $ modeq.trans (yn_modeq_a_sub_one w1 w) (modeq.modeq_zero_iff.2 $ dvd_refl _) in have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^w : nat.pow_le_pow_of_le_right npos kw ... < (w + 1)^w : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) wpos ... ≤ a : xn_ge_a_pow w1 w, let ⟨t, te⟩ := int.eq_coe_of_zero_le $ le_trans (int.coe_zero_le _) $ le_of_lt nt in have na : n ≤ a, from le_trans nw $ le_of_lt $ n_lt_xn w1 w, have tm : x ≡ y * (a - n) + n^k [MOD t], begin apply modeq.modeq_of_dvd, rw [int.coe_nat_add, int.coe_nat_mul, int.coe_nat_sub na, ← te], exact x_sub_y_dvd_pow a1 n k end, have ta : 2 * a * n = t + (n * n + 1), from int.coe_nat_inj $ by rw [int.coe_nat_add, ← te, sub_sub]; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; rw [int.coe_nat_one, sub_add_cancel]; refl, have mt : n^k < t, from int.lt_of_coe_nat_lt_coe_nat $ by rw ← te; exact nt, have zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1, by rw ← ze; exact pell_eq w1 w, ⟨w, a, t, z, a1, tm, ta, mt, nw, kw, zp⟩, λo, match o with | or.inl ⟨k0, m1⟩ := by rw [k0, m1]; refl | or.inr ⟨kpos, or.inl ⟨n0, m0⟩⟩ := by rw [n0, m0, zero_pow kpos] | or.inr ⟨kpos, or.inr ⟨npos, w, a, t, z, (a1 : 1 < a), (tm : xn a1 k ≡ yn a1 k * (a - n) + m [MOD t]), (ta : 2 * a * n = t + (n * n + 1)), (mt : m < t), (nw : n ≤ w), (kw : k ≤ w), (zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)⟩⟩ := have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let ⟨j, xj, yj⟩ := eq_pell w1 zp in by clear _match o _let_match; exact have jpos : 0 < j, from (nat.eq_zero_or_pos j).resolve_left $ λj0, have a1 : a = 1, by rw j0 at xj; exact xj, have 2 * n = t + (n * n + 1), by rw a1 at ta; exact ta, have n1 : n = 1, from have n * n < n * 2, by rw [mul_comm n 2, this]; apply nat.le_add_left, have n ≤ 1, from nat.le_of_lt_succ $ lt_of_mul_lt_mul_left this (nat.zero_le _), le_antisymm this npos, by rw n1 at this; rw ← @nat.add_right_cancel 0 2 t this at mt; exact nat.not_lt_zero _ mt, have wj : w ≤ j, from nat.le_of_dvd jpos $ modeq.modeq_zero_iff.1 $ (yn_modeq_a_sub_one w1 j).symm.trans $ modeq.modeq_zero_iff.2 ⟨z, yj.symm⟩, have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^j : nat.pow_le_pow_of_le_right npos (le_trans kw wj) ... < (w + 1)^j : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) jpos ... ≤ xn w1 j : xn_ge_a_pow w1 j ... = a : xj.symm, have na : n ≤ a, by rw xj; exact le_trans (le_trans nw wj) (le_of_lt $ n_lt_xn _ _), have te : (t : ℤ) = 2 * ↑a * ↑n - ↑n * ↑n - 1, by rw sub_sub; apply eq_sub_of_add_eq; apply (int.coe_nat_eq_coe_nat_iff _ _).2; exact ta.symm, have xn a1 k ≡ yn a1 k * (a - n) + n^k [MOD t], by have := x_sub_y_dvd_pow a1 n k; rw [← te, ← int.coe_nat_sub na] at this; exact modeq.modeq_of_dvd this, have n^k % t = m % t, from modeq.modeq_add_cancel_left (modeq.refl _) (this.symm.trans tm), by rw ← te at nt; rwa [nat.mod_eq_of_lt (int.lt_of_coe_nat_lt_coe_nat nt), nat.mod_eq_of_lt mt] at this end⟩ end pell
35312b55b7fb8e138d2b1d524488cb2e1a627dc1
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coe14.lean
530470c332f47d45728c69380d81b81cf8445a8a
[ "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
558
lean
import data.nat open nat inductive functor (A B : Type) := mk : (A → B) → functor A B definition functor.to_fun [coercion] {A B : Type} (f : functor A B) : A → B := functor.rec (λ f, f) f inductive struct := mk : Π (A : Type), (A → A → Prop) → struct definition struct.to_sort [coercion] (s : struct) : Type := struct.rec (λA r, A) s definition g (f : nat → nat) (a : nat) := f a constant f : functor nat nat check g (functor.to_fun f) 0 check g f 0 constant S : struct constant a : S check @id (struct.to_sort S) a check @id S a
9d9276bf731741ff1774d8e4b24a200b48c680e5
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/have5.lean
1046f87662733c3dadbbae2647f3e1c965d5a63f
[ "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
234
lean
import logic open tactic constants a b c d : Prop axiom Ha : a axiom Hb : b axiom Hc : c print raw have H1 : a, by assumption, then have H2 : b, by assumption, have H3 : c, by assumption, then have H4 : d, by assumption, H4
0edcf30f8d366e52e1845487e35351c00c833ba9
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/list/basic.lean
a37a9db4c5838e610e9549f39fe2ab3ed3cdcdf7
[ "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
141,156
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.nat.basic /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {ι : Type*} {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l := mt (congr_arg length) (nat.succ_ne_self _) theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) @[simp] theorem cons_injective {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := cons_injective.eq_iff theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L := by { induction l with c l', contradiction, use [c,l'], } /-! ### mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem _root_.decidable.list.eq_or_ne_mem_of_mem [decidable_eq α] {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := decidable.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} : a ∈ b :: l → a = b ∨ (a ≠ b ∧ a ∈ l) := by classical; exact decidable.list.eq_or_ne_mem_of_mem theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := begin -- This proof uses no axioms, that's why it's longer that `induction`; simp [...] induction l with a l ihl, { split, { rintro ⟨_⟩ }, { rintro ⟨a, ⟨_⟩, _⟩ } }, { refine (or_congr eq_comm ihl).trans _, split, { rintro (h|⟨c, hcl, h⟩), exacts [⟨a, or.inl rfl, h⟩, ⟨c, or.inr hcl, h⟩] }, { rintro ⟨c, (hc|hc), h⟩, exacts [or.inl $ (congr_arg f hc.symm).trans h, or.inr ⟨c, hc, h⟩] } } end alias mem_map ↔ list.exists_of_mem_map _ theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := mem_map.2 ⟨a, h, rfl⟩ theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] lemma map_bind (g : β → list γ) (f : α → β) : ∀ l : list α, (list.map f l).bind g = l.bind (λ a, g (f a)) | [] := rfl | (a::l) := by simp only [cons_bind, map_cons, map_bind l] /-- If each element of a list can be lifted to some type, then the whole list can be lifted to this type. -/ instance [h : can_lift α β] : can_lift (list α) (list β) := { coe := list.map h.coe, cond := λ l, ∀ x ∈ l, can_lift.cond β x, prf := λ l H, begin induction l with a l ihl, { exact ⟨[], rfl⟩ }, rcases ihl (λ x hx, H x (or.inr hx)) with ⟨l, rfl⟩, rcases can_lift.prf a (H a (or.inl rfl)) with ⟨a, rfl⟩, exact ⟨a :: l, rfl⟩ end} /-! ### length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ @[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ lemma exists_mem_of_ne_nil (l : list α) (h : l ≠ []) : ∃ x, x ∈ l := exists_mem_of_length_pos (length_pos_of_ne_nil h) theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ @[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end @[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) := length_injective_iff.mpr $ by apply_instance lemma length_eq_two {l : list α} : l.length = 2 ↔ ∃ a b, l = [a, b] := ⟨match l with [a, b], _ := ⟨a, b, rfl⟩ end, λ ⟨a, b, e⟩, e.symm ▸ rfl⟩ lemma length_eq_three {l : list α} : l.length = 3 ↔ ∃ a b c, l = [a, b, c] := ⟨match l with [a, b, c], _ := ⟨a, b, c, rfl⟩ end, λ ⟨a, b, c, e⟩, e.symm ▸ rfl⟩ /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] := by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] } /-! ### bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : list α}, (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := ball_cons theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /-! ### list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl @[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_injective (s : list α) : function.injective (λ t, s ++ t) := λ t₁ t₂, append_left_cancel theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := (append_right_injective s).eq_iff theorem append_left_injective (t : list α) : function.injective (λ s, s ++ t) := λ s₁ s₂, append_right_cancel theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := (append_left_injective t).eq_iff theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /-! ### repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n ↔ n ≠ 0 ∧ b = a | 0 := by simp | (n + 1) := by simp [mem_repeat] theorem eq_of_mem_repeat {a b : α} {n} (h : b ∈ repeat a n) : b = a := (mem_repeat.1 h).2 theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] lemma repeat_left_injective {n : ℕ} (hn : n ≠ 0) : function.injective (λ a : α, repeat a n) := λ a b h, (eq_repeat.1 h).2 _ $ mem_repeat.2 ⟨hn, rfl⟩ lemma repeat_left_inj {a b : α} {n : ℕ} (hn : n ≠ 0) : repeat a n = repeat b n ↔ a = b := (repeat_left_injective hn).eq_iff @[simp] lemma repeat_left_inj' {a b : α} : ∀ {n}, repeat a n = repeat b n ↔ n = 0 ∨ a = b | 0 := by simp | (n + 1) := (repeat_left_inj n.succ_ne_zero).trans $ by simp only [n.succ_ne_zero, false_or] lemma repeat_right_injective (a : α) : function.injective (repeat a) := function.left_inverse.injective (length_repeat a) @[simp] lemma repeat_right_inj {a : α} {n m : ℕ} : repeat a n = repeat a m ↔ n = m := (repeat_right_injective a).eq_iff /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl -- TODO: duplicate of a lemma in core theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ @[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x := append_nil (f x) @[simp] theorem bind_singleton' (l : list α) : l.bind (λ x, [x]) = l := bind_pure l theorem map_eq_bind {α β} (f : α → β) (l : list α) : map f l = l.bind (λ x, [f x]) := by { transitivity, rw [← bind_singleton' l, bind_map], refl } theorem bind_assoc {α β} (l : list α) (f : α → list β) (g : β → list γ) : (l.bind f).bind g = l.bind (λ x, (f x).bind g) := by induction l; simp * /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ := begin intro h, rw [concat_eq_append, concat_eq_append] at h, exact append_right_cancel h end theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b := begin intro h, rw [concat_eq_append, concat_eq_append] at h, exact head_eq_of_cons_eq (append_left_cancel h) end theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /-! ### reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l := by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl @[simp] theorem reverse_involutive : involutive (@reverse α) := λ l, reverse_reverse l @[simp] theorem reverse_injective : injective (@reverse α) := reverse_involutive.injective @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff lemma reverse_eq_iff {l l' : list α} : l.reverse = l' ↔ l = l'.reverse := reverse_involutive.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ /-! ### empty -/ attribute [simp] list.empty lemma empty_iff_eq_nil {l : list α} : l.empty ↔ l = [] := list.cases_on l (by simp) (by simp) /-! ### init -/ @[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1 | [] := rfl | [a] := rfl | (a :: b :: l) := begin rw init, simp only [add_left_inj, length, succ_add_sub_one], exact length_init (b :: l) end /-! ### last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l | [] h := absurd rfl h | [a] h := rfl | (a::b::l) h := begin rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)], congr, exact init_append_last (cons_ne_nil b l) end theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } lemma last_repeat_succ (a m : ℕ) : (repeat a m.succ).last (ne_nil_of_length_eq_succ (show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a := begin induction m with k IH, { simp }, { simpa only [repeat_succ, last] } end /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem last'_eq_last_of_ne_nil : ∀ {l : list α} (h : l ≠ []), l.last' = some (l.last h) | [] h := (h rfl).elim | [a] _ := by {unfold last, unfold last'} | (a::b::l) _ := @last'_eq_last_of_ne_nil (b::l) (cons_ne_nil _ _) theorem mem_last'_cons {x y : α} : ∀ {l : list α} (h : x ∈ l.last'), x ∈ (y :: l).last' | [] _ := by contradiction | (a::l) h := h theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] @[simp] theorem last'_cons_cons (x y : α) (l : list α) : last' (x :: y :: l) = last' (y :: l) := rfl theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem head'_append {s t : list α} {x : α} (h : x ∈ s.head') : x ∈ (s ++ t).head' := by { cases s, contradiction, exact h } theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) : tail (l ++ [a]) = tail l ++ [a] := by { induction l, contradiction, rw [tail,cons_append,tail], } theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) lemma head_mem_self [inhabited α] {l : list α} (h : l ≠ nil) : l.head ∈ l := begin have h' := mem_cons_self l.head l.tail, rwa cons_head_tail h at h', end @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl lemma tail_append_of_ne_nil (l l' : list α) (h : l ≠ []) : (l ++ l').tail = l.tail ++ l' := begin cases l, { contradiction }, { simp } end @[simp] lemma nth_le_tail (l : list α) (i) (h : i < l.tail.length) (h' : i + 1 < l.length := by simpa [←lt_tsub_iff_right] using h) : l.tail.nth_le i h = l.nth_le (i + 1) h' := begin cases l, { cases h, }, { simpa } end /-! ### Induction from the right -/ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /-- Bidirectional induction principle for lists: if a property holds for the empty list, the singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def bidirectional_rec {C : list α → Sort*} (H0 : C []) (H1 : ∀ (a : α), C [a]) (Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l | [] := H0 | [a] := H1 a | (a :: b :: l) := let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in have length l' < length (a :: b :: l), by { change _ < length l + 2, simp }, begin rw ←init_append_last (cons_ne_nil b l), have : C l', from bidirectional_rec l', exact Hn a l' b' ‹C l'› end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] } /-- Like `bidirectional_rec`, but with the list parameter placed first. -/ @[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a]) (Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l := bidirectional_rec H0 H1 Hn l /-! ### sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem sublist.cons_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := (sublist_append_left l₁ l₂).cons_cons _ @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, sublist.cons_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply ih.cons_cons a } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (sublist.cons_cons _) (mem_cons_of_mem _) } } end theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (sublist.subset s h) end @[simp] theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ ((nil_sublist _).cons_cons _ ).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset @[simp] theorem sublist_nil_iff_eq_nil {l : list α} : l <+ [] ↔ l = [] := ⟨eq_nil_of_sublist_nil, λ H, H ▸ sublist.refl _⟩ @[simp] theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨sublist.cons_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /-! ### index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, decidable.by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /-! ### nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ @[simp] theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n := begin intros, split, { intro h, by_contradiction h', have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩, rw [← nth_eq_some, h] at h₂, cases h₂ }, { solve_by_elim [nth_len_le] }, end theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm lemma nth_zero (l : list α) : l.nth 0 = l.head' := by cases l; refl lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ} (h₀ : i < xs.length) (h₁ : nodup xs) (h₂ : xs.nth i = xs.nth j) : i = j := begin induction xs with x xs generalizing i j, { cases h₀ }, { cases i; cases j, case nat.zero nat.zero { refl }, case nat.succ nat.succ { congr, cases h₁, apply xs_ih; solve_by_elim [lt_of_succ_lt_succ] }, iterate 2 { dsimp at h₂, cases h₁ with _ _ h h', cases h x _ rfl, rw mem_iff_nth, exact ⟨_, h₂.symm⟩ <|> exact ⟨_, h₂⟩ } }, end @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (nat.not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (tsub_lt_tsub_iff_right h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [tsub_add_eq_tsub_tsub, tsub_right_comm, add_tsub_cancel_right], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact nat.le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma nth_append_right {l₁ l₂ : list α} {n : ℕ} (hn : l₁.length ≤ n) : (l₁ ++ l₂).nth n = l₂.nth (n - l₁.length) := begin by_cases hl : n < (l₁ ++ l₂).length, { rw [nth_le_nth hl, nth_le_nth, nth_le_append_right hn] }, { rw [nth_len_le (le_of_not_lt hl), nth_len_le], rw [not_lt, length_append] at hl, exact le_tsub_of_add_le_left hl } end lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (nat.sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] lemma nth_le_cons_length (x : α) (xs : list α) (n : ℕ) (h : n = xs.length) : (x :: xs).nth_le n (by simp [h]) = (x :: xs).last (cons_ne_nil x xs) := begin rw last_eq_nth_le, congr, simp [h] end @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (nat.not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw ← tsub_add_eq_tsub_tsub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma nth_le_reverse' (l : list α) (n : ℕ) (hn : n < l.reverse.length) (hn') : l.reverse.nth_le n hn = l.nth_le (l.length - 1 - n) hn' := begin rw eq_comm, convert nth_le_reverse l.reverse _ _ _ using 1, { simp }, { simpa } end lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [add_tsub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), tsub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma update_nth_nil (n : ℕ) (a : α) : [].update_nth n a = [] := rfl @[simp] lemma update_nth_succ (x : α) (xs : list α) (n : ℕ) (a : α) : (x :: xs).update_nth n.succ a = x :: xs.update_nth n a := rfl lemma update_nth_comm (a b : α) : Π {n m : ℕ} (l : list α) (h : n ≠ m), (l.update_nth n a).update_nth m b = (l.update_nth m b).update_nth n a | _ _ [] _ := by simp | 0 0 (x :: t) h := absurd rfl h | (n + 1) 0 (x :: t) h := by simp [list.update_nth] | 0 (m + 1) (x :: t) h := by simp [list.update_nth] | (n + 1) (m + 1) (x :: t) h := by { simp only [update_nth, true_and, eq_self_iff_true], exact update_nth_comm t (λ h', h $ nat.succ_inj'.mpr h'), } @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_zero (s : list α) (x : α) : insert_nth 0 x s = x :: s := rfl @[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] := rfl @[simp] lemma insert_nth_succ_cons (s : list α) (hd x : α) (n : ℕ) : insert_nth (n + 1) x (hd :: s) = hd :: (insert_nth n x s) := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → n ≤ m → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end lemma inj_on_insert_nth_index_of_not_mem (l : list α) (x : α) (hx : x ∉ l) : set.inj_on (λ k, insert_nth k x l) {n | n ≤ l.length} := begin induction l with hd tl IH, { intros n hn m hm h, simp only [set.mem_singleton_iff, set.set_of_eq_eq_singleton, length, nonpos_iff_eq_zero] at hn hm, simp [hn, hm] }, { intros n hn m hm h, simp only [length, set.mem_set_of_eq] at hn hm, simp only [mem_cons_iff, not_or_distrib] at hx, cases n; cases m, { refl }, { simpa [hx.left] using h }, { simpa [ne.symm hx.left] using h }, { simp only [true_and, eq_self_iff_true, insert_nth_succ_cons] at h, rw nat.succ_inj', refine IH hx.right _ _ h, { simpa [nat.succ_le_succ_iff] using hn }, { simpa [nat.succ_le_succ_iff] using hm } } } end lemma insert_nth_of_length_lt (l : list α) (x : α) (n : ℕ) (h : l.length < n) : insert_nth n x l = l := begin induction l with hd tl IH generalizing n, { cases n, { simpa using h }, { simp } }, { cases n, { simpa using h }, { simp only [nat.succ_lt_succ_iff, length] at h, simpa using IH _ h } } end @[simp] lemma insert_nth_length_self (l : list α) (x : α) : insert_nth l.length x l = l ++ [x] := begin induction l with hd tl IH, { simp }, { simpa using IH } end lemma length_le_length_insert_nth (l : list α) (x : α) (n : ℕ) : l.length ≤ (insert_nth n x l).length := begin cases le_or_lt n l.length with hn hn, { rw length_insert_nth _ _ hn, exact (nat.lt_succ_self _).le }, { rw insert_nth_of_length_lt _ _ _ hn } end lemma length_insert_nth_le_succ (l : list α) (x : α) (n : ℕ) : (insert_nth n x l).length ≤ l.length + 1 := begin cases le_or_lt n l.length with hn hn, { rw length_insert_nth _ _ hn }, { rw insert_nth_of_length_lt _ _ _ hn, exact (nat.lt_succ_self _).le } end lemma nth_le_insert_nth_of_lt (l : list α) (x : α) (n k : ℕ) (hn : k < n) (hk : k < l.length) (hk' : k < (insert_nth n x l).length := hk.trans_le (length_le_length_insert_nth _ _ _)): (insert_nth n x l).nth_le k hk' = l.nth_le k hk := begin induction n with n IH generalizing k l, { simpa using hn }, { cases l with hd tl, { simp }, { cases k, { simp }, { rw nat.succ_lt_succ_iff at hn, simpa using IH _ _ hn _ } } } end @[simp] lemma nth_le_insert_nth_self (l : list α) (x : α) (n : ℕ) (hn : n ≤ l.length) (hn' : n < (insert_nth n x l).length := by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff]) : (insert_nth n x l).nth_le n hn' = x := begin induction l with hd tl IH generalizing n, { simp only [length, nonpos_iff_eq_zero] at hn, simp [hn] }, { cases n, { simp }, { simp only [nat.succ_le_succ_iff, length] at hn, simpa using IH _ hn } } end lemma nth_le_insert_nth_add_succ (l : list α) (x : α) (n k : ℕ) (hk' : n + k < l.length) (hk : n + k + 1 < (insert_nth n x l).length := by rwa [length_insert_nth _ _ (le_self_add.trans hk'.le), nat.succ_lt_succ_iff]) : (insert_nth n x l).nth_le (n + k + 1) hk = nth_le l (n + k) hk' := begin induction l with hd tl IH generalizing n k, { simpa using hk' }, { cases n, { simpa }, { simpa [succ_add] using IH _ _ _ } } end lemma insert_nth_injective (n : ℕ) (x : α) : function.injective (insert_nth n x) := begin induction n with n IH, { have : insert_nth 0 x = cons x := funext (λ _, rfl), simp [this] }, { rintros (_|⟨a, as⟩) (_|⟨b, bs⟩) h; simpa [IH.eq_iff] using h <|> refl } end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl theorem map_eq_foldr (f : α → β) (l : list α) : map f l = foldr (λ a bs, f a :: bs) [] l := by induction l; simp * lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl @[simp] theorem map_id'' (l : list α) : map (λ x, x) l = l := map_id _ theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by simp [show f = id, from funext h] theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-- A single `list.map` of a composition of functions is equal to composing a `list.map` with another `list.map`, fully applied. This is the reverse direction of `list.map_map`. -/ lemma comp_map (h : β → γ) (g : α → β) (l : list α) : map (h ∘ g) l = map h (map g l) := (map_map _ _ _).symm /-- Composing a `list.map` with another `list.map` is equal to a single `list.map` of composed functions. -/ @[simp] lemma map_comp_map (g : β → γ) (f : α → β) : map g ∘ map f = map (g ∘ f) := by { ext l, rw comp_map } theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) : map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as := by { induction as, { refl }, { simp! [*, apply_ite (map f)] } } lemma last_map (f : α → β) {l : list α} (hl : l ≠ []) : (l.map f).last (mt eq_nil_of_map_eq_nil hl) = f (l.last hl) := begin induction l with l_ih l_tl l_ih, { apply (hl rfl).elim }, { cases l_tl, { simp }, { simpa using l_ih } } end /-! ### map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl @[simp] theorem map₂_flip (f : α → β → γ) : ∀ as bs, map₂ (flip f) bs as = map₂ f as bs | [] [] := rfl | [] (b :: bs) := rfl | (a :: as) [] := rfl | (a :: as) (b :: bs) := by { simp! [map₂_flip], refl } /-! ### take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } /-- Taking the first `n` elements in `l₁ ++ l₂` is the same as appending the first `n` elements of `l₁` to the first `n - l₁.length` elements of `l₂`. -/ lemma take_append_eq_append_take {l₁ l₂ : list α} {n : ℕ} : take n (l₁ ++ l₂) = take n l₁ ++ take (n - l₁.length) l₂ := begin induction l₁ generalizing n, { simp }, cases n, { simp }, simp * end lemma take_append_of_le_length {l₁ l₂ : list α} {n : ℕ} (h : n ≤ l₁.length) : (l₁ ++ l₂).take n = l₁.take n := by simp [take_append_eq_append_take, tsub_eq_zero_iff_le.mpr h] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := by simp [take_append_eq_append_take, take_all_of_le le_self_add] /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } lemma nth_take {l : list α} {n m : ℕ} (h : m < n) : (l.take n).nth m = l.nth m := begin induction n with n hn generalizing l m, { simp only [nat.nat_zero_eq_zero] at h, exact absurd h (not_lt_of_le m.zero_le) }, { cases l with hd tl, { simp only [take_nil] }, { cases m, { simp only [nth, take] }, { simpa only using hn (nat.lt_of_succ_lt_succ h) } } }, end @[simp] lemma nth_take_of_succ {l : list α} {n : ℕ} : (l.take (n + 1)).nth n = l.nth n := nth_take (nat.lt_succ_self n) lemma take_succ {l : list α} {n : ℕ} : l.take (n + 1) = l.take n ++ (l.nth n).to_list := begin induction l with hd tl hl generalizing n, { simp only [option.to_list, nth, take_nil, append_nil]}, { cases n, { simp only [option.to_list, nth, eq_self_iff_true, and_self, take, nil_append] }, { simp only [hl, cons_append, nth, eq_self_iff_true, and_self, take] } } end @[simp] lemma take_eq_nil_iff {l : list α} {k : ℕ} : l.take k = [] ↔ l = [] ∨ k = 0 := by { cases l; cases k; simp [nat.succ_ne_zero] } lemma init_eq_take (l : list α) : l.init = l.take l.length.pred := begin cases l with x l, { simp [init] }, { induction l with hd tl hl generalizing x, { simp [init], }, { simp [init, hl] } } end lemma init_take {n : ℕ} {l : list α} (h : n < l.length) : (l.take n).init = l.take n.pred := by simp [init_eq_take, min_eq_left_of_lt h, take_take, pred_le] @[simp] lemma init_cons_of_ne_nil {α : Type*} {x : α} : ∀ {l : list α} (h : l ≠ []), (x :: l).init = x :: l.init | [] h := false.elim (h rfl) | (a :: l) _ := by simp [init] @[simp] lemma init_append_of_ne_nil {α : Type*} {l : list α} : ∀ (l' : list α) (h : l ≠ []), (l' ++ l).init = l' ++ l.init | [] _ := by simp only [nil_append] | (a :: l') h := by simp [append_ne_nil_of_ne_nil_right l' l h, init_append_of_ne_nil l' h] @[simp] lemma drop_eq_nil_of_le {l : list α} {k : ℕ} (h : l.length ≤ k) : l.drop k = [] := by simpa [←length_eq_zero] using tsub_eq_zero_iff_le.mpr h lemma drop_eq_nil_iff_le {l : list α} {k : ℕ} : l.drop k = [] ↔ l.length ≤ k := begin refine ⟨λ h, _, drop_eq_nil_of_le⟩, induction k with k hk generalizing l, { simp only [drop] at h, simp [h] }, { cases l, { simp }, { simp only [drop] at h, simpa [nat.succ_le_succ_iff] using hk h } } end lemma tail_drop (l : list α) (n : ℕ) : (l.drop n).tail = l.drop (n + 1) := begin induction l with hd tl hl generalizing n, { simp }, { cases n, { simp }, { simp [hl] } } end lemma cons_nth_le_drop_succ {l : list α} {n : ℕ} (hn : n < l.length) : l.nth_le n hn :: l.drop (n + 1) = l.drop n := begin induction l with hd tl hl generalizing n, { exact absurd n.zero_le (not_le_of_lt (by simpa using hn)) }, { cases n, { simp }, { simp only [nat.succ_lt_succ_iff, list.length] at hn, simpa [list.nth_le, list.drop] using hl hn } } end theorem drop_nil : ∀ n, drop n [] = ([] : list α) := λ _, drop_eq_nil_of_le (nat.zero_le _) @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ /-- Dropping the elements up to `n` in `l₁ ++ l₂` is the same as dropping the elements up to `n` in `l₁`, dropping the elements up to `n - l₁.length` in `l₂`, and appending them. -/ lemma drop_append_eq_append_drop {l₁ l₂ : list α} {n : ℕ} : drop n (l₁ ++ l₂) = drop n l₁ ++ drop (n - l₁.length) l₂ := begin induction l₁ generalizing n, { simp }, cases n, { simp }, simp * end lemma drop_append_of_le_length {l₁ l₂ : list α} {n : ℕ} (h : n ≤ l₁.length) : (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ := by simp [drop_append_eq_append_drop, tsub_eq_zero_iff_le.mpr h] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := by simp [drop_append_eq_append_drop, take_all_of_le le_self_add] /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (lt_tsub_iff_left.mp ((length_drop i L) ▸ h)) := by rw nth_le_drop lemma nth_drop (L : list α) (i j : ℕ) : nth (L.drop i) j = nth L (i + j) := begin ext, simp only [nth_eq_some, nth_le_drop', option.mem_def], split; exact λ ⟨h, ha⟩, ⟨by simpa [lt_tsub_iff_left] using h, ha⟩ end @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] lemma reverse_take {α} {xs : list α} (n : ℕ) (h : n ≤ xs.length) : xs.reverse.take n = (xs.drop (xs.length - n)).reverse := begin induction xs generalizing n; simp only [reverse_cons, drop, reverse_nil, zero_tsub, length, take_nil], cases h.lt_or_eq_dec with h' h', { replace h' := le_of_succ_le_succ h', rwa [take_append_of_le_length, xs_ih _ h'], rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop], { rwa [succ_eq_add_one, ← tsub_add_eq_add_tsub] }, { rwa length_reverse } }, { subst h', rw [length, tsub_self, drop], suffices : xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length, by rw [this, take_length, reverse_cons], rw [length_append, length_reverse], refl } end @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat default n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /-! ### foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) : list.foldl f' (g a) (l.map g) = g (list.foldl f a l) := begin induction l generalizing a, { simp }, { simp [l_ih, h] } end theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) : list.foldr f' (g a) (l.map g) = g (list.foldr f a l) := begin induction l generalizing a, { simp }, { simp [l_ih, h] } end theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } lemma foldl_hom₂ (l : list ι) (f : α → β → γ) (op₁ : α → ι → α) (op₂ : β → ι → β) (op₃ : γ → ι → γ) (a : α) (b : β) (h : ∀ a b i, f (op₁ a i) (op₂ b i) = op₃ (f a b) i) : foldl op₃ (f a b) l = f (foldl op₁ a l) (foldl op₂ b l) := eq.symm $ by { revert a b, induction l; intros; [refl, simp only [*, foldl]] } lemma foldr_hom₂ (l : list ι) (f : α → β → γ) (op₁ : ι → α → α) (op₂ : ι → β → β) (op₃ : ι → γ → γ) (a : α) (b : β) (h : ∀ a b i, f (op₁ i a) (op₂ i b) = op₃ i (f a b)) : foldr op₃ (f a b) l = f (foldr op₁ a l) (foldr op₂ b l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α} (hl : ∀ f ∈ l, function.injective f) (hf : function.injective f): function.injective (@list.foldl (α → α) (α → α) function.comp f l) := begin induction l generalizing f, { exact hf }, { apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)), apply function.injective.comp hf, apply hl _ (list.mem_cons_self _ _) } end /-- Induction principle for values produced by a `foldr`: if a property holds for the seed element `b : β` and for all incremental `op : α → β → β` performed on the elements `(a : α) ∈ l`. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def foldr_rec_on {C : β → Sort*} (l : list α) (op : α → β → β) (b : β) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op a b)) : C (foldr op b l) := begin induction l with hd tl IH, { exact hb }, { refine hl _ _ hd (mem_cons_self hd tl), refine IH _, intros y hy x hx, exact hl y hy x (mem_cons_of_mem hd hx) } end /-- Induction principle for values produced by a `foldl`: if a property holds for the seed element `b : β` and for all incremental `op : β → α → β` performed on the elements `(a : α) ∈ l`. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def foldl_rec_on {C : β → Sort*} (l : list α) (op : β → α → β) (b : β) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op b a)) : C (foldl op b l) := begin induction l with hd tl IH generalizing b, { exact hb }, { refine IH _ _ _, { intros y hy x hx, exact hl y hy x (mem_cons_of_mem hd hx) }, { exact hl b hb hd (mem_cons_self hd tl) } } end @[simp] lemma foldr_rec_on_nil {C : β → Sort*} (op : α → β → β) (b) (hb : C b) (hl) : foldr_rec_on [] op b hb hl = hb := rfl @[simp] lemma foldr_rec_on_cons {C : β → Sort*} (x : α) (l : list α) (op : α → β → β) (b) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ (x :: l)), C (op a b)) : foldr_rec_on (x :: l) op b hb hl = hl _ (foldr_rec_on l op b hb (λ b hb a ha, hl b hb a (mem_cons_of_mem _ ha))) x (mem_cons_self _ _) := rfl @[simp] lemma foldl_rec_on_nil {C : β → Sort*} (op : β → α → β) (b) (hb : C b) (hl) : foldl_rec_on [] op b hb hl = hb := rfl /- scanl -/ section scanl variables {f : β → α → β} {b : β} {a : α} {l : list α} lemma length_scanl : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] @[simp] lemma scanl_nil (b : β) : scanl f b nil = [b] := rfl @[simp] lemma scanl_cons : scanl f b (a :: l) = [b] ++ scanl f (f b a) l := by simp only [scanl, eq_self_iff_true, singleton_append, and_self] @[simp] lemma nth_zero_scanl : (scanl f b l).nth 0 = some b := begin cases l, { simp only [nth, scanl_nil] }, { simp only [nth, scanl_cons, singleton_append] } end @[simp] lemma nth_le_zero_scanl {h : 0 < (scanl f b l).length} : (scanl f b l).nth_le 0 h = b := begin cases l, { simp only [nth_le, scanl_nil] }, { simp only [nth_le, scanl_cons, singleton_append] } end lemma nth_succ_scanl {i : ℕ} : (scanl f b l).nth (i + 1) = ((scanl f b l).nth i).bind (λ x, (l.nth i).map (λ y, f x y)) := begin induction l with hd tl hl generalizing b i, { symmetry, simp only [option.bind_eq_none', nth, forall_2_true_iff, not_false_iff, option.map_none', scanl_nil, option.not_mem_none, forall_true_iff] }, { simp only [nth, scanl_cons, singleton_append], cases i, { simp only [option.map_some', nth_zero_scanl, nth, option.some_bind'] }, { simp only [hl, nth] } } end lemma nth_le_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} : (scanl f b l).nth_le (i + 1) h = f ((scanl f b l).nth_le i (nat.lt_of_succ_lt h)) (l.nth_le i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) := begin induction i with i hi generalizing b l, { cases l, { simp only [length, zero_add, scanl_nil] at h, exact absurd h (lt_irrefl 1) }, { simp only [scanl_cons, singleton_append, nth_le_zero_scanl, nth_le] } }, { cases l, { simp only [length, add_lt_iff_neg_right, scanl_nil] at h, exact absurd h (not_lt_of_lt nat.succ_pos') }, { simp_rw scanl_cons, rw nth_le_append_right _, { simpa only [hi, length, succ_add_sub_one] }, { simp only [length, nat.zero_le, le_add_iff_nonneg_left] } } } end end scanl /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### mfoldl, mfoldr, mmap -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl theorem mfoldr_eq_foldr (f : α → β → m β) (b l) : mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l := by induction l; simp * attribute [simp] mmap mmap' variables [is_lawful_monad m] theorem mfoldl_eq_foldl (f : β → α → m β) (b l) : mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l := begin suffices h : ∀ (mb : m β), (mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l, by simp [←h (pure b)], induction l; intro, { simp }, { simp only [mfoldl, foldl, ←l_ih] with functor_norm } end @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, is_lawful_monad.bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, is_lawful_monad.bind_assoc] end mfoldl_mfoldr /-! ### intersperse -/ @[simp] lemma intersperse_nil {α : Type u} (a : α) : intersperse a [] = [] := rfl @[simp] lemma intersperse_singleton {α : Type u} (a b : α) : intersperse a [b] = [b] := rfl @[simp] lemma intersperse_cons_cons {α : Type u} (a b c : α) (tl : list α) : intersperse a (b :: c :: tl) = b :: a :: intersperse a (c :: tl) := rfl /-! ### split_at and split_on -/ @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] lemma split_on_nil {α : Type u} [decidable_eq α] (a : α) : [].split_on a = [[]] := rfl /-- An auxiliary definition for proving a specification lemma for `split_on_p`. `split_on_p_aux' P xs ys` splits the list `ys ++ xs` at every element satisfying `P`, where `ys` is an accumulating parameter for the initial segment of elements not satisfying `P`. -/ def split_on_p_aux' {α : Type u} (P : α → Prop) [decidable_pred P] : list α → list α → list (list α) | [] xs := [xs] | (h :: t) xs := if P h then xs :: split_on_p_aux' t [] else split_on_p_aux' t (xs ++ [h]) lemma split_on_p_aux_eq {α : Type u} (P : α → Prop) [decidable_pred P] (xs ys : list α) : split_on_p_aux' P xs ys = split_on_p_aux P xs ((++) ys) := begin induction xs with a t ih generalizing ys; simp! only [append_nil, eq_self_iff_true, and_self], split_ifs; rw ih, { refine ⟨rfl, rfl⟩ }, { congr, ext, simp } end lemma split_on_p_aux_nil {α : Type u} (P : α → Prop) [decidable_pred P] (xs : list α) : split_on_p_aux P xs id = split_on_p_aux' P xs [] := by { rw split_on_p_aux_eq, refl } /-- The original list `L` can be recovered by joining the lists produced by `split_on_p p L`, interspersed with the elements `L.filter p`. -/ lemma split_on_p_spec {α : Type u} (p : α → Prop) [decidable_pred p] (as : list α) : join (zip_with (++) (split_on_p p as) ((as.filter p).map (λ x, [x]) ++ [[]])) = as := begin rw [split_on_p, split_on_p_aux_nil], suffices : ∀ xs, join (zip_with (++) (split_on_p_aux' p as xs) ((as.filter p).map(λ x, [x]) ++ [[]])) = xs ++ as, { rw this, refl }, induction as; intro; simp! only [split_on_p_aux', append_nil], split_ifs; simp [zip_with, join, *], end /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) : sizeof x < sizeof l := begin induction l with h t ih; cases hx, { rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) }, { exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) } end @[simp] theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_map {p : β → Prop} (g : ∀ b, p b → γ) (f : α → β) (l H) : pmap g (map f l) H = pmap (λ a h, g (f a) h) l (λ a h, H _ (mem_map_of_mem _ h)) := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap @[simp] lemma pmap_eq_nil {p : α → Prop} {f : Π a, p a → β} {l H} : pmap f l H = [] ↔ l = [] := by rw [← length_eq_zero, length_pmap, length_eq_zero] @[simp] lemma attach_eq_nil (l : list α) : l.attach = [] ↔ l = [] := pmap_eq_nil lemma last_pmap {α β : Type*} (p : α → Prop) (f : Π a, p a → β) (l : list α) (hl₁ : ∀ a ∈ l, p a) (hl₂ : l ≠ []) : (l.pmap f hl₁).last (mt list.pmap_eq_nil.1 hl₂) = f (l.last hl₂) (hl₁ _ (list.last_mem hl₂)) := begin induction l with l_hd l_tl l_ih, { apply (hl₂ rfl).elim }, { cases l_tl, { simp }, { apply l_ih } } end lemma nth_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) (n : ℕ) : nth (pmap f l h) n = option.pmap f (nth l n) (λ x H, h x (nth_mem H)) := begin induction l with hd tl hl generalizing n, { simp }, { cases n; simp [hl] } end lemma nth_le_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) {n : ℕ} (hn : n < (pmap f l h).length) : nth_le (pmap f l h) n hn = f (nth_le l n (@length_pmap _ _ p f l h ▸ hn)) (h _ (nth_le_mem l n (@length_pmap _ _ p f l h ▸ hn))) := begin induction l with hd tl hl generalizing n, { simp only [length, pmap] at hn, exact absurd hn (not_lt_of_le n.zero_le) }, { cases n, { simp }, { simpa [hl] } } end /-! ### find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /-! ### lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /-! ### filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { rw filter_map_cons_none _ _ eq }, { rw filter_map_cons_some _ _ _ eq }, end lemma filter_map_append {α β : Type*} (l l' : list α) (f : α → option β) : filter_map f (l ++ l') = filter_map f l ++ filter_map f l' := begin induction l with hd tl hl generalizing l', { simp }, { rw [cons_append, filter_map, filter_map], cases f hd; simp only [filter_map, hl, cons_append, eq_self_iff_true, and_self] } end theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### reduce_option -/ @[simp] lemma reduce_option_cons_of_some (x : α) (l : list (option α)) : reduce_option (some x :: l) = x :: l.reduce_option := by simp only [reduce_option, filter_map, id.def, eq_self_iff_true, and_self] @[simp] lemma reduce_option_cons_of_none (l : list (option α)) : reduce_option (none :: l) = l.reduce_option := by simp only [reduce_option, filter_map, id.def] @[simp] lemma reduce_option_nil : @reduce_option α [] = [] := rfl @[simp] lemma reduce_option_map {l : list (option α)} {f : α → β} : reduce_option (map (option.map f) l) = map f (reduce_option l) := begin induction l with hd tl hl, { simp only [reduce_option_nil, map_nil] }, { cases hd; simpa only [true_and, option.map_some', map, eq_self_iff_true, reduce_option_cons_of_some] using hl }, end lemma reduce_option_append (l l' : list (option α)) : (l ++ l').reduce_option = l.reduce_option ++ l'.reduce_option := filter_map_append l l' id lemma reduce_option_length_le (l : list (option α)) : l.reduce_option.length ≤ l.length := begin induction l with hd tl hl, { simp only [reduce_option_nil, length] }, { cases hd, { exact nat.le_succ_of_le hl }, { simpa only [length, add_le_add_iff_right, reduce_option_cons_of_some] using hl} } end lemma reduce_option_length_eq_iff {l : list (option α)} : l.reduce_option.length = l.length ↔ ∀ x ∈ l, option.is_some x := begin induction l with hd tl hl, { simp only [forall_const, reduce_option_nil, not_mem_nil, forall_prop_of_false, eq_self_iff_true, length, not_false_iff] }, { cases hd, { simp only [mem_cons_iff, forall_eq_or_imp, bool.coe_sort_ff, false_and, reduce_option_cons_of_none, length, option.is_some_none, iff_false], intro H, have := reduce_option_length_le tl, rw H at this, exact absurd (nat.lt_succ_self _) (not_lt_of_le this) }, { simp only [hl, true_and, mem_cons_iff, forall_eq_or_imp, add_left_inj, bool.coe_sort_tt, length, option.is_some_some, reduce_option_cons_of_some] } } end lemma reduce_option_length_lt_iff {l : list (option α)} : l.reduce_option.length < l.length ↔ none ∈ l := begin rw [(reduce_option_length_le l).lt_iff_ne, ne, reduce_option_length_eq_iff], induction l; simp *, rw [eq_comm, ← option.not_is_some_iff_eq_none, decidable.imp_iff_not_or] end lemma reduce_option_singleton (x : option α) : [x].reduce_option = x.to_list := by cases x; refl lemma reduce_option_concat (l : list (option α)) (x : option α) : (l.concat x).reduce_option = l.reduce_option ++ x.to_list := begin induction l with hd tl hl generalizing x, { cases x; simp [option.to_list] }, { simp only [concat_eq_append, reduce_option_append] at hl, cases hd; simp [hl, reduce_option_append] } end lemma reduce_option_concat_of_some (l : list (option α)) (x : α) : (l.concat (some x)).reduce_option = l.reduce_option.concat x := by simp only [reduce_option_nil, concat_eq_append, reduce_option_append, reduce_option_cons_of_some] lemma reduce_option_mem_iff {l : list (option α)} {x : α} : x ∈ l.reduce_option ↔ (some x) ∈ l := by simp only [reduce_option, id.def, mem_filter_map, exists_eq_right] lemma reduce_option_nth_iff {l : list (option α)} {x : α} : (∃ i, l.nth i = some (some x)) ↔ ∃ i, l.reduce_option.nth i = some x := by rw [←mem_iff_nth, ←mem_iff_nth, reduce_option_mem_iff] /-! ### filter -/ section filter variables {p : α → Prop} [decidable_pred p] theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) : filter p l = foldr (λ a out, if p a then a :: out else out) [] l := by induction l; simp [*, filter] lemma filter_congr' {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr' h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr' h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := (filter_sublist l).subset theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ lemma monotone_filter_left (p : α → Prop) [decidable_pred p] ⦃l l' : list α⦄ (h : l ⊆ l') : filter p l ⊆ filter p l' := begin intros x hx, rw [mem_filter] at hx ⊢, exact ⟨h hx.left, hx.right⟩ end theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] variable (p) theorem sublist.filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ lemma monotone_filter_right (l : list α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : l.filter p <+ l.filter q := begin induction l with hd tl IH, { refl }, { by_cases hp : p hd, { rw [filter_cons_of_pos _ hp, filter_cons_of_pos _ (h _ hp)], exact IH.cons_cons hd }, { rw filter_cons_of_neg _ hp, by_cases hq : q hd, { rw filter_cons_of_pos _ hq, exact sublist_cons_of_sublist hd IH }, { rw filter_cons_of_neg _ hq, exact IH } } } end theorem map_filter (f : β → α) (l : list β) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter (q) [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] end filter /-! ### erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl @[simp] lemma length_erasep_add_one {l : list α} {a} (al : a ∈ l) (pa : p a) : (l.erasep p).length + 1 = l.length := let ⟨_, l₁, l₂, _, _, h₁, h₂⟩ := exists_of_erasep al pa in by { rw [h₂, h₁, length_append, length_append], refl } theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := (erasep_sublist l).subset theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl @[simp] lemma length_erase_add_one {a : α} {l : list α} (h : a ∈ l) : (l.erase a).length + 1 = l.length := by rw [erase_eq_erasep, length_erasep_add_one h rfl] theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact sublist.erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := have this : eq a = eq (f a) ∘ f, { ext b, simp [finj.eq_iff] }, by simp [erase_eq_erasep, erase_eq_erasep, erasep_map, this] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] end erase /-! ### diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] lemma diff_cons_right (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.diff l₂).erase a := begin induction l₂ with b l₂ ih generalizing l₁ a, { simp_rw [diff_cons, diff_nil] }, { rw [diff_cons, diff_cons, erase_comm, ← diff_cons, ih, ← diff_cons] } end lemma diff_erase (l₁ l₂ : list α) (a : α) : (l₁.diff l₂).erase a = (l₁.erase a).diff l₂ := by rw [← diff_cons_right, diff_cons] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist _ _).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, (h.erase _).diff_right] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (h.erase b) end diff /-! ### enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /-! ### map₂_left' -/ section map₂_left' -- The definitional equalities for `map₂_left'` can already be used by the -- simplifie because `map₂_left'` is marked `@[simp]`. @[simp] theorem map₂_left'_nil_right (f : α → option β → γ) (as) : map₂_left' f as [] = (as.map (λ a, f a none), []) := by cases as; refl end map₂_left' /-! ### map₂_right' -/ section map₂_right' variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem map₂_right'_nil_left : map₂_right' f [] bs = (bs.map (f none), []) := by cases bs; refl @[simp] theorem map₂_right'_nil_right : map₂_right' f as [] = ([], as) := rfl @[simp] theorem map₂_right'_nil_cons : map₂_right' f [] (b :: bs) = (f none b :: bs.map (f none), []) := rfl @[simp] theorem map₂_right'_cons_cons : map₂_right' f (a :: as) (b :: bs) = let rec := map₂_right' f as bs in (f (some a) b :: rec.fst, rec.snd) := rfl end map₂_right' /-! ### zip_left' -/ section zip_left' variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_left'_nil_right : zip_left' as ([] : list β) = (as.map (λ a, (a, none)), []) := by cases as; refl @[simp] theorem zip_left'_nil_left : zip_left' ([] : list α) bs = ([], bs) := rfl @[simp] theorem zip_left'_cons_nil : zip_left' (a :: as) ([] : list β) = ((a, none) :: as.map (λ a, (a, none)), []) := rfl @[simp] theorem zip_left'_cons_cons : zip_left' (a :: as) (b :: bs) = let rec := zip_left' as bs in ((a, some b) :: rec.fst, rec.snd) := rfl end zip_left' /-! ### zip_right' -/ section zip_right' variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_right'_nil_left : zip_right' ([] : list α) bs = (bs.map (λ b, (none, b)), []) := by cases bs; refl @[simp] theorem zip_right'_nil_right : zip_right' as ([] : list β) = ([], as) := rfl @[simp] theorem zip_right'_nil_cons : zip_right' ([] : list α) (b :: bs) = ((none, b) :: bs.map (λ b, (none, b)), []) := rfl @[simp] theorem zip_right'_cons_cons : zip_right' (a :: as) (b :: bs) = let rec := zip_right' as bs in ((some a, b) :: rec.fst, rec.snd) := rfl end zip_right' /-! ### map₂_left -/ section map₂_left variables (f : α → option β → γ) (as : list α) -- The definitional equalities for `map₂_left` can already be used by the -- simplifier because `map₂_left` is marked `@[simp]`. @[simp] theorem map₂_left_nil_right : map₂_left f as [] = as.map (λ a, f a none) := by cases as; refl theorem map₂_left_eq_map₂_left' : ∀ as bs, map₂_left f as bs = (map₂_left' f as bs).fst | [] bs := by simp! | (a :: as) [] := by simp! | (a :: as) (b :: bs) := by simp! [*] theorem map₂_left_eq_map₂ : ∀ as bs, length as ≤ length bs → map₂_left f as bs = map₂ (λ a b, f a (some b)) as bs | [] [] h := by simp! | [] (b :: bs) h := by simp! | (a :: as) [] h := by { simp at h, contradiction } | (a :: as) (b :: bs) h := by { simp at h, simp! [*] } end map₂_left /-! ### map₂_right -/ section map₂_right variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem map₂_right_nil_left : map₂_right f [] bs = bs.map (f none) := by cases bs; refl @[simp] theorem map₂_right_nil_right : map₂_right f as [] = [] := rfl @[simp] theorem map₂_right_nil_cons : map₂_right f [] (b :: bs) = f none b :: bs.map (f none) := rfl @[simp] theorem map₂_right_cons_cons : map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs := rfl theorem map₂_right_eq_map₂_right' : map₂_right f as bs = (map₂_right' f as bs).fst := by simp only [map₂_right, map₂_right', map₂_left_eq_map₂_left'] theorem map₂_right_eq_map₂ (h : length bs ≤ length as) : map₂_right f as bs = map₂ (λ a b, f (some a) b) as bs := begin have : (λ a b, flip f a (some b)) = (flip (λ a b, f (some a) b)) := rfl, simp only [map₂_right, map₂_left_eq_map₂, map₂_flip, *] end end map₂_right /-! ### zip_left -/ section zip_left variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_left_nil_right : zip_left as ([] : list β) = as.map (λ a, (a, none)) := by cases as; refl @[simp] theorem zip_left_nil_left : zip_left ([] : list α) bs = [] := rfl @[simp] theorem zip_left_cons_nil : zip_left (a :: as) ([] : list β) = (a, none) :: as.map (λ a, (a, none)) := rfl @[simp] theorem zip_left_cons_cons : zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs := rfl theorem zip_left_eq_zip_left' : zip_left as bs = (zip_left' as bs).fst := by simp only [zip_left, zip_left', map₂_left_eq_map₂_left'] end zip_left /-! ### zip_right -/ section zip_right variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_right_nil_left : zip_right ([] : list α) bs = bs.map (λ b, (none, b)) := by cases bs; refl @[simp] theorem zip_right_nil_right : zip_right as ([] : list β) = [] := rfl @[simp] theorem zip_right_nil_cons : zip_right ([] : list α) (b :: bs) = (none, b) :: bs.map (λ b, (none, b)) := rfl @[simp] theorem zip_right_cons_cons : zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs := rfl theorem zip_right_eq_zip_right' : zip_right as bs = (zip_right' as bs).fst := by simp only [zip_right, zip_right', map₂_right_eq_map₂_right'] end zip_right /-! ### to_chunks -/ section to_chunks @[simp] theorem to_chunks_nil (n) : @to_chunks α n [] = [] := by cases n; refl theorem to_chunks_aux_eq (n) : ∀ xs i, @to_chunks_aux α n xs i = (xs.take i, (xs.drop i).to_chunks (n+1)) | [] i := by cases i; refl | (x::xs) 0 := by rw [to_chunks_aux, drop, to_chunks]; cases to_chunks_aux n xs n; refl | (x::xs) (i+1) := by rw [to_chunks_aux, to_chunks_aux_eq]; refl theorem to_chunks_eq_cons' (n) : ∀ {xs : list α} (h : xs ≠ []), xs.to_chunks (n+1) = xs.take (n+1) :: (xs.drop (n+1)).to_chunks (n+1) | [] e := (e rfl).elim | (x::xs) _ := by rw [to_chunks, to_chunks_aux_eq]; refl theorem to_chunks_eq_cons : ∀ {n} {xs : list α} (n0 : n ≠ 0) (x0 : xs ≠ []), xs.to_chunks n = xs.take n :: (xs.drop n).to_chunks n | 0 _ e := (e rfl).elim | (n+1) xs _ := to_chunks_eq_cons' _ theorem to_chunks_aux_join {n} : ∀ {xs i l L}, @to_chunks_aux α n xs i = (l, L) → l ++ L.join = xs | [] _ _ _ rfl := rfl | (x::xs) i l L e := begin cases i; [ cases e' : to_chunks_aux n xs n with l L, cases e' : to_chunks_aux n xs i with l L]; { rw [to_chunks_aux, e', to_chunks_aux] at e, cases e, exact (congr_arg (cons x) (to_chunks_aux_join e') : _) } end @[simp] theorem to_chunks_join : ∀ n xs, (@to_chunks α n xs).join = xs | n [] := by cases n; refl | 0 (x::xs) := by simp only [to_chunks, join]; rw append_nil | (n+1) (x::xs) := begin rw to_chunks, cases e : to_chunks_aux n xs n with l L, exact (congr_arg (cons x) (to_chunks_aux_join e) : _), end theorem to_chunks_length_le : ∀ n xs, n ≠ 0 → ∀ l : list α, l ∈ @to_chunks α n xs → l.length ≤ n | 0 _ e _ := (e rfl).elim | (n+1) xs _ l := begin refine (measure_wf length).induction xs _, intros xs IH h, by_cases x0 : xs = [], {subst xs, cases h}, rw to_chunks_eq_cons' _ x0 at h, rcases h with rfl|h, { apply length_take_le }, { refine IH _ _ h, simp only [measure, inv_image, length_drop], exact tsub_lt_self (length_pos_iff_ne_nil.2 x0) (succ_pos _) }, end end to_chunks /-! ### Retroattributes The list definitions happen earlier than `to_additive`, so here we tag the few multiplicative definitions that couldn't be tagged earlier. -/ attribute [to_additive] list.prod -- `list.sum` attribute [to_additive] alternating_prod -- `list.alternating_sum` /-! ### Miscellaneous lemmas -/ theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val @[simp] theorem mem_map_swap (x : α) (y : β) (xs : list (α × β)) : (y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs := begin induction xs with x xs, { simp only [not_mem_nil, map_nil] }, { cases x with a b, simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk, prod.exists, xs_ih, and_comm] }, end lemma slice_eq (xs : list α) (n m : ℕ) : slice n m xs = xs.take n ++ xs.drop (n+m) := begin induction n generalizing xs, { simp [slice] }, { cases xs; simp [slice, *, nat.succ_add], } end lemma sizeof_slice_lt [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) : sizeof (list.slice i j xs) < sizeof xs := begin induction xs generalizing i j, case list.nil : i j h { cases hi }, case list.cons : x xs xs_ih i j h { cases i; simp only [-slice_eq, list.slice], { cases j, cases h, dsimp only [drop], unfold_wf, apply @lt_of_le_of_lt _ _ _ xs.sizeof, { clear_except, induction xs generalizing j; unfold_wf, case list.nil : j { refl }, case list.cons : xs_hd xs_tl xs_ih j { cases j; unfold_wf, refl, transitivity, apply xs_ih, simp }, }, unfold_wf, apply zero_lt_one_add, }, { unfold_wf, apply xs_ih _ _ h, apply lt_of_succ_lt_succ hi, } }, end end list
bce0c0d8d4ad793100f700a6b749b3f060a57a7f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/tryPostponeIssue.lean
c1f80608bc3ae0ec2196d1568f779794ccf884e8
[ "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
132
lean
notation:50 e:51 " matches' " p:51 => (match e with | p => true | _ => false) def g (x : Nat) := if x + 1 matches' 1 then x else 0
286e4aab7efb5ae47318b205fc5fc04fedc7df69
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/box_integral/integrability.lean
eba1bdd4c83d76e1c2e57744e629c3126a23c046
[ "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
17,962
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.basic import measure_theory.measure.regular /-! # McShane integrability vs Bochner integrability In this file we prove that any Bochner integrable function is McShane integrable (hence, it is Henstock and `⊥` integrable) with the same integral. The proof is based on [Russel A. Gordon, *The integrals of Lebesgue, Denjoy, Perron, and Henstock*][Gordon55]. ## Tags integral, McShane integral, Bochner integral -/ open_locale classical nnreal ennreal topology big_operators universes u v variables {ι : Type u} {E : Type v} [fintype ι] [normed_add_comm_group E] [normed_space ℝ E] open measure_theory metric set finset filter box_integral namespace box_integral /-- The indicator function of a measurable set is McShane integrable with respect to any locally-finite measure. -/ lemma has_integral_indicator_const (l : integration_params) (hl : l.bRiemann = ff) {s : set (ι → ℝ)} (hs : measurable_set s) (I : box ι) (y : E) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] : has_integral.{u v v} I l (s.indicator (λ _, y)) μ.to_box_additive.to_smul ((μ (s ∩ I)).to_real • y) := begin refine has_integral_of_mul (‖y‖) (λ ε ε0, _), lift ε to ℝ≥0 using ε0.le, rw nnreal.coe_pos at ε0, /- First we choose a closed set `F ⊆ s ∩ I.Icc` and an open set `U ⊇ s` such that both `(s ∩ I.Icc) \ F` and `U \ s` have measuer less than `ε`. -/ have A : μ (s ∩ I.Icc) ≠ ∞, from ((measure_mono $ set.inter_subset_right _ _).trans_lt (I.measure_Icc_lt_top μ)).ne, have B : μ (s ∩ I) ≠ ∞, from ((measure_mono $ set.inter_subset_right _ _).trans_lt (I.measure_coe_lt_top μ)).ne, obtain ⟨F, hFs, hFc, hμF⟩ : ∃ F ⊆ s ∩ I.Icc, is_closed F ∧ μ ((s ∩ I.Icc) \ F) < ε, from (hs.inter I.measurable_set_Icc).exists_is_closed_diff_lt A (ennreal.coe_pos.2 ε0).ne', obtain ⟨U, hsU, hUo, hUt, hμU⟩ : ∃ U ⊇ s ∩ I.Icc, is_open U ∧ μ U < ∞ ∧ μ (U \ (s ∩ I.Icc)) < ε, from (hs.inter I.measurable_set_Icc).exists_is_open_diff_lt A (ennreal.coe_pos.2 ε0).ne', /- Then we choose `r` so that `closed_ball x (r x) ⊆ U` whenever `x ∈ s ∩ I.Icc` and `closed_ball x (r x)` is disjoint with `F` otherwise. -/ have : ∀ x ∈ s ∩ I.Icc, ∃ r : Ioi (0 : ℝ), closed_ball x r ⊆ U, from λ x hx, subtype.exists'.1 (nhds_basis_closed_ball.mem_iff.1 (hUo.mem_nhds $ hsU hx)), choose! rs hrsU, have : ∀ x ∈ I.Icc \ s, ∃ r : Ioi (0 : ℝ), closed_ball x r ⊆ Fᶜ, from λ x hx, subtype.exists'.1 (nhds_basis_closed_ball.mem_iff.1 (hFc.is_open_compl.mem_nhds $ λ hx', hx.2 (hFs hx').1)), choose! rs' hrs'F, set r : (ι → ℝ) → Ioi (0 : ℝ) := s.piecewise rs rs', refine ⟨λ c, r, λ c, l.r_cond_of_bRiemann_eq_ff hl, λ c π hπ hπp, _⟩, rw mul_comm, /- Then the union of boxes `J ∈ π` such that `π.tag ∈ s` includes `F` and is included by `U`, hence its measure is `ε`-close to the measure of `s`. -/ dsimp [integral_sum], simp only [mem_closed_ball, dist_eq_norm, ← indicator_const_smul_apply, sum_indicator_eq_sum_filter, ← sum_smul, ← sub_smul, norm_smul, real.norm_eq_abs, ← prepartition.filter_boxes, ← prepartition.measure_Union_to_real], refine mul_le_mul_of_nonneg_right _ (norm_nonneg y), set t := (π.to_prepartition.filter (λ J, π.tag J ∈ s)).Union, change abs ((μ t).to_real - (μ (s ∩ I)).to_real) ≤ ε, have htU : t ⊆ U ∩ I, { simp only [t, prepartition.Union_def, Union_subset_iff, prepartition.mem_filter, and_imp], refine λ J hJ hJs x hx, ⟨hrsU _ ⟨hJs, π.tag_mem_Icc J⟩ _, π.le_of_mem' J hJ hx⟩, simpa only [r, s.piecewise_eq_of_mem _ _ hJs] using hπ.1 J hJ (box.coe_subset_Icc hx) }, refine abs_sub_le_iff.2 ⟨_, _⟩, { refine (ennreal.le_to_real_sub B).trans (ennreal.to_real_le_coe_of_le_coe _), refine (tsub_le_tsub (measure_mono htU) le_rfl).trans (le_measure_diff.trans _), refine (measure_mono $ λ x hx, _).trans hμU.le, exact ⟨hx.1.1, λ hx', hx.2 ⟨hx'.1, hx.1.2⟩⟩ }, { have hμt : μ t ≠ ∞ := ((measure_mono (htU.trans (inter_subset_left _ _))).trans_lt hUt).ne, refine (ennreal.le_to_real_sub hμt).trans (ennreal.to_real_le_coe_of_le_coe _), refine le_measure_diff.trans ((measure_mono _).trans hμF.le), rintro x ⟨⟨hxs, hxI⟩, hxt⟩, refine ⟨⟨hxs, box.coe_subset_Icc hxI⟩, λ hxF, hxt _⟩, simp only [t, prepartition.Union_def, prepartition.mem_filter, set.mem_Union, exists_prop], rcases hπp x hxI with ⟨J, hJπ, hxJ⟩, refine ⟨J, ⟨hJπ, _⟩, hxJ⟩, contrapose hxF, refine hrs'F _ ⟨π.tag_mem_Icc J, hxF⟩ _, simpa only [r, s.piecewise_eq_of_not_mem _ _ hxF] using hπ.1 J hJπ (box.coe_subset_Icc hxJ) } end /-- If `f` is a.e. equal to zero on a rectangular box, then it has McShane integral zero on this box. -/ lemma has_integral_zero_of_ae_eq_zero {l : integration_params} {I : box ι} {f : (ι → ℝ) → E} {μ : measure (ι → ℝ)} [is_locally_finite_measure μ] (hf : f =ᵐ[μ.restrict I] 0) (hl : l.bRiemann = ff) : has_integral.{u v v} I l f μ.to_box_additive.to_smul 0 := begin /- Each set `{x | n < ‖f x‖ ≤ n + 1}`, `n : ℕ`, has measure zero. We cover it by an open set of measure less than `ε / 2 ^ n / (n + 1)`. Then the norm of the integral sum is less than `ε`. -/ refine has_integral_iff.2 (λ ε ε0, _), lift ε to ℝ≥0 using ε0.lt.le, rw [gt_iff_lt, nnreal.coe_pos] at ε0, rcases nnreal.exists_pos_sum_of_countable ε0.ne' ℕ with ⟨δ, δ0, c, hδc, hcε⟩, haveI := fact.mk (I.measure_coe_lt_top μ), change μ.restrict I {x | f x ≠ 0} = 0 at hf, set N : (ι → ℝ) → ℕ := λ x, ⌈‖f x‖⌉₊, have N0 : ∀ {x}, N x = 0 ↔ f x = 0, by { intro x, simp [N] }, have : ∀ n, ∃ U ⊇ N ⁻¹' {n}, is_open U ∧ μ.restrict I U < δ n / n, { refine λ n, (N ⁻¹' {n}).exists_is_open_lt_of_lt _ _, cases n, { simpa [ennreal.div_zero (ennreal.coe_pos.2 (δ0 _)).ne'] using measure_lt_top (μ.restrict I) _ }, { refine (measure_mono_null _ hf).le.trans_lt _, { exact λ x hxN hxf, n.succ_ne_zero ((eq.symm hxN).trans $ N0.2 hxf) }, { simp [(δ0 _).ne'] } } }, choose U hNU hUo hμU, have : ∀ x, ∃ r : Ioi (0 : ℝ), closed_ball x r ⊆ U (N x), from λ x, subtype.exists'.1 (nhds_basis_closed_ball.mem_iff.1 ((hUo _).mem_nhds (hNU _ rfl))), choose r hrU, refine ⟨λ _, r, λ c, l.r_cond_of_bRiemann_eq_ff hl, λ c π hπ hπp, _⟩, rw [dist_eq_norm, sub_zero, ← integral_sum_fiberwise (λ J, N (π.tag J))], refine le_trans _ (nnreal.coe_lt_coe.2 hcε).le, refine (norm_sum_le_of_le _ _).trans (sum_le_has_sum _ (λ n _, (δ n).2) (nnreal.has_sum_coe.2 hδc)), rintro n -, dsimp [integral_sum], have : ∀ J ∈ π.filter (λ J, N (π.tag J) = n), ‖(μ ↑J).to_real • f (π.tag J)‖ ≤ (μ J).to_real * n, { intros J hJ, rw tagged_prepartition.mem_filter at hJ, rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact mul_le_mul_of_nonneg_left (hJ.2 ▸ nat.le_ceil _) ennreal.to_real_nonneg }, refine (norm_sum_le_of_le _ this).trans _, clear this, rw [← sum_mul, ← prepartition.measure_Union_to_real], generalize hm : μ (π.filter (λ J, N (π.tag J) = n)).Union = m, have : m < δ n / n, { simp only [measure.restrict_apply (hUo _).measurable_set] at hμU, refine hm ▸ (measure_mono _).trans_lt (hμU _), simp only [set.subset_def, tagged_prepartition.mem_Union, exists_prop, tagged_prepartition.mem_filter], rintro x ⟨J, ⟨hJ, rfl⟩, hx⟩, exact ⟨hrU _ (hπ.1 _ hJ (box.coe_subset_Icc hx)), π.le_of_mem' J hJ hx⟩ }, lift m to ℝ≥0 using ne_top_of_lt this, rw [ennreal.coe_to_real, ← nnreal.coe_nat_cast, ← nnreal.coe_mul, nnreal.coe_le_coe, ← ennreal.coe_le_coe, ennreal.coe_mul, ennreal.coe_nat, mul_comm], exact (mul_le_mul_left' this.le _).trans ennreal.mul_div_le end /-- If `f` has integral `y` on a box `I` with respect to a locally finite measure `μ` and `g` is a.e. equal to `f` on `I`, then `g` has the same integral on `I`. -/ lemma has_integral.congr_ae {l : integration_params} {I : box ι} {y : E} {f g : (ι → ℝ) → E} {μ : measure (ι → ℝ)} [is_locally_finite_measure μ] (hf : has_integral.{u v v} I l f μ.to_box_additive.to_smul y) (hfg : f =ᵐ[μ.restrict I] g) (hl : l.bRiemann = ff) : has_integral.{u v v} I l g μ.to_box_additive.to_smul y := begin have : (g - f) =ᵐ[μ.restrict I] 0, from hfg.mono (λ x hx, sub_eq_zero.2 hx.symm), simpa using hf.add (has_integral_zero_of_ae_eq_zero this hl) end end box_integral namespace measure_theory namespace simple_func /-- A simple function is McShane integrable w.r.t. any locally finite measure. -/ lemma has_box_integral (f : simple_func (ι → ℝ) E) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] (I : box ι) (l : integration_params) (hl : l.bRiemann = ff) : has_integral.{u v v} I l f μ.to_box_additive.to_smul (f.integral (μ.restrict I)) := begin induction f using measure_theory.simple_func.induction with y s hs f g hd hfi hgi, { simpa only [measure.restrict_apply hs, const_zero, integral_piecewise_zero, integral_const, measure.restrict_apply, measurable_set.univ, set.univ_inter] using box_integral.has_integral_indicator_const l hl hs I y μ }, { borelize E, haveI := fact.mk (I.measure_coe_lt_top μ), rw integral_add, exacts [hfi.add hgi, integrable_iff.2 $ λ _ _, measure_lt_top _ _, integrable_iff.2 $ λ _ _, measure_lt_top _ _] } end /-- For a simple function, its McShane (or Henstock, or `⊥`) box integral is equal to its integral in the sense of `measure_theory.simple_func.integral`. -/ lemma box_integral_eq_integral (f : simple_func (ι → ℝ) E) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] (I : box ι) (l : integration_params) (hl : l.bRiemann = ff) : box_integral.integral.{u v v} I l f μ.to_box_additive.to_smul = f.integral (μ.restrict I) := (f.has_box_integral μ I l hl).integral_eq end simple_func open topological_space /-- If `f : ℝⁿ → E` is Bochner integrable w.r.t. a locally finite measure `μ` on a rectangular box `I`, then it is McShane integrable on `I` with the same integral. -/ lemma integrable_on.has_box_integral [complete_space E] {f : (ι → ℝ) → E} {μ : measure (ι → ℝ)} [is_locally_finite_measure μ] {I : box ι} (hf : integrable_on f I μ) (l : integration_params) (hl : l.bRiemann = ff) : has_integral.{u v v} I l f μ.to_box_additive.to_smul (∫ x in I, f x ∂ μ) := begin borelize E, /- First we replace an `ae_strongly_measurable` function by a measurable one. -/ rcases hf.ae_strongly_measurable with ⟨g, hg, hfg⟩, haveI : separable_space (range g ∪ {0} : set E) := hg.separable_space_range_union_singleton, rw integral_congr_ae hfg, have hgi : integrable_on g I μ := (integrable_congr hfg).1 hf, refine box_integral.has_integral.congr_ae _ hfg.symm hl, clear_dependent f, /- Now consider the sequence of simple functions `simple_func.approx_on g hg.measurable (range g ∪ {0}) 0 (by simp)` approximating `g`. Recall some properties of this sequence. -/ set f : ℕ → simple_func (ι → ℝ) E := simple_func.approx_on g hg.measurable (range g ∪ {0}) 0 (by simp), have hfi : ∀ n, integrable_on (f n) I μ, from simple_func.integrable_approx_on_range hg.measurable hgi, have hfi' := λ n, ((f n).has_box_integral μ I l hl).integrable, have hfgi : tendsto (λ n, (f n).integral (μ.restrict I)) at_top (𝓝 $ ∫ x in I, g x ∂μ), from tendsto_integral_approx_on_of_measurable_of_range_subset hg.measurable hgi _ subset.rfl, have hfg_mono : ∀ x {m n}, m ≤ n → ‖f n x - g x‖ ≤ ‖f m x - g x‖, { intros x m n hmn, rw [← dist_eq_norm, ← dist_eq_norm, dist_nndist, dist_nndist, nnreal.coe_le_coe, ← ennreal.coe_le_coe, ← edist_nndist, ← edist_nndist], exact simple_func.edist_approx_on_mono hg.measurable _ x hmn }, /- Now consider `ε > 0`. We need to find `r` such that for any tagged partition subordinate to `r`, the integral sum is `(μ I + 1 + 1) * ε`-close to the Bochner integral. -/ refine has_integral_of_mul ((μ I).to_real + 1 + 1) (λ ε ε0, _), lift ε to ℝ≥0 using ε0.le, rw nnreal.coe_pos at ε0, have ε0' := ennreal.coe_pos.2 ε0, /- Choose `N` such that the integral of `‖f N x - g x‖` is less than or equal to `ε`. -/ obtain ⟨N₀, hN₀⟩ : ∃ N : ℕ, ∫ x in I, ‖f N x - g x‖ ∂μ ≤ ε, { have : tendsto (λ n, ∫⁻ x in I, ‖f n x - g x‖₊ ∂μ) at_top (𝓝 0), from simple_func.tendsto_approx_on_range_L1_nnnorm hg.measurable hgi, refine (this.eventually (ge_mem_nhds ε0')).exists.imp (λ N hN, _), exact integral_coe_le_of_lintegral_coe_le hN }, /- For each `x`, we choose `Nx x ≥ N₀` such that `dist (f Nx x) (g x) ≤ ε`. -/ have : ∀ x, ∃ N₁, N₀ ≤ N₁ ∧ dist (f N₁ x) (g x) ≤ ε, { intro x, have : tendsto (λ n, f n x) at_top (𝓝 $ g x), from simple_func.tendsto_approx_on hg.measurable _ (subset_closure (by simp)), exact ((eventually_ge_at_top N₀).and $ this $ closed_ball_mem_nhds _ ε0).exists }, choose Nx hNx hNxε, /- We also choose a convergent series with `∑' i : ℕ, δ i < ε`. -/ rcases nnreal.exists_pos_sum_of_countable ε0.ne' ℕ with ⟨δ, δ0, c, hδc, hcε⟩, /- Since each simple function `fᵢ` is integrable, there exists `rᵢ : ℝⁿ → (0, ∞)` such that the integral sum of `f` over any tagged prepartition is `δᵢ`-close to the sum of integrals of `fᵢ` over the boxes of this prepartition. For each `x`, we choose `r (Nx x)` as the radius at `x`. -/ set r : ℝ≥0 → (ι → ℝ) → Ioi (0 : ℝ) := λ c x, (hfi' $ Nx x).convergence_r (δ $ Nx x) c x, refine ⟨r, λ c, l.r_cond_of_bRiemann_eq_ff hl, λ c π hπ hπp, _⟩, /- Now we prove the estimate in 3 "jumps": first we replace `g x` in the formula for the integral sum by `f (Nx x)`; then we replace each `μ J • f (Nx (π.tag J)) (π.tag J)` by the Bochner integral of `f (Nx (π.tag J)) x` over `J`, then we jump to the Bochner integral of `g`. -/ refine (dist_triangle4 _ (∑ J in π.boxes, (μ J).to_real • f (Nx $ π.tag J) (π.tag J)) (∑ J in π.boxes, ∫ x in J, f (Nx $ π.tag J) x ∂μ) _).trans _, rw [add_mul, add_mul, one_mul], refine add_le_add_three _ _ _, { /- Since each `f (Nx $ π.tag J)` is `ε`-close to `g (π.tag J)`, replacing the latter with the former in the formula for the integral sum changes the sum at most by `μ I * ε`. -/ rw [← hπp.Union_eq, π.to_prepartition.measure_Union_to_real, sum_mul, integral_sum], refine dist_sum_sum_le_of_le _ (λ J hJ, _), dsimp, rw [dist_eq_norm, ← smul_sub, norm_smul, real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], refine mul_le_mul_of_nonneg_left _ ennreal.to_real_nonneg, rw [← dist_eq_norm'], exact hNxε _ }, { /- We group the terms of both sums by the values of `Nx (π.tag J)`. For each `N`, the sum of Bochner integrals over the boxes is equal to the sum of box integrals, and the sum of box integrals is `δᵢ`-close to the corresponding integral sum due to the Henstock-Sacks inequality. -/ rw [← π.to_prepartition.sum_fiberwise (λ J, Nx (π.tag J)), ← π.to_prepartition.sum_fiberwise (λ J, Nx (π.tag J))], refine le_trans _ (nnreal.coe_lt_coe.2 hcε).le, refine (dist_sum_sum_le_of_le _ (λ n hn, _)).trans (sum_le_has_sum _ (λ n _, (δ n).2) (nnreal.has_sum_coe.2 hδc)), have hNxn : ∀ J ∈ π.filter (λ J, Nx (π.tag J) = n), Nx (π.tag J) = n, from λ J hJ, (π.mem_filter.1 hJ).2, have hrn : ∀ J ∈ π.filter (λ J, Nx (π.tag J) = n), r c (π.tag J) = (hfi' n).convergence_r (δ n) c (π.tag J), { intros J hJ, obtain rfl := hNxn J hJ, refl }, have : l.mem_base_set I c ((hfi' n).convergence_r (δ n) c) (π.filter (λ J, Nx (π.tag J) = n)), from (hπ.filter _).mono' _ le_rfl le_rfl (λ J hJ, (hrn J hJ).le), convert (hfi' n).dist_integral_sum_sum_integral_le_of_mem_base_set (δ0 _) this using 2, { refine sum_congr rfl (λ J hJ, _), simp [hNxn J hJ] }, { refine sum_congr rfl (λ J hJ, _), rw [← simple_func.integral_eq_integral, simple_func.box_integral_eq_integral _ _ _ _ hl, hNxn J hJ], exact (hfi _).mono_set (prepartition.le_of_mem _ hJ) } }, { /- For the last jump, we use the fact that the distance between `f (Nx x) x` and `g x` is less than or equal to the distance between `f N₀ x` and `g x` and the integral of `‖f N₀ x - g x‖` is less than or equal to `ε`. -/ refine le_trans _ hN₀, have hfi : ∀ n (J ∈ π), integrable_on (f n) ↑J μ, from λ n J hJ, (hfi n).mono_set (π.le_of_mem' J hJ), have hgi : ∀ J ∈ π, integrable_on g ↑J μ, from λ J hJ, hgi.mono_set (π.le_of_mem' J hJ), have hfgi : ∀ n (J ∈ π), integrable_on (λ x, ‖f n x - g x‖) J μ, from λ n J hJ, ((hfi n J hJ).sub (hgi J hJ)).norm, rw [← hπp.Union_eq, prepartition.Union_def', integral_finset_bUnion π.boxes (λ J hJ, J.measurable_set_coe) π.pairwise_disjoint hgi, integral_finset_bUnion π.boxes (λ J hJ, J.measurable_set_coe) π.pairwise_disjoint (hfgi _)], refine dist_sum_sum_le_of_le _ (λ J hJ, _), rw [dist_eq_norm, ← integral_sub (hfi _ J hJ) (hgi J hJ)], refine norm_integral_le_of_norm_le (hfgi _ J hJ) (eventually_of_forall $ λ x, _), exact hfg_mono x (hNx (π.tag J)) } end end measure_theory
0a2f525f94731264870beee10206eec035aa259a
d757fb8bb0d538df3510904d3c09a0da191d06b9
/sf_bools.lean
2d36cf64f436dae2360756fd1338567fbd6b8383
[]
no_license
happy-bracket/lean_playground
188f64c2a431dec5617c75e33c7a75e475b9c23d
137b76966001091c445f6f472d27bbe5a8cf5d49
refs/heads/master
1,600,889,668,807
1,575,375,570,000
1,575,375,570,000
225,569,694
2
0
null
null
null
null
UTF-8
Lean
false
false
504
lean
inductive bool' : Type | true' | false' open bool' def or' : bool' -> bool' -> bool' | true' _ := true' | _ true' := true' | _ _ := false' infixr `||` := or' example : true' || false' = true' := rfl example : true' || true' = true' := rfl example : false' || false' = false' := rfl example : false' || true' = true' := rfl def and' : bool' -> bool' -> bool' | false' _ := false' | true' false' := false' | _ _ := true' infixr `&&` := and' def not' : bool' → bool' | true' := false' | _ := true'
ad6aefa227575f462d58de7572cd5d91111d86bf
82e44445c70db0f03e30d7be725775f122d72f3e
/src/linear_algebra/free_module.lean
5587570f573e899311e8341e0575180845e85b53
[ "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
5,690
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.direct_sum.finsupp import linear_algebra.std_basis import logic.small /-! # Free modules We introduce a class `module.free R M`, for `R` a `semiring` and `M` an `R`-module and we provide several basic instances for this class. Use `finsupp.total_id_surjective` to prove that any module is the quotient of a free module. ## Main definition * `module.free R M` : the class of free `R`-modules. -/ universes u v w z variables (R : Type u) (M : Type v) (N : Type z) open_locale tensor_product direct_sum section basic variables [semiring R] [add_comm_monoid M] [module R M] /-- `module.free R M` is the statement that the `R`-module `M` is free.-/ class module.free : Prop := (exists_basis [] : nonempty (Σ (I : Type v), basis I R M)) /- If `M` fits in universe `w`, then freeness is equivalent to existence of a basis in that universe. Note that if `M` does not fit in `w`, the reverse direction of this implication is still true as `module.free.of_basis`. -/ lemma module.free_def [small.{w} M] : module.free R M ↔ ∃ (I : Type w), nonempty (basis I R M) := ⟨ λ h, ⟨shrink (set.range h.exists_basis.some.2), ⟨(basis.reindex_range h.exists_basis.some.2).reindex (equiv_shrink _)⟩⟩, λ h, ⟨(nonempty_sigma.2 h).map $ λ ⟨i, b⟩, ⟨set.range b, b.reindex_range⟩⟩⟩ lemma module.free_iff_set : module.free R M ↔ ∃ (S : set M), nonempty (basis S R M) := ⟨λ h, ⟨set.range h.exists_basis.some.2, ⟨basis.reindex_range h.exists_basis.some.2⟩⟩, λ ⟨S, hS⟩, ⟨nonempty_sigma.2 ⟨S, hS⟩⟩⟩ variables {R M} lemma module.free.of_basis {ι : Type w} (b : basis ι R M) : module.free R M := (module.free_def R M).2 ⟨set.range b, ⟨b.reindex_range⟩⟩ end basic namespace module.free section semiring variables (R M) [semiring R] [add_comm_monoid M] [module R M] [module.free R M] variables [add_comm_monoid N] [module R N] /-- If `[finite_free R M]` then `choose_basis_index R M` is the `ι` which indexes the basis `ι → M`. -/ @[nolint has_inhabited_instance] def choose_basis_index := (exists_basis R M).some.1 /-- If `[finite_free R M]` then `choose_basis : ι → M` is the basis. Here `ι = choose_basis_index R M`. -/ noncomputable def choose_basis : basis (choose_basis_index R M) R M := (exists_basis R M).some.2 /-- The isomorphism `M ≃ₗ[R] (choose_basis_index R M →₀ R)`. -/ noncomputable def repr : M ≃ₗ[R] (choose_basis_index R M →₀ R) := (choose_basis R M).repr /-- The universal property of free modules: giving a functon `(choose_basis_index R M) → N`, for `N` an `R`-module, is the same as giving an `R`-linear map `M →ₗ[R] N`. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ noncomputable def constr {S : Type z} [semiring S] [module S N] [smul_comm_class R S N] : ((choose_basis_index R M) → N) ≃ₗ[S] M →ₗ[R] N := basis.constr (choose_basis R M) S @[priority 100] instance no_zero_smul_divisors [no_zero_divisors R] : no_zero_smul_divisors R M := let ⟨⟨_, b⟩⟩ := exists_basis R M in b.no_zero_smul_divisors variables {R M N} lemma of_equiv (e : M ≃ₗ[R] N) : module.free R N := of_basis $ (choose_basis R M).map e /-- A variation of `of_equiv`: the assumption `module.free R P` here is explicit rather than an instance. -/ lemma of_equiv' {P : Type v} [add_comm_monoid P] [module R P] (h : module.free R P) (e : P ≃ₗ[R] N) : module.free R N := of_equiv e variables (R M N) instance {ι : Type v} : module.free R (ι →₀ R) := of_basis (basis.of_repr (linear_equiv.refl _ _)) instance {ι : Type v} [fintype ι] : module.free R (ι → R) := of_equiv (basis.of_repr $ linear_equiv.refl _ _).equiv_fun instance prod [module.free R N] : module.free R (M × N) := of_basis $ (choose_basis R M).prod (choose_basis R N) instance self : module.free R R := of_basis $ basis.singleton unit R @[priority 100] instance of_subsingleton [subsingleton N] : module.free R N := of_basis (basis.empty N : basis pempty R N) instance dfinsupp {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π₀ i, M i) := of_basis $ dfinsupp.basis $ λ i, choose_basis R (M i) instance direct_sum {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (⨁ i, M i) := module.free.dfinsupp R M instance pi {ι : Type*} [fintype ι] {M : ι → Type*} [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π i, M i) := of_basis $ pi.basis $ λ i, choose_basis R (M i) end semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] instance tensor [module.free R M] [module.free R N] : module.free R (M ⊗[R] N) := of_equiv' (of_equiv' (finsupp.free R) (finsupp_tensor_finsupp' R _ _).symm) (tensor_product.congr (choose_basis R M).repr (choose_basis R N).repr).symm end comm_ring section division_ring variables [division_ring R] [add_comm_group M] [module R M] @[priority 100] instance of_division_ring : module.free R M := of_basis (basis.of_vector_space R M) end division_ring end module.free
fa9cca865c142f1f010552a04087571b1d5914d6
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/algebra/group_power.lean
5fe40d48ca9a15af11189f022a7f1f33ac4594c7
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
28,831
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import data.int.basic data.equiv.basic /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. ## Notation The class `has_pow α β` provides the notation `a^b` for powers. We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`. ## Implementation details We adopt the convention that `0^0 = 1`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M | 0 := 1 | (n+1) := a * monoid.pow n /-- The scalar multiplication in an additive monoid. `n • a = a+a+...+a` n times. -/ def add_monoid.smul [has_add A] [has_zero A] (n : ℕ) (a : A) : A := @monoid.pow (multiplicative A) _ { one := (0 : A) } a n precedence `•`:70 localized "infix ` • ` := add_monoid.smul" in add_monoid @[priority 5] instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩ /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl @[simp] theorem add_monoid.zero_smul (a : A) : 0 • a = 0 := rfl theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_smul (a : A) (n : ℕ) : (n+1)•a = a + n•a := rfl @[simp] theorem pow_one (a : M) : a^1 = a := mul_one _ @[simp] theorem add_monoid.one_smul (a : A) : 1•a = a := add_zero _ @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := by induction n with n ih; [rw [pow_zero, one_mul, mul_one], rw [pow_succ, mul_assoc, ih]] theorem smul_add_comm' : ∀ (a : A) (n : ℕ), n•a + a = a + n•a := @pow_mul_comm' (multiplicative A) _ theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_smul' (a : A) (n : ℕ) : (n+1)•a = n•a + a := by rw [succ_smul, smul_add_comm'] theorem pow_two (a : M) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_smul (a : A) : 2•a = a + a := show a+(a+0)=a+a, by rw add_zero theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [add_zero, pow_zero, mul_one], rw [pow_succ, ← pow_mul_comm', ← mul_assoc, ← ih, ← pow_succ']]; refl theorem add_monoid.add_smul : ∀ (a : A) (m n : ℕ), (m + n)•a = m•a + n•a := @pow_add (multiplicative A) _ @[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : A) = 0 := by induction n with n ih; [refl, rw [succ_smul, ih, zero_add]] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem add_monoid.mul_smul' : ∀ (a : A) (m n : ℕ), m * n • a = n•(m•a) := @pow_mul (multiplicative A) _ theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem add_monoid.mul_smul (a : A) (m n : ℕ) : m * n • a = m•(n•a) := by rw [mul_comm, add_monoid.mul_smul'] @[simp] theorem add_monoid.smul_one [has_one A] : ∀ n : ℕ, n • (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n • (1 : A), add_monoid.zero_smul _, λ _ _, add_monoid.add_smul _ _ _⟩ (add_monoid.one_smul _) theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_smul (a : A) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _ theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_smul : ∀ (a : A) (n : ℕ), bit1 n • a = n•a + n•a + a := @pow_bit1 (multiplicative A) _ theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := by rw [←pow_add, ←pow_add, add_comm] theorem smul_add_comm : ∀ (a : A) (m n : ℕ), m•a + n•a = n•a + m•a := @pow_mul_comm (multiplicative A) _ @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative A) _ theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] theorem monoid_hom.iterate_map_pow (f : M →* M) (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := show f^[n] ((λ x, x^m) a) = (λ x, x^m) (f^[n] a), from nat.iterate₁ $ λ x, f.map_pow x m theorem add_monoid_hom.map_smul (f : A →+ B) (a : A) (n : ℕ) : f (n • a) = n • f a := f.to_multiplicative.map_pow a n theorem add_monoid_hom.iterate_map_smul (f : A →+ A) (a : A) (n m : ℕ) : f^[n] (m • a) = m • (f^[n] a) := f.to_multiplicative.iterate_map_pow a n m theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n := (monoid_hom.of f).map_pow a theorem is_add_monoid_hom.map_smul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n • a) = n • f a := (add_monoid_hom.of f).map_smul a n @[simp] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n end monoid @[simp] theorem nat.pow_eq_pow (p q : ℕ) : @has_pow.pow _ _ monoid.has_pow p q = p ^ q := by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ, mul_comm, ih]] @[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n := by induction m with m ih; [rw [add_monoid.zero_smul, zero_mul], rw [succ_smul', ih, nat.succ_mul]] /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := by induction n with n ih; [exact (mul_one _).symm, simp only [pow_succ, ih, mul_assoc, mul_left_comm]] theorem add_monoid.smul_add : ∀ (a b : A) (n : ℕ), n•(a + b) = n•a + n•b := @mul_pow (multiplicative A) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance add_monoid.smul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (add_monoid.smul n : A → A) := { map_add := λ _ _, add_monoid.smul_add _ _ _, map_zero := add_monoid.smul_zero _ } end comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] section nat @[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem add_monoid.neg_smul : ∀ (a : A) (n : ℕ), n•(-a) = -(n•a) := @inv_pow (multiplicative A) _ theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem add_monoid.smul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n)•a = m•a - n•a := @pow_sub (multiplicative A) _ theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _) theorem add_monoid.smul_neg_comm : ∀ (a : A) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) := @pow_inv_comm (multiplicative A) _ end nat open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : G) : ℤ → G | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ /-- The scalar multiplication by integers on an additive group. This extends `add_monoid.smul` to negative integers with the definition `(-n) • a = -(n • a)`. -/ def gsmul (n : ℤ) (a : A) : A := @gpow (multiplicative A) _ a n @[priority 10] instance group.has_pow : has_pow G ℤ := ⟨gpow⟩ localized "infix ` • `:70 := gsmul" in add_group localized "infix ` •ℕ `:70 := add_monoid.smul" in smul localized "infix ` •ℤ `:70 := gsmul" in smul @[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n • a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ (a : A) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : A) : (0:ℤ) • a = 0 := rfl @[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := mul_one _ @[simp] theorem one_gsmul (a : A) : (1:ℤ) • a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:G), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n • (0 : A) = 0 := @one_gpow (multiplicative A) _ @[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm @[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n • a = -(n • a) := @gpow_neg (multiplicative A) _ theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : A) : (-1:ℤ) • x = -x := congr_arg has_neg.neg $ add_monoid.one_smul x theorem gsmul_one [has_one A] (n : ℤ) : n • (1 : A) = n := by cases n; simp theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a := @inv_gpow (multiplicative A) _ a n private lemma gpow_add_aux (a : G) (m n : nat) : a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] := or.elim (nat.lt_or_ge m (nat.succ n)) (assume h1 : m < succ n, have h2 : m ≤ n, from le_of_lt_succ h1, suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by rwa [of_nat_add_neg_succ_of_nat_of_lt h1], show (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw [← succ_sub h2, pow_sub _ (le_of_lt h1), mul_inv_rev, inv_inv]; refl) (assume : m ≥ succ n, suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]), by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption, suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this, by rw pow_sub; assumption) theorem gpow_add (a : G) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j | (of_nat m) (of_nat n) := pow_add _ _ _ | (of_nat m) -[1+n] := gpow_add_aux _ _ _ | -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux, gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm] | -[1+m] -[1+n] := suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this, by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev] theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) • a = i • a + j • a := @gpow_add (multiplicative A) _ theorem gpow_add_one (a : G) (i : ℤ) : a ^ (i + 1) = a ^ i * a := by rw [gpow_add, gpow_one] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) • a = i • a + a := @gpow_add_one (multiplicative A) _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) • a = a + i • a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i • a + j • a = j • a + i • a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n | (m : ℕ) (n : ℕ) := pow_mul _ _ _ | (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $ show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl | -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $ show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow]; refl | -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ show _ = (_⁻¹^_)⁻¹, by rw [inv_pow, inv_inv] theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n • a = n • (m • a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n • a = m • (n • a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n • a = n • a + n • a + a := @gpow_bit1 (multiplicative A) _ theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n • a) = n • f a := f.to_multiplicative.map_gpow a n end group open_locale smul section comm_group variables [comm_group G] [add_comm_group A] theorem mul_gpow (a b : G) : ∀ n:ℤ, (a * b)^n = a^n * b^n | (n : ℕ) := mul_pow a b n | -[1+ n] := show _⁻¹=_⁻¹*_⁻¹, by rw [mul_pow, mul_inv_rev, mul_comm] theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative A) _ theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b := by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) := { map_add := λ _ _, gsmul_add _ _ n } end comm_group @[simp] lemma with_bot.coe_smul [add_monoid A] (a : A) (n : ℕ) : ((add_monoid.smul n a : A) : with_bot A) = add_monoid.smul n a := add_monoid_hom.map_smul ⟨_, with_bot.coe_zero, with_bot.coe_add⟩ a n theorem add_monoid.smul_eq_mul' [semiring R] (a : R) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [add_monoid.zero_smul, nat.cast_zero, mul_zero], rw [succ_smul', ih, nat.cast_succ, mul_add, mul_one]] theorem add_monoid.smul_eq_mul [semiring R] (n : ℕ) (a : R) : n • a = n * a := by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm] theorem add_monoid.mul_smul_left [semiring R] (a b : R) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc] theorem add_monoid.mul_smul_assoc [semiring R] (a b : R) (n : ℕ) : n • (a * b) = n • a * b := by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc] lemma zero_pow [semiring R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := zero_mul _ @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a variable (f : R →+* R) lemma iterate_map_pow (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := f.to_monoid_hom.iterate_map_pow a n m lemma iterate_map_smul (a) (n m : ℕ) : f^[n] (m • a) = m • (f^[n] a) := f.to_add_monoid_hom.iterate_map_smul a n m end ring_hom lemma is_semiring_hom.map_pow [semiring R] [semiring S] (f : R → S) [is_semiring_hom f] (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := is_monoid_hom.map_pow f a theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [comm_semiring R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩ theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := add_monoid.smul_eq_mul _ _ | -[1+ n] := show -(_•_)=-_*_, by rw [neg_mul_eq_neg_mul_symm, add_monoid.smul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, int.mul_cast_comm] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = -1 ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [domain R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[field_simps] theorem pow_ne_zero [domain R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h theorem add_monoid.smul_nonneg [ordered_add_comm_monoid R] {a : R} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a | 0 := le_refl _ | (n+1) := add_nonneg' H (add_monoid.smul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] namespace add_monoid variable [ordered_add_comm_monoid A] theorem smul_le_smul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := let ⟨k, hk⟩ := nat.le.dest h in calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + k • a : add_le_add_left' (smul_nonneg ha _) ... = m • a : by rw [← hk, add_smul] lemma smul_le_smul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i • a ≤ i • b | 0 := by simp | (k+1) := add_le_add' hab (smul_le_smul_of_le_right _) end add_monoid namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := canonically_ordered_semiring.zero_lt_one | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_right_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) /-- Bernoulli's inequality. This version works for semirings but requires an additional hypothesis `0 ≤ a * a`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := calc 1 + (n + 1) • a ≤ (1 + a) * (1 + n • a) : by simpa [succ_smul, mul_add, add_mul, add_monoid.mul_smul_left, add_comm, add_left_comm] using add_monoid.smul_nonneg Hsqr n ... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 := by { rw pow_two, exact mul_self_nonneg _ } /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | 1 := by simp | (n+2) := have H' : 0 ≤ 2 + a, from neg_le_iff_add_nonneg.1 H, have 0 ≤ n • (a * a * (2 + a)) + a * a, from add_nonneg (add_monoid.smul_nonneg (mul_nonneg (mul_self_nonneg a) H') n) (mul_self_nonneg a), calc 1 + (n + 2) • a ≤ 1 + (n + 2) • a + (n • (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n • a) : by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_smul, add_monoid.smul_add, add_monoid.mul_smul_assoc, (add_monoid.mul_smul_left _ _ _).symm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a)) ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_sub_mul_le_pow [linear_ordered_ring R] {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 }, by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] @[simp] lemma pow_of_add [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl @[simp] lemma gpow_of_add [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← pow_of_add] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← gpow_of_add] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n • x, add_monoid.zero_smul x, λ m n, add_monoid.add_smul _ _ _⟩, inv_fun := λ f, f 1, left_inv := add_monoid.one_smul, right_inv := λ f, add_monoid_hom.ext $ λ n, by simp [← f.map_smul] } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext $ λ n, by simp [← f.map_gsmul] }
05cbf4a158874a8c98006b526f8ca10d1c0c6554
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/pretty_cases.lean
b078016019891516a18aa8d62b1c480435117b30
[ "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
886
lean
import tactic.pretty_cases import data.list.perm example {α} (xs ys : list α) (h : xs ~ ys) : true := begin induction h, do { x ← tactic.pretty_cases_advice, guard (x = "Try this: case list.perm.nil { admit }, case list.perm.cons : h_x h_l₁ h_l₂ h_ᾰ h_ih { admit }, case list.perm.swap : h_x h_y h_l { admit }, case list.perm.trans : h_l₁ h_l₂ h_l₃ h_ᾰ h_ᾰ_1 h_ih_ᾰ h_ih_ᾰ_1 { admit }" ) <|> fail!"expecting: {repr x}" }, all_goals { trivial } end example {α} (xs ys : list α) (h : xs ~ ys) : true := begin cases h, do { x ← tactic.pretty_cases_advice, guard (x = "Try this: case list.perm.nil { admit }, case list.perm.cons : h_x h_l₁ h_l₂ h_ᾰ { admit }, case list.perm.swap : h_x h_y h_l { admit }, case list.perm.trans : xs h_l₂ ys h_ᾰ h_ᾰ_1 { admit }") }, all_goals { trivial } end
795929aa6a2c6eb9428fbbe7ef255a229f03b65f
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/theories/topology/basic.lean
b902d2bde0e538335a71d94bc41f8eb80b3b189c
[ "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
7,500
lean
/- Copyright (c) 2015 Jacob Gross. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jacob Gross, Jeremy Avigad Open and closed sets, seperation axioms and generated topologies. -/ import data.set data.nat open algebra eq.ops set nat structure topology [class] (X : Type) := (opens : set (set X)) (univ_mem_opens : univ ∈ opens) (sUnion_mem_opens : ∀ {S : set (set X)}, S ⊆ opens → ⋃₀ S ∈ opens) (inter_mem_opens : ∀₀ s ∈ opens, ∀₀ t ∈ opens, s ∩ t ∈ opens) namespace topology variables {X : Type} [topology X] /- open sets -/ definition Open (s : set X) : Prop := s ∈ opens X theorem Open_empty : Open (∅ : set X) := have ∅ ⊆ opens X, from empty_subset _, have ⋃₀ ∅ ∈ opens X, from sUnion_mem_opens this, show ∅ ∈ opens X, using this, by rewrite -sUnion_empty; apply this theorem Open_univ : Open (univ : set X) := univ_mem_opens X theorem Open_sUnion {S : set (set X)} (H : ∀₀ t ∈ S, Open t) : Open (⋃₀ S) := sUnion_mem_opens H theorem Open_Union {I : Type} {s : I → set X} (H : ∀ i, Open (s i)) : Open (⋃ i, s i) := have ∀₀ t ∈ s ' univ, Open t, from take t, suppose t ∈ s ' univ, obtain i [univi (Hi : s i = t)], from this, show Open t, by rewrite -Hi; exact H i, using this, by rewrite Union_eq_sUnion_image; apply Open_sUnion this theorem Open_union {s t : set X} (Hs : Open s) (Ht : Open t) : Open (s ∪ t) := have ∀ i, Open (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht, show Open (s ∪ t), using this, by rewrite -Union_bin_ext; exact Open_Union this theorem Open_inter {s t : set X} (Hs : Open s) (Ht : Open t) : Open (s ∩ t) := inter_mem_opens X Hs Ht theorem Open_sInter_of_finite {s : set (set X)} [fins : finite s] (H : ∀₀ t ∈ s, Open t) : Open (⋂₀ s) := begin induction fins with a s fins anins ih, {rewrite sInter_empty, exact Open_univ}, rewrite sInter_insert, apply Open_inter, show Open a, from H (mem_insert a s), apply ih, intros t ts, show Open t, from H (mem_insert_of_mem a ts) end /- closed sets -/ definition closed [reducible] (s : set X) : Prop := Open (-s) theorem closed_iff_Open_comp (s : set X) : closed s ↔ Open (-s) := !iff.refl theorem Open_iff_closed_comp (s : set X) : Open s ↔ closed (-s) := by rewrite [closed_iff_Open_comp, comp_comp] theorem closed_comp {s : set X} (H : Open s) : closed (-s) := by rewrite [-Open_iff_closed_comp]; apply H theorem closed_empty : closed (∅ : set X) := by rewrite [↑closed, comp_empty]; exact Open_univ theorem closed_univ : closed (univ : set X) := by rewrite [↑closed, comp_univ]; exact Open_empty theorem closed_sInter {S : set (set X)} (H : ∀₀ t ∈ S, closed t) : closed (⋂₀ S) := begin rewrite [↑closed, comp_sInter], apply Open_sUnion, intro t, rewrite [mem_image_complement, Open_iff_closed_comp], apply H end theorem closed_Inter {I : Type} {s : I → set X} (H : ∀ i, closed (s i : set X)) : closed (⋂ i, s i) := by rewrite [↑closed, comp_Inter]; apply Open_Union; apply H theorem closed_inter {s t : set X} (Hs : closed s) (Ht : closed t) : closed (s ∩ t) := by rewrite [↑closed, comp_inter]; apply Open_union; apply Hs; apply Ht theorem closed_union {s t : set X} (Hs : closed s) (Ht : closed t) : closed (s ∪ t) := by rewrite [↑closed, comp_union]; apply Open_inter; apply Hs; apply Ht theorem closed_sUnion_of_finite {s : set (set X)} [fins : finite s] (H : ∀₀ t ∈ s, closed t) : closed (⋂₀ s) := begin rewrite [↑closed, comp_sInter], apply Open_sUnion, intro t, rewrite [mem_image_complement, Open_iff_closed_comp], apply H end theorem open_diff {s t : set X} (Hs : Open s) (Ht : closed t) : Open (s \ t) := Open_inter Hs Ht theorem closed_diff {s t : set X} (Hs : closed s) (Ht : Open t) : closed (s \ t) := closed_inter Hs (closed_comp Ht) end topology /- separation -/ structure T0_space [class] (X : Type) extends topology X := (T0 : ∀ {x y}, x ≠ y → ∃ U, U ∈ opens ∧ ¬(x ∈ U ↔ y ∈ U)) namespace topology variables {X : Type} [T0_space X] theorem T0 {x y : X} (H : x ≠ y) : ∃ U, Open U ∧ ¬(x ∈ U ↔ y ∈ U) := T0_space.T0 H end topology structure T1_space [class] (X : Type) extends topology X := (T1 : ∀ {x y}, x ≠ y → ∃ U, U ∈ opens ∧ x ∈ U ∧ y ∉ U) protected definition T0_space.of_T1 [reducible] [trans_instance] {X : Type} [T : T1_space X] : T0_space X := ⦃T0_space, T, T0 := abstract take x y, assume H, obtain U [Uopens [xU ynU]], from T1_space.T1 H, exists.intro U (and.intro Uopens (show ¬ (x ∈ U ↔ y ∈ U), from assume H, ynU (iff.mp H xU))) end ⦄ namespace topology variables {X : Type} [T1_space X] theorem T1 {x y : X} (H : x ≠ y) : ∃ U, Open U ∧ x ∈ U ∧ y ∉ U := T1_space.T1 H end topology structure T2_space [class] (X : Type) extends topology X := (T2 : ∀ {x y}, x ≠ y → ∃ U V, U ∈ opens ∧ V ∈ opens ∧ x ∈ U ∧ y ∈ V ∧ U ∩ V = ∅) protected definition T1_space.of_T2 [reducible] [trans_instance] {X : Type} [T : T2_space X] : T1_space X := ⦃T1_space, T, T1 := abstract take x y, assume H, obtain U [V [Uopens [Vopens [xU [yV UVempty]]]]], from T2_space.T2 H, exists.intro U (and.intro Uopens (and.intro xU (show y ∉ U, from assume yU, have y ∈ U ∩ V, from and.intro yU yV, show y ∈ ∅, from UVempty ▸ this))) end ⦄ namespace topology variables {X : Type} [T2_space X] theorem T2 {x y : X} (H : x ≠ y) : ∃ U V, Open U ∧ Open V ∧ x ∈ U ∧ y ∈ V ∧ U ∩ V = ∅ := T2_space.T2 H end topology structure perfect_space [class] (X : Type) extends topology X := (perfect : ∀ x, '{x} ∉ opens) /- topology generated by a set -/ namespace topology inductive opens_generated_by {X : Type} (B : set (set X)) : set X → Prop := | generators_mem : ∀ ⦃s : set X⦄, s ∈ B → opens_generated_by B s | univ_mem : opens_generated_by B univ | inter_mem : ∀ ⦃s t⦄, opens_generated_by B s → opens_generated_by B t → opens_generated_by B (s ∩ t) | sUnion_mem : ∀ ⦃S : set (set X)⦄, S ⊆ opens_generated_by B → opens_generated_by B (⋃₀ S) protected definition generated_by [instance] [reducible] {X : Type} (B : set (set X)) : topology X := ⦃topology, opens := opens_generated_by B, univ_mem_opens := opens_generated_by.univ_mem B, inter_mem_opens := λ s Hs t Ht, opens_generated_by.inter_mem Hs Ht, sUnion_mem_opens := opens_generated_by.sUnion_mem ⦄ theorem generators_mem_topology_generated_by {X : Type} (B : set (set X)) : let T := topology.generated_by B in ∀₀ s ∈ B, @Open _ T s := λ s H, opens_generated_by.generators_mem H theorem opens_generated_by_initial {X : Type} {B : set (set X)} {T : topology X} (H : B ⊆ @opens _ T) : opens_generated_by B ⊆ @opens _ T := begin intro s Hs, induction Hs with s sB s t os ot soX toX S SB SOX, {exact H sB}, {exact univ_mem_opens X}, {exact inter_mem_opens X soX toX}, exact sUnion_mem_opens SOX end theorem topology_generated_by_initial {X : Type} {B : set (set X)} {T : topology X} (H : ∀₀ s ∈ B, @Open _ T s) {s : set X} (H1 : @Open _ (topology.generated_by B) s) : @Open _ T s := opens_generated_by_initial H H1 end topology
7b34fed773b76cc4f982653f8fdd57254157b6ed
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/functor.lean
dc77be75ec4a4001d8004f98a4f5956828734410
[ "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
3,526
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison -/ import tactic.reassoc_axiom import tactic.monotonicity import category_theory.category.basic /-! # Functors Defines a functor between categories, extending a `prefunctor` between quivers. Introduces notation `C ⥤ D` for the type of all functors from `C` to `D`. (Unfortunately the `⇒` arrow (`\functor`) is taken by core, but in mathlib4 we should switch to this.) -/ namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v v₁ v₂ v₃ u u₁ u₂ u₃ section set_option old_structure_cmd true /-- `functor C D` represents a functor between categories `C` and `D`. To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`. The axiom `map_id` expresses preservation of identities, and `map_comp` expresses functoriality. See https://stacks.math.columbia.edu/tag/001B. -/ structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] extends prefunctor C D : Type (max v₁ v₂ u₁ u₂) := (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) /-- The prefunctor between the underlying quivers. -/ add_decl_doc functor.to_prefunctor end -- A functor is basically a function, so give ⥤ a similar precedence to → (25). -- For example, `C × D ⥤ E` should parse as `(C × D) ⥤ E` not `C × (D ⥤ E)`. infixr ` ⥤ `:26 := functor -- type as \func -- restate_axiom functor.map_id' attribute [simp] functor.map_id restate_axiom functor.map_comp' attribute [reassoc, simp] functor.map_comp namespace functor section variables (C : Type u₁) [category.{v₁} C] /-- `𝟭 C` is the identity functor on a category `C`. -/ protected def id : C ⥤ C := { obj := λ X, X, map := λ _ _ f, f } notation `𝟭` := functor.id -- Type this as `\sb1` instance : inhabited (C ⥤ C) := ⟨functor.id C⟩ variable {C} @[simp] lemma id_obj (X : C) : (𝟭 C).obj X = X := rfl @[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (𝟭 C).map f = f := rfl end section variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] /-- `F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`). -/ def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E := { obj := λ X, G.obj (F.obj X), map := λ _ _ f, G.map (F.map f) } infixr ` ⋙ `:80 := comp @[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) {X Y : C} (f : X ⟶ Y) : (F ⋙ G).map f = G.map (F.map f) := rfl -- These are not simp lemmas because rewriting along equalities between functors -- is not necessarily a good idea. -- Natural isomorphisms are also provided in `whiskering.lean`. protected lemma comp_id (F : C ⥤ D) : F ⋙ (𝟭 D) = F := by cases F; refl protected lemma id_comp (F : C ⥤ D) : (𝟭 C) ⋙ F = F := by cases F; refl @[simp] lemma map_dite (F : C ⥤ D) {X Y : C} {P : Prop} [decidable P] (f : P → (X ⟶ Y)) (g : ¬P → (X ⟶ Y)) : F.map (if h : P then f h else g h) = if h : P then F.map (f h) else F.map (g h) := by { split_ifs; refl, } end end functor end category_theory
5b5f7cb0b12b8d375c6b2ab78791477095da3251
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/forest2.lean
c348a10bf09eacf961cb3d392ec4d8e069667582
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,663
lean
import data.prod data.unit open prod inductive tree (A : Type) : Type := | node : A → forest A → tree A with forest : Type := | nil : forest A | cons : tree A → forest A → forest A namespace solution1 inductive tree_forest (A : Type) := | of_tree : tree A → tree_forest A | of_forest : forest A → tree_forest A inductive same_kind {A : Type} : tree_forest A → tree_forest A → Type := | is_tree : Π (t₁ t₂ : tree A), same_kind (tree_forest.of_tree t₁) (tree_forest.of_tree t₂) | is_forest : Π (f₁ f₂ : forest A), same_kind (tree_forest.of_forest f₁) (tree_forest.of_forest f₂) definition to_tree {A : Type} (tf : tree_forest A) (t : tree A) : same_kind tf (tree_forest.of_tree t) → tree A := tree_forest.cases_on tf (λ t₁ H, t₁) (λ f₁ H, by cases H) end solution1 namespace solution2 variables {A B : Type} inductive same_kind : sum A B → sum A B → Prop := | isl : Π (a₁ a₂ : A), same_kind (sum.inl a₁) (sum.inl a₂) | isr : Π (b₁ b₂ : B), same_kind (sum.inr b₁) (sum.inr b₂) definition to_left (s : sum A B) (a : A) : same_kind s (sum.inl a) → A := sum.cases_on s (λ a₁ H, a₁) (λ b₁ H, false.rec _ (by cases H)) definition to_right (s : sum A B) (b : B) : same_kind s (sum.inr b) → B := sum.cases_on s (λ a₁ H, false.rec _ (by cases H)) (λ b₁ H, b₁) theorem to_left_inl (a₁ a₂ : A) (H : same_kind (sum.intro_left B a₁) (sum.inl a₂)) : to_left (sum.inl a₁) a₂ H = a₁ := rfl theorem to_right_inr (b₁ b₂ : B) (H : same_kind (sum.intro_right A b₁) (sum.inr b₂)) : to_right (sum.inr b₁) b₂ H = b₁ := rfl end solution2
261c781da12f6d9010cdf04376aa28c1df714c54
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/basic_monitor3.lean
a66c1d952e28bf0634072905d4fcf9934f9f1b79
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,619
lean
meta def get_file (fn : name) : vm format := do { d ← vm.get_decl fn, some n ← return (vm_decl.olean d) | failure, return (to_fmt n) } <|> return (to_fmt "<curr file>") meta def pos_info (fn : name) : vm format := do { d ← vm.get_decl fn, some pos ← return (vm_decl.pos d) | failure, file ← get_file fn, return (file ++ ":" ++ pos.1 ++ ":" ++ pos.2) } <|> return (to_fmt "<position not available>") meta def obj_fmt (o : vm_obj) : vm format := match o^.kind with | vm_obj_kind.tactic_state := return (to_fmt "state:" ++ format.nest 8 (format.line ++ o^.to_tactic_state^.to_format)) | _ := do s ← vm.obj_to_string o, return $ to_fmt s end meta def display_args_aux : nat → vm unit | i := do sz ← vm.stack_size, if i = sz then return () else do o ← vm.stack_obj i, (n, t) ← vm.stack_obj_info i, fmt ← obj_fmt o, vm.trace (to_fmt " " ++ to_fmt n ++ " := " ++ fmt), display_args_aux (i+1) meta def display_args : vm unit := do bp ← vm.bp, display_args_aux bp meta def basic_monitor : vm_monitor nat := { init := 1000, step := λ sz, do csz ← vm.call_stack_size, if sz = csz then return sz else do { fn ← vm.curr_fn, pos ← pos_info fn, vm.trace (to_fmt "[" ++ csz ++ "]: " ++ to_fmt fn ++ " @ " ++ pos), display_args, return csz } <|> return csz -- curr_fn failed } run_cmd vm_monitor.register `basic_monitor set_option debugger true open tactic example (a b : Prop) : a → b → a ∧ b := by (intros >> constructor >> repeat assumption)
2d8d9e436c1d66a54b6e9f06403e517ec73591d4
1fd908b06e3f9c1252cb2285ada1102623a67f72
/init/pointed.lean
a34e2f9d086ab3ee394d9f06255ef4568c720185
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
6,810
lean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The definition of pointed types. This file is here to avoid circularities in the import graph -/ import .trunc universes u v w namespace hott hott_theory open eq equiv is_equiv is_trunc class pointed (A : Type u) := (point : A) structure pType := (carrier : Type u) (Point : carrier) notation `Type*` := pType namespace pointed instance : has_coe_to_sort pType.{u} := { S := Type u, coe := pType.carrier, } variables {A : Type _} @[hott, reducible] def pt [H : pointed A] := point A @[hott, reducible] def Point (A : Type*) := pType.Point A @[hott, reducible] def carrier (A : Type*) := pType.carrier A @[hott, reducible] protected def Mk {A : Type _} (a : A) := pType.mk A a @[hott, reducible] protected def MK (A : Type _) (a : A) := pType.mk A a @[hott, reducible] protected def mk' (A : Type _) [H : pointed A] : Type* := pType.mk A (point A) @[hott, instance, priority 1900] def pointed_carrier (A : Type*) : pointed A := pointed.mk (Point A) @[hott, hsimp] def coe_pType_mk (A : Type _) (a : A) : @coe_sort _ pointed.has_coe_to_sort {pType . carrier := A, Point := a} = A := by refl @[hott, hsimp] def pt_pointed_mk (A : Type _) (a : A) : @pt A (pointed.mk a) = a := by refl @[hott, hsimp] def Point_pType_mk (A : Type _) (a : A) : Point (pType.mk A a) = a := by refl end pointed open pointed set_option old_structure_cmd true section structure ptrunctype (n : ℕ₋₂) extends trunctype.{u} n, pType.{u} notation n `-Type*` := ptrunctype n @[reducible, hott] def pSet := 0-Type* notation `Set*` := pSet @[hott] instance pType_of_ptrunctype (n : ℕ₋₂) : has_coe (n-Type*) Type* := ⟨λx, x.to_pType⟩ @[hott] instance pType_of_pSet : has_coe Set* Type* := hott.pType_of_ptrunctype 0 @[hott] instance trunctype_of_ptrunctype (n : ℕ₋₂) : has_coe (n-Type*) (n-Type) := ⟨λx, x.to_trunctype⟩ @[hott, hsimp] def coe_ptrunctype_mk (A : Type _) {n : ℕ₋₂} (H : is_trunc n A) (a : A) : @coe_sort _ (@coe_sort_trans _ _ (@coe_base_aux _ _ (hott.trunctype_of_ptrunctype n)) (hott.has_coe_to_sort n)) {ptrunctype . carrier := A, Point := a, struct := H} = A := by refl @[hott, hsimp] def to_pType_ptrunctype_mk (A : Type _) {n : ℕ₋₂} (H : is_trunc n A) (a : A) : {ptrunctype . carrier := A, Point := a, struct := H}.to_pType = {carrier := A, Point := a} := by refl -- @[hott] instance ptrunctype.has_coe_to_sort (n) : has_coe_to_sort (ptrunctype n) := -- ⟨_, ptrunctype.carrier⟩ @[hott] instance is_trunc_ptrunctype {n : ℕ₋₂} (X : ptrunctype n) : is_trunc n X := X.struct @[hott] instance is_trunc_pointed {n : ℕ₋₂} (X : ptrunctype n) : pointed X := pointed_carrier X.to_pType end namespace pointed @[hott] protected def ptrunctype.mk' (n : ℕ₋₂) (A : Type _) [pointed A] [is_trunc n A] : n-Type* := ptrunctype.mk A (by apply_instance) pt @[hott] protected def pSet.mk := @ptrunctype.mk (-1.+1) @[hott] protected def pSet.mk' := ptrunctype.mk' (-1.+1) @[hott] def ptrunctype_of_trunctype {n : ℕ₋₂} (A : n-Type) (a : A) : n-Type* := ptrunctype.mk A (by apply_instance) a @[hott] def ptrunctype_of_pType {n : ℕ₋₂} (A : Type*) (H : is_trunc n A) : n-Type* := ptrunctype.mk A (by apply_instance) pt @[hott] def pSet_of_Set (A : Set) (a : A) : Set* := ptrunctype.mk A (by apply_instance) a @[hott] def pSet_of_pType (A : Type*) (H : is_set A) : Set* := ptrunctype.mk A (by apply_instance) pt -- Any contractible type is pointed @[hott, instance] def pointed_of_is_contr (A : Type _) [H : is_contr A] : pointed A := pointed.mk (center _) end pointed /- pointed maps -/ variables {A : Type*} structure ppi (P : A → Type _) (x₀ : P pt) := (to_fun : Π a : A, P a) (resp_pt : to_fun (Point A) = x₀) @[hott] def pppi' (P : A → Type*) : Type _ := ppi (λ a, P a) pt @[hott] def ppi_const (P : A → Type*) : pppi' P := ppi.mk (λa, pt) idp @[hott] def pppi (P : A → Type*) : Type* := pointed.MK (pppi' P) (ppi_const P) -- do we want to make this already pointed? @[hott] def pmap (A B : Type*) : Type _ := @pppi A (λa, B) @[hott] instance (P : A → Type _) (x₀): has_coe_to_fun (ppi P x₀) := { F := λ f, Π a, P a, coe := λ f a, f.to_fun a } @[hott, hsimp] def coe_fn_ppi {P : A → Type _} {x₀} (f : Πa, P a) (p : f (Point A) = x₀) : @coe_fn _ (hott.has_coe_to_fun P x₀) {ppi . to_fun := f, resp_pt := p} = f := by refl infix ` →* `:28 := pmap notation `Π*` binders `, ` r:(scoped P, pppi P) := r namespace pointed @[hott] def pppi.mk {P : A → Type*} (f : Πa, P a) (p : f pt = pt) : pppi P := ppi.mk f p @[hott] def pppi.to_fun {P : A → Type*} (f : pppi' P) (a : A) : P a := ppi.to_fun f a @[hott] instance {P : A → Type*}: has_coe_to_fun (pppi' P) := { F := λ f, Π a, P a, coe := λ f a, f.to_fun a, } @[hott] def pmap.mk {A B : Type*} (f : A → B) (p : f (Point A) = Point B) : A →* B := pppi.mk f p @[reducible] def pmap.to_fun {A B : Type*} (f : A →* B) : A → B := pppi.to_fun f @[hott] instance pmap.has_coe_to_fun {A B : Type*}: has_coe_to_fun (A →* B) := { F := λ f, A → B, coe := pmap.to_fun, } @[hott] def respect_pt {P : A → Type _} {p₀ : P pt} (f : ppi P p₀) : f pt = p₀ := ppi.resp_pt f -- notation `Π*` binders `, ` r:(scoped P, ppi _ P) := r -- @[hott] def pmxap.mk [constructor] {A B : Type*} (f : A → B) (p : f pt = pt) : A →* B := -- ppi.mk f p -- @[hott] def pmap.to_fun [coercion] [unfold 3] {A B : Type*} (f : A →* B) : A → B := f /- pointed homotopies -/ @[hott] def phomotopy {P : A → Type _} {p₀ : P pt} (f g : ppi P p₀) : Type _ := ppi (λa, f a = g a) (respect_pt f ⬝ (respect_pt g)⁻¹) -- structure phomotopy {A B : Type*} (f g : A →* B) : Type _ := -- (homotopy : f ~ g) -- (homotopy_pt : homotopy pt ⬝ respect_pt g = respect_pt f) variables {P : A → Type _} {p₀ : P pt} {f g : ppi P p₀} infix ` ~* `:50 := phomotopy @[hott] def phomotopy.mk (h : f ~ g) (p : h pt ⬝ respect_pt g = respect_pt f) : f ~* g := ppi.mk h (eq_con_inv_of_con_eq p) @[hott] protected def phomotopy.to_fun (h : f ~* g) : Π a : A, f a = g a := ppi.to_fun h @[hott] instance phomotopy.has_coe_to_fun: has_coe_to_fun (f ~* g) := { F := _, coe := phomotopy.to_fun, } @[hott] def to_homotopy (p : f ~* g) : Πa, f a = g a := p @[hott] def to_homotopy_pt (p : f ~* g) : p pt ⬝ respect_pt g = respect_pt f := con_eq_of_eq_con_inv (respect_pt p) end pointed end hott
ac001e3447da99f70978ddd6febdc636e175abaf
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/nat/parity.lean
a8f7ba5e7f2cc650a5599b834ea109cb5f8ab9bb
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
8,100
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 The `even` and `odd` predicates on the natural numbers. -/ import data.nat.modeq 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 [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [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 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 [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, h⟩ | ⟨k, h⟩; use k, { simpa only [xor, h, true_and, eq_self_iff_true, not_true, or_false, and_false] using (succ_ne_self (2*k)).symm }, { simp only [xor, h, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff, one_ne_zero, and_self] }, end lemma odd_gt_zero (h : odd n) : 0 < n := by { obtain ⟨k, hk⟩ := h, rw hk, exact succ_pos', } instance : decidable_pred (even : ℕ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm instance decidable_pred_odd : decidable_pred (odd : ℕ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) odd_iff_not_even.symm mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" @[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even 1 := by rw even_iff; apply one_ne_zero @[simp] theorem even_bit0 (n : ℕ) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) := begin 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₂], { exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂ end theorem even.add_even (hm : even m) (hn : even n) : even (m + n) := even_add.2 $ by simp only [*] 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] theorem odd.add_odd (hm : odd m) (hn : odd n) : even (m + n) := even_add'.2 $ by simp only [*] @[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 convert not_even_bit1 n; exact two_mul n 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 [←nat.sub_add_cancel h, even_add] }, by_cases h : even n; simp [h] end theorem even.sub_even (hm : even m) (hn : even n) : even (m - n) := (le_total n m).elim (λ h, by simp only [even_sub h, *]) (λ h, by simp only [sub_eq_zero_of_le h, even_zero]) 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 [sub_eq_zero_of_le h, even_zero]) @[parity_simps] theorem even_succ : even (succ n) ↔ ¬ even n := by rw [succ_eq_add_one, even_add]; simp [not_even_one] @[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n := begin 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₂], { exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂ end theorem odd_mul : odd (m * n) ↔ odd m ∧ odd n := by simp [not_or_distrib] with parity_simps theorem even.mul_left (hm : even m) (n) : even (m * n) := even_mul.mpr $ or.inl hm theorem even.mul_right (m) (hn : even n) : even (m * n) := even_mul.mpr $ or.inr hn theorem odd.mul (hm : odd m) (hn : odd n) : odd (m * n) := odd_mul.mpr ⟨hm, hn⟩ 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_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) := begin by_contra hnot, rw [not_iff, ← even_iff_not_odd, even_add, odd_iff_not_even, ← not_iff] at hnot, exact (iff_not_self _).mp hnot, end theorem odd.add_even (hm : odd m) (hn : even n) : odd (m + n) := odd_add.2 $ by simp only [*] theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) := by rw [add_comm, odd_add] theorem even.add_odd (hm : even m) (hn : odd n) : odd (m + n) := odd_add'.2 $ by simp only [*] @[parity_simps] theorem odd_sub (h : n ≤ m) : odd (m - n) ↔ (odd m ↔ even n) := begin by_contra hnot, rw [not_iff, ← even_iff_not_odd, even_sub h, odd_iff_not_even, ← not_iff] at hnot, exact (iff_not_self _).mp hnot, end 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) := begin by_contra hnot, rw [not_iff, ← even_iff_not_odd, even_sub h, odd_iff_not_even, ← not_iff, @iff.comm _ (even n)] at hnot, exact (iff_not_self _).mp hnot, end 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 variables {R : Type*} [ring R] theorem neg_one_pow_eq_one_iff_even (h1 : (-1 : R) ≠ 1) : (-1 : R) ^ n = 1 ↔ even n := ⟨λ h, n.mod_two_eq_zero_or_one.elim (dvd_iff_mod_eq_zero _ _).2 (λ hn, by rw [neg_one_pow_eq_pow_mod_two, hn, pow_one] at h; exact (h1 h).elim), λ ⟨m, hm⟩, by rw [neg_one_pow_eq_pow_mod_two, hm]; simp⟩ @[simp] theorem neg_one_pow_two : (-1 : R) ^ 2 = 1 := by simp theorem neg_one_pow_of_even : even n → (-1 : R) ^ n = 1 := by { rintro ⟨c, rfl⟩, simp [pow_mul] } theorem neg_one_pow_of_odd : odd n → (-1 : R) ^ n = -1 := by { rintro ⟨c, rfl⟩, simp [pow_add, pow_mul] } -- 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
7b7f486071bf61df3d23b6f3f681afd6113ff326
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/dvec.lean
bb6f536c6e608af2a136753573615c28e2e0d728
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
2,717
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Dependently-typed vectors. These are necessary to store multiple tensors of arbitrary shapes. -/ import .util inductive dvec {X : Type} (Y : X → Type) : list X → Type | nil {} : dvec [] | cons : Π {x : X}, Y x → Π {xs : list X}, dvec xs → dvec (x::xs) namespace dvec reserve infixr ` ::: `:67 notation h `:::` t := cons h t notation `⟦` l:(foldr `, ` (h t, cons h t) nil `⟧`) := l def head {X : Type} {Y : X → Type} {x : X} {xs : list X} : dvec Y (x::xs) → Y x | (cons y ys) := y def tail {X : Type} {Y : X → Type} {x : X} {xs : list X} : dvec Y (x::xs) → dvec Y xs | (cons y ys) := ys def head2 {X : Type} {Y : X → Type} {x₁ x₂ : X} {xs : list X} : dvec Y (x₁::x₂::xs) → Y x₂ | (cons y₁ (cons y₂ ys)) := y₂ def head3 {X : Type} {Y : X → Type} {x₁ x₂ x₃ : X} {xs : list X} : dvec Y (x₁::x₂::x₃::xs) → Y x₃ | (cons y₁ (cons y₂ (cons y₃ ys))) := y₃ def get {X : Type} [decidable_eq X] {Y : X → Type} (x₀ : X) [inhabited (Y x₀)] : Π {xs : list X}, dvec Y xs → ℕ → Y x₀ | [] _ _ := default (Y x₀) | (x::xs) (cons y ys) 0 := if H : x = x₀ then eq.rec_on H y else default (Y x₀) | (x::xs) (cons y ys) (n+1) := get ys n lemma singleton_congr {X : Type} {Y : X → Type} {x : X} (y₁ y₂ : Y x) : y₁ = y₂ → ⟦y₁⟧ = ⟦y₂⟧ := assume H, by rw H lemma get₀_head {X : Type} [decidable_eq X] {Y : X → Type} (x₀ : X) [inhabited (Y x₀)] : ∀ {xs : list X} (ys : dvec Y (x₀::xs)), get x₀ ys 0 = head ys | xs (y:::ys) := begin dunfold head get, simp [dif_ctx_simp_congr, dif_pos] end def update_at {X : Type} [decidable_eq X] {Y : X → Type} {x₀ : X} (y₀ : Y x₀) : Π {xs : list X} (ys : dvec Y xs) (idx : ℕ), dvec Y xs | [] _ _ := ⟦⟧ | (x::xs) (cons y ys) 0 := if H : x₀ = x then cons (eq.rec_on H y₀) ys else cons y ys | (x::xs) (cons y ys) (n+1) := cons y (update_at ys n) protected def to_string_aux {X : Type} {Y : X → Type} [∀ x, has_to_string (Y x)] : Π {xs : list X}, dvec Y xs → string | [] _ := "-------------" | (x::xs) (cons y ys) := to_string y ++ "\n" ++ to_string_aux ys protected def to_string {X : Type} {Y : X → Type} [∀ x, has_to_string (Y x)] {xs : list X} (ys : dvec Y xs) : string := "-------------\n" ++ dvec.to_string_aux ys instance {X : Type} {Y : X → Type} [∀ x, has_to_string (Y x)] {xs : list X} : has_to_string (dvec Y xs) := ⟨dvec.to_string⟩ attribute [simp] head tail head2 head3 get update_at end dvec
c4b0f5d4a6edf3cbdf58ad3727030ae34367e140
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/order/lattice.lean
a8880feb4642c9145ad74ad4b309fdc363f53451
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,663
lean
/- Copyright (c) 2021 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import topology.algebra.order.basic import topology.constructions /-! # Topological lattices In this file we define mixin classes `has_continuous_inf` and `has_continuous_sup`. We define the class `topological_lattice` as a topological space and lattice `L` extending `has_continuous_inf` and `has_continuous_sup`. ## References * [Gierz et al, A Compendium of Continuous Lattices][GierzEtAl1980] ## Tags topological, lattice -/ open filter open_locale topological_space /-- Let `L` be a topological space and let `L×L` be equipped with the product topology and let `⊓:L×L → L` be an infimum. Then `L` is said to have *(jointly) continuous infimum* if the map `⊓:L×L → L` is continuous. -/ class has_continuous_inf (L : Type*) [topological_space L] [has_inf L] : Prop := (continuous_inf : continuous (λ p : L × L, p.1 ⊓ p.2)) /-- Let `L` be a topological space and let `L×L` be equipped with the product topology and let `⊓:L×L → L` be a supremum. Then `L` is said to have *(jointly) continuous supremum* if the map `⊓:L×L → L` is continuous. -/ class has_continuous_sup (L : Type*) [topological_space L] [has_sup L] : Prop := (continuous_sup : continuous (λ p : L × L, p.1 ⊔ p.2)) @[priority 100] -- see Note [lower instance priority] instance order_dual.has_continuous_sup (L : Type*) [topological_space L] [has_inf L] [has_continuous_inf L] : has_continuous_sup Lᵒᵈ := { continuous_sup := @has_continuous_inf.continuous_inf L _ _ _ } @[priority 100] -- see Note [lower instance priority] instance order_dual.has_continuous_inf (L : Type*) [topological_space L] [has_sup L] [has_continuous_sup L] : has_continuous_inf Lᵒᵈ := { continuous_inf := @has_continuous_sup.continuous_sup L _ _ _ } /-- Let `L` be a lattice equipped with a topology such that `L` has continuous infimum and supremum. Then `L` is said to be a *topological lattice*. -/ class topological_lattice (L : Type*) [topological_space L] [lattice L] extends has_continuous_inf L, has_continuous_sup L @[priority 100] -- see Note [lower instance priority] instance order_dual.topological_lattice (L : Type*) [topological_space L] [lattice L] [topological_lattice L] : topological_lattice Lᵒᵈ := {} @[priority 100] -- see Note [lower instance priority] instance linear_order.topological_lattice {L : Type*} [topological_space L] [linear_order L] [order_closed_topology L] : topological_lattice L := { continuous_inf := continuous_min, continuous_sup := continuous_max } variables {L : Type*} [topological_space L] variables {X : Type*} [topological_space X] @[continuity] lemma continuous_inf [has_inf L] [has_continuous_inf L] : continuous (λp:L×L, p.1 ⊓ p.2) := has_continuous_inf.continuous_inf @[continuity] lemma continuous.inf [has_inf L] [has_continuous_inf L] {f g : X → L} (hf : continuous f) (hg : continuous g) : continuous (λx, f x ⊓ g x) := continuous_inf.comp (hf.prod_mk hg : _) @[continuity] lemma continuous_sup [has_sup L] [has_continuous_sup L] : continuous (λp:L×L, p.1 ⊔ p.2) := has_continuous_sup.continuous_sup @[continuity] lemma continuous.sup [has_sup L] [has_continuous_sup L] {f g : X → L} (hf : continuous f) (hg : continuous g) : continuous (λx, f x ⊔ g x) := continuous_sup.comp (hf.prod_mk hg : _) lemma filter.tendsto.sup_right_nhds' {ι β} [topological_space β] [has_sup β] [has_continuous_sup β] {l : filter ι} {f g : ι → β} {x y : β} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (f ⊔ g) l (𝓝 (x ⊔ y)) := (continuous_sup.tendsto _).comp (tendsto.prod_mk_nhds hf hg) lemma filter.tendsto.sup_right_nhds {ι β} [topological_space β] [has_sup β] [has_continuous_sup β] {l : filter ι} {f g : ι → β} {x y : β} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ i, f i ⊔ g i) l (𝓝 (x ⊔ y)) := hf.sup_right_nhds' hg lemma filter.tendsto.inf_right_nhds' {ι β} [topological_space β] [has_inf β] [has_continuous_inf β] {l : filter ι} {f g : ι → β} {x y : β} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (f ⊓ g) l (𝓝 (x ⊓ y)) := (continuous_inf.tendsto _).comp (tendsto.prod_mk_nhds hf hg) lemma filter.tendsto.inf_right_nhds {ι β} [topological_space β] [has_inf β] [has_continuous_inf β] {l : filter ι} {f g : ι → β} {x y : β} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ i, f i ⊓ g i) l (𝓝 (x ⊓ y)) := hf.inf_right_nhds' hg
c406023d2c94ea0f7e7aa5d965d68cf17f5968a1
137c667471a40116a7afd7261f030b30180468c2
/src/data/equiv/basic.lean
d7b87f4fa4dfe5146f9fe9e7fdcd1140ad3d0b8a
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
101,594
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import data.set.function import data.sigma.basic /-! # Equivalence between types In this file we define two types: * `equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and not equality!) to express that various `Type`s or `Sort`s are equivalent. * `equiv.perm α`: the group of permutations `α ≃ α`. More lemmas about `equiv.perm` can be found in `group_theory/perm`. Then we define * canonical isomorphisms between various types: e.g., - `equiv.refl α` is the identity map interpreted as `α ≃ α`; - `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β` and the sigma-type `Σ b : bool, cond b α β`; - `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum satisfy the distributive law up to a canonical equivalence; * operations on equivalences: e.g., - `equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`; - `equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order of the arguments!); - `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and `eb : β₁ ≃ β₂` using `prod.map`. * definitions that transfer some instances along an equivalence. By convention, we transfer instances from right to left. - `equiv.inhabited` takes `e : α ≃ β` and `[inhabited β]` and returns `inhabited α`; - `equiv.unique` takes `e : α ≃ β` and `[unique β]` and returns `unique α`; - `equiv.decidable_eq` takes `e : α ≃ β` and `[decidable_eq β]` and returns `decidable_eq α`. More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance` does it for many algebraic type classes like `group`, `module`, etc. ## Tags equivalence, congruence, bijective map -/ open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ @[nolint has_inhabited_instance] structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) infix ` ≃ `:25 := equiv /-- Convert an involutive function `f` to an equivalence with `to_fun = inv_fun = f`. -/ def function.involutive.to_equiv (f : α → α) (h : involutive f) : α ≃ α := ⟨f, f, h.left_inverse, h.right_inverse⟩ namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl /-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/ theorem coe_fn_injective : function.injective (λ (e : α ≃ β) (x : α), e x) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from l₁.eq_right_inverse (this.symm ▸ r₂), by simp * @[simp, norm_cast] protected lemma coe_inj {e₁ e₂ : α ≃ β} : ⇑e₁ = e₂ ↔ e₁ = e₂ := coe_fn_injective.eq_iff @[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g := coe_fn_injective (funext H) protected lemma congr_arg {f : equiv α β} : Π {x x' : α}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : equiv α β} (h : f = g) (x : α) : f x = g x := h ▸ rfl lemma ext_iff {f g : equiv α β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ @[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext H protected lemma perm.congr_arg {f : equiv.perm α} {x x' : α} : x = x' → f x = f x' := equiv.congr_arg protected lemma perm.congr_fun {f g : equiv.perm α} (h : f = g) (x : α) : f x = g x := equiv.congr_fun h x lemma perm.ext_iff {σ τ : equiv.perm α} : σ = τ ↔ ∀ x, σ x = τ x := ext_iff /-- Any type is equivalent to itself. -/ @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ instance inhabited' : inhabited (α ≃ α) := ⟨equiv.refl α⟩ /-- Inverse of an equivalence `e : α ≃ β`. -/ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) -- Generate the `simps` projections for previously defined equivs. attribute [simps] function.involutive.to_equiv /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ @[simp] lemma to_fun_as_coe (e : α ≃ β) : e.to_fun = e := rfl @[simp] lemma inv_fun_as_coe (e : α ≃ β) : e.inv_fun = e.symm := rfl protected theorem injective (e : α ≃ β) : injective e := e.left_inv.injective protected theorem surjective (e : α ≃ β) : surjective e := e.right_inv.surjective protected theorem bijective (f : α ≃ β) : bijective f := ⟨f.injective, f.surjective⟩ @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ := set.eq_univ_of_forall e.surjective protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α := e.injective.subsingleton protected theorem subsingleton.symm (e : α ≃ β) [subsingleton α] : subsingleton β := e.symm.injective.subsingleton lemma subsingleton_congr (e : α ≃ β) : subsingleton α ↔ subsingleton β := ⟨λ h, by exactI e.symm.subsingleton, λ h, by exactI e.subsingleton⟩ instance equiv_subsingleton_cod [subsingleton β] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, subsingleton.elim _ _⟩ instance equiv_subsingleton_dom [subsingleton α] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, @subsingleton.elim _ (equiv.subsingleton.symm f) _ _⟩ instance perm_subsingleton [subsingleton α] : subsingleton (perm α) := equiv.equiv_subsingleton_cod lemma perm.subsingleton_eq_refl [subsingleton α] (e : perm α) : e = equiv.refl α := subsingleton.elim _ _ /-- Transfer `decidable_eq` across an equivalence. -/ protected def decidable_eq (e : α ≃ β) [decidable_eq β] : decidable_eq α := e.injective.decidable_eq lemma nonempty_iff_nonempty (e : α ≃ β) : nonempty α ↔ nonempty β := nonempty.congr e e.symm /-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/ protected def inhabited [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ /-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/ protected def unique [unique β] (e : α ≃ β) : unique α := e.symm.surjective.unique /-- Equivalence between equal types. -/ protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl @[simp] theorem perm.coe_subsingleton {α : Type*} [subsingleton α] (e : perm α) : ⇑(e) = id := by rw [perm.subsingleton_eq_refl e, coe_refl] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x := e.right_inv x @[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl -- The `simp` attribute is needed to make this a `dsimp` lemma. -- `simp` will always rewrite with `equiv.symm_symm` before this has a chance to fire. @[simp, nolint simp_nf] theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl @[simp] theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y := f.injective.eq_iff theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) {x : α} {y : β} : f x = y ↔ x = f.symm y := begin conv_lhs { rw ←apply_symm_apply f y, }, rw apply_eq_iff_eq, end @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl @[simp] theorem cast_symm {α β} (h : α = β) : (equiv.cast h).symm = equiv.cast h.symm := rfl @[simp] theorem cast_refl {α} (h : α = α := rfl) : equiv.cast h = equiv.refl α := rfl @[simp] theorem cast_trans {α β γ} (h : α = β) (h2 : β = γ) : (equiv.cast h).trans (equiv.cast h2) = equiv.cast (h.trans h2) := ext $ λ x, by { substs h h2, refl } lemma cast_eq_iff_heq {α β} (h : α = β) {a : α} {b : β} : equiv.cast h a = b ↔ a == b := by { subst h, simp } lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl } @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl } @[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl } @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv @[simp] lemma injective_comp (e : α ≃ β) (f : β → γ) : injective (f ∘ e) ↔ injective f := injective.of_comp_iff' f e.bijective @[simp] lemma comp_injective (f : α → β) (e : β ≃ γ) : injective (e ∘ f) ↔ injective f := e.injective.of_comp_iff f @[simp] lemma surjective_comp (e : α ≃ β) (f : β → γ) : surjective (f ∘ e) ↔ surjective f := e.surjective.of_comp_iff f @[simp] lemma comp_surjective (f : α → β) (e : β ≃ γ) : surjective (e ∘ f) ↔ surjective f := surjective.of_comp_iff' e.bijective f @[simp] lemma bijective_comp (e : α ≃ β) (f : β → γ) : bijective (f ∘ e) ↔ bijective f := e.bijective.of_comp_iff f @[simp] lemma comp_bijective (f : α → β) (e : β ≃ γ) : bijective (e ∘ f) ↔ bijective f := bijective.of_comp_iff' e.bijective f /-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ` is equivalent to the type of equivalences `β ≃ δ`. -/ def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩ @[simp] lemma equiv_congr_refl {α β} : (equiv.refl α).equiv_congr (equiv.refl β) = equiv.refl (α ≃ β) := by { ext, refl } @[simp] lemma equiv_congr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (ab.equiv_congr cd).symm = ab.symm.equiv_congr cd.symm := by { ext, refl } @[simp] lemma equiv_congr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) : (ab.equiv_congr de).trans (bc.equiv_congr ef) = (ab.trans bc).equiv_congr (de.trans ef) := by { ext, refl } @[simp] lemma equiv_congr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) : (equiv.refl α).equiv_congr bg e = e.trans bg := rfl @[simp] lemma equiv_congr_refl_right {α β} (ab e : α ≃ β) : ab.equiv_congr (equiv.refl β) e = ab.symm.trans e := rfl @[simp] lemma equiv_congr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) : ab.equiv_congr cd e x = cd (e (ab.symm x)) := rfl section perm_congr variables {α' β' : Type*} (e : α' ≃ β') /-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/ def perm_congr : perm α' ≃ perm β' := equiv_congr e e lemma perm_congr_def (p : equiv.perm α') : e.perm_congr p = (e.symm.trans p).trans e := rfl @[simp] lemma perm_congr_refl : e.perm_congr (equiv.refl _) = equiv.refl _ := by simp [perm_congr_def] @[simp] lemma perm_congr_symm : e.perm_congr.symm = e.symm.perm_congr := rfl @[simp] lemma perm_congr_apply (p : equiv.perm α') (x) : e.perm_congr p x = e (p (e.symm x)) := rfl lemma perm_congr_symm_apply (p : equiv.perm β') (x) : e.perm_congr.symm p x = e.symm (p (e x)) := rfl lemma perm_congr_trans (p p' : equiv.perm α') : (e.perm_congr p).trans (e.perm_congr p') = e.perm_congr (p.trans p') := by { ext, simp } end perm_congr protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] @[simp] lemma symm_image_image {α β} (e : α ≃ β) (s : set α) : e.symm '' (e '' s) = s := by { rw [← set.image_comp], simp } lemma eq_image_iff_symm_image_eq {α β} (e : α ≃ β) (s : set α) (t : set β) : t = e '' s ↔ e.symm '' t = s := begin refine (injective.eq_iff' _ _).symm, { rw set.image_injective, exact (equiv.symm e).injective }, { exact equiv.symm_image_image _ _ } end @[simp] lemma image_symm_image {α β} (e : α ≃ β) (s : set β) : e '' (e.symm '' s) = s := e.symm.symm_image_image s @[simp] lemma image_preimage {α β} (e : α ≃ β) (s : set β) : e '' (e ⁻¹' s) = s := e.surjective.image_preimage s @[simp] lemma preimage_image {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e '' s) = s := set.preimage_image_eq s e.injective protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' sᶜ = (f '' s)ᶜ := set.image_compl_eq f.bijective @[simp] lemma symm_preimage_preimage {α β} (e : α ≃ β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s := by ext; simp @[simp] lemma preimage_symm_preimage {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e.symm ⁻¹' s) = s := by ext; simp @[simp] lemma preimage_subset {α β} (e : α ≃ β) (s t : set β) : e ⁻¹' s ⊆ e ⁻¹' t ↔ s ⊆ t := e.surjective.preimage_subset_preimage_iff @[simp] lemma image_subset {α β} (e : α ≃ β) (s t : set α) : e '' s ⊆ e '' t ↔ s ⊆ t := set.image_subset_image_iff e.injective @[simp] lemma image_eq_iff_eq {α β} (e : α ≃ β) (s t : set α) : e '' s = e '' t ↔ s = t := set.image_eq_image e.injective lemma preimage_eq_iff_eq_image {α β} (e : α ≃ β) (s t) : e ⁻¹' s = t ↔ s = e '' t := set.preimage_eq_iff_eq_image e.bijective lemma eq_preimage_iff_image_eq {α β} (e : α ≃ β) (s t) : s = e ⁻¹' t ↔ e '' s = t := set.eq_preimage_iff_image_eq e.bijective /-- If `α` is an empty type, then it is equivalent to the `empty` type. -/ def equiv_empty (α : Sort u) [is_empty α] : α ≃ empty := ⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩ /-- `α` is equivalent to an empty type iff `α` is empty. -/ def equiv_empty_equiv (α : Sort u) : (α ≃ empty) ≃ is_empty α := ⟨λ e, function.is_empty e, @equiv_empty α, λ e, ext $ λ x, (e x).elim, λ p, rfl⟩ /-- `false` is equivalent to `empty`. -/ def false_equiv_empty : false ≃ empty := equiv_empty _ /-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/ def {u' v'} equiv_pempty (α : Sort v') [is_empty α] : α ≃ pempty.{u'} := ⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩ /-- `false` is equivalent to `pempty`. -/ def false_equiv_pempty : false ≃ pempty := equiv_pempty _ /-- `empty` is equivalent to `pempty`. -/ def empty_equiv_pempty : empty ≃ pempty := equiv_pempty _ /-- `pempty` types from any two universes are equivalent. -/ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty _ /-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ /-- `true` is equivalent to `punit`. -/ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial /-- `ulift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def ulift {α : Type v} : ulift.{u} α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ /-- `plift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ /-- equivalence of propositions is the same as iff -/ def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q := { to_fun := h.mp, inv_fun := h.mpr, left_inv := λ x, rfl, right_inv := λ y, rfl } /-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁` is equivalent to the type of maps `α₂ → β₂`. -/ @[congr, simps apply] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := { to_fun := λ f, e₂ ∘ f ∘ e₁.symm, inv_fun := λ f, e₂.symm ∘ f ∘ e₁, left_inv := λ f, funext $ λ x, by simp, right_inv := λ f, funext $ λ x, by simp } lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) := by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] } @[simp] lemma arrow_congr_refl {α β : Sort*} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := rfl @[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := rfl /-- A version of `equiv.arrow_congr` in `Type`, rather than `Sort`. The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`, because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`. -/ @[congr, simps apply] def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := equiv.arrow_congr hα hβ @[simp] lemma arrow_congr'_refl {α β : Type*} : arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') := rfl @[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm := rfl /-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/ @[simps apply] def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e @[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl @[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl -- This should not be a simp lemma as long as `(∘)` is reducible: -- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using -- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination. lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) := by apply arrow_congr_comp section binary_op variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp instance [is_associative α₁ f] : is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_associative_right e.surjective instance [is_idempotent α₁ f] : is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_idempotent_right e.surjective instance [is_left_cancel α₁ f] : is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩ instance [is_right_cancel α₁ f] : is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩ end binary_op /-- `punit` sorts in any two universes are equivalent. -/ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩ section /-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/ def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩ /-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/ @[simps] def fun_unique (α β) [unique α] : (α → β) ≃ β := { to_fun := λ f, f (default α), inv_fun := λ b a, b, left_inv := λ f, funext $ λ a, congr_arg f $ subsingleton.elim _ _, right_inv := λ b, rfl } /-- The sort of maps from `punit` is equivalent to the codomain. -/ def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := fun_unique _ _ /-- The sort of maps from `true` is equivalent to the codomain. -/ def true_arrow_equiv (α : Sort*) : (true → α) ≃ α := fun_unique _ _ /-- The sort of maps from a type that `is_empty` is equivalent to `punit`. -/ def arrow_punit_of_is_empty (α β : Sort*) [is_empty α] : (α → β) ≃ punit.{u} := ⟨λ f, punit.star, λ u, is_empty_elim, λ f, funext is_empty_elim, λ u, by { cases u, refl }⟩ /-- The sort of maps from `empty` is equivalent to `punit`. -/ def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ /-- The sort of maps from `pempty` is equivalent to `punit`. -/ def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ /-- The sort of maps from `false` is equivalent to `punit`. -/ def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ end /-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/ @[congr, simps apply] def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩ @[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm := rfl /-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/ @[simps apply] def prod_comm (α β : Type*) : α × β ≃ β × α := ⟨prod.swap, prod.swap, λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl /-- Type product is associative up to an equivalence. -/ @[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, (p.1.1, p.1.2, p.2), λp, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} : equiv.prod_assoc α β γ ⁻¹' s.prod (t.prod u) = (s.prod t).prod u := by { ext, simp [and_assoc] } /-- Functions on `α × β` are equivalent to functions `α → β → γ`. -/ @[simps {fully_applied := ff}] def curry (α β γ : Type*) : (α × β → γ) ≃ (α → β → γ) := { to_fun := curry, inv_fun := uncurry, left_inv := uncurry_curry, right_inv := curry_uncurry } section /-- `punit` is a right identity for type product up to an equivalence. -/ @[simps] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ /-- `punit` is a left identity for type product up to an equivalence. -/ @[simps] def punit_prod (α : Type*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ /-- `empty` type is a right absorbing element for type product up to an equivalence. -/ def prod_empty (α : Type*) : α × empty ≃ empty := equiv_empty _ /-- `empty` type is a left absorbing element for type product up to an equivalence. -/ def empty_prod (α : Type*) : empty × α ≃ empty := equiv_empty _ /-- `pempty` type is a right absorbing element for type product up to an equivalence. -/ def prod_pempty (α : Type*) : α × pempty ≃ pempty := equiv_pempty _ /-- `pempty` type is a left absorbing element for type product up to an equivalence. -/ def pempty_prod (α : Type*) : pempty × α ≃ pempty := equiv_pempty _ end section open sum /-- `psum` is equivalent to `sum`. -/ def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/ @[simps apply] def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ := ⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩ @[simp] lemma sum_congr_trans {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} (e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) : (equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) := by { ext i, cases i; refl } @[simp] lemma sum_congr_symm {α β γ δ : Sort*} (e : α ≃ β) (f : γ ≃ δ) : (equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) := rfl @[simp] lemma sum_congr_refl {α β : Sort*} : equiv.sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := by { ext i, cases i; refl } namespace perm /-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/ @[reducible] def sum_congr {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) : equiv.perm (α ⊕ β) := equiv.sum_congr ea eb @[simp] lemma sum_congr_apply {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) (x : α ⊕ β) : sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x @[simp] lemma sum_congr_trans {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) (g : equiv.perm α) (h : equiv.perm β) : (sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) := equiv.sum_congr_trans e f g h @[simp] lemma sum_congr_symm {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) : (sum_congr e f).symm = sum_congr (e.symm) (f.symm) := equiv.sum_congr_symm e f @[simp] lemma sum_congr_refl {α β : Sort*} : sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := equiv.sum_congr_refl end perm /-- `bool` is equivalent the sum of two `punit`s. -/ def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ /-- `Prop` is noncomputably equivalent to `bool`. -/ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ /-- Sum of types is commutative up to an equivalence. -/ @[simps apply] def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α := ⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩ @[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl /-- Sum of types is associative up to an equivalence. -/ def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr), sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr, by rintros (⟨_ | _⟩ | _); refl, by rintros (_ | ⟨_ | _⟩); refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl /-- Sum with `empty` is equivalent to the original type. -/ @[simps symm_apply] def sum_empty (α β : Type*) [is_empty β] : α ⊕ β ≃ α := ⟨sum.elim id is_empty_elim, inl, λ s, by { rcases s with _ | x, refl, exact is_empty_elim x }, λ a, rfl⟩ @[simp] lemma sum_empty_apply_inl {α β : Type*} [is_empty β] (a : α) : sum_empty α β (sum.inl a) = a := rfl /-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/ @[simps symm_apply] def empty_sum (α β : Type*) [is_empty α] : α ⊕ β ≃ β := (sum_comm _ _).trans $ sum_empty _ _ @[simp] lemma empty_sum_apply_inr {α β : Type*} [is_empty α] (b : β) : empty_sum α β (sum.inr b) = b := rfl /-- `option α` is equivalent to `α ⊕ punit` -/ def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ @[simp] lemma option_equiv_sum_punit_none {α} : option_equiv_sum_punit α none = sum.inr punit.star := rfl @[simp] lemma option_equiv_sum_punit_some {α} (a) : option_equiv_sum_punit α (some a) = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_coe {α} (a : α) : option_equiv_sum_punit α a = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_symm_inl {α} (a) : (option_equiv_sum_punit α).symm (sum.inl a) = a := rfl @[simp] lemma option_equiv_sum_punit_symm_inr {α} (a) : (option_equiv_sum_punit α).symm (sum.inr a) = none := rfl /-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/ def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α := { to_fun := λ o, option.get o.2, inv_fun := λ x, ⟨some x, dec_trivial⟩, left_inv := λ o, subtype.eq $ option.some_get _, right_inv := λ x, option.get_some _ _ } /-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `α` and `β` to be types from the same universe, so it cannot by used directly to transfer theorems about sigma types to theorems about sum types. In many cases one can use `ulift` to work around this difficulty. -/ def sum_equiv_sigma_bool (α β : Type u) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, s.elim (λ x, ⟨tt, x⟩) (λ x, ⟨ff, x⟩), λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ /-- `sigma_preimage_equiv f` for `f : α → β` is the natural equivalence between the type of all fibres of `f` and the total space `α`. -/ @[simps] def sigma_preimage_equiv {α β : Type*} (f : α → β) : (Σ y : β, {x // f x = y}) ≃ α := ⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩ /-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/ def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) : s ≃ Σ x : α, {y | (x, y) ∈ s} := { to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩, inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩, left_inv := λ ⟨⟨x, y⟩, h⟩, rfl, right_inv := λ ⟨x, y, h⟩, rfl } end section sum_compl /-- For any predicate `p` on `α`, the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}` is naturally equivalent to `α`. -/ def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] : {a // p a} ⊕ {a // ¬ p a} ≃ α := { to_fun := sum.elim coe coe, inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩, left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], }, right_inv := λ a, by { dsimp, split_ifs; refl } } @[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // p a}) : sum_compl p (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // ¬ p a}) : sum_compl p (sum.inr x) = x := rfl @[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : p a) : (sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h @[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : ¬ p a) : (sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h /-- Combines an `equiv` between two subtypes with an `equiv` between their complements to form a permutation. -/ def subtype_congr {α : Type*} {p q : α → Prop} [decidable_pred p] [decidable_pred q] (e : {x // p x} ≃ {x // q x}) (f : {x // ¬p x} ≃ {x // ¬q x}) : perm α := (sum_compl p).symm.trans ((sum_congr e f).trans (sum_compl q)) open equiv variables {ε : Type*} {p : ε → Prop} [decidable_pred p] variables (ep ep' : perm {a // p a}) (en en' : perm {a // ¬ p a}) /-- Combining permutations on `ε` that permute only inside or outside the subtype split induced by `p : ε → Prop` constructs a permutation on `ε`. -/ def perm.subtype_congr : equiv.perm ε := perm_congr (sum_compl p) (sum_congr ep en) lemma perm.subtype_congr.apply (a : ε) : ep.subtype_congr en a = if h : p a then ep ⟨a, h⟩ else en ⟨a, h⟩ := by { by_cases h : p a; simp [perm.subtype_congr, h] } @[simp] lemma perm.subtype_congr.left_apply {a : ε} (h : p a) : ep.subtype_congr en a = ep ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.left_apply_subtype (a : {a // p a}) : ep.subtype_congr en a = ep a := by { convert perm.subtype_congr.left_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.right_apply {a : ε} (h : ¬ p a) : ep.subtype_congr en a = en ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.right_apply_subtype (a : {a // ¬ p a}) : ep.subtype_congr en a = en a := by { convert perm.subtype_congr.right_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.refl : perm.subtype_congr (equiv.refl {a // p a}) (equiv.refl {a // ¬ p a}) = equiv.refl ε := by { ext x, by_cases h : p x; simp [h] } @[simp] lemma perm.subtype_congr.symm : (ep.subtype_congr en).symm = perm.subtype_congr ep.symm en.symm := begin ext x, by_cases h : p x, { have : p (ep.symm ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }, { have : ¬ p (en.symm ⟨x, h⟩) := subtype.property (en.symm _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end @[simp] lemma perm.subtype_congr.trans : (ep.subtype_congr en).trans (ep'.subtype_congr en') = perm.subtype_congr (ep.trans ep') (en.trans en') := begin ext x, by_cases h : p x, { have : p (ep ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, this] }, { have : ¬ p (en ⟨x, h⟩) := subtype.property (en _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end end sum_compl section subtype_preimage variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β) /-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`, the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/ @[simps] def subtype_preimage : {x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) := { to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a, inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩, funext $ λ ⟨a, h⟩, dif_pos h⟩, left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a, (by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }), right_inv := λ x, funext $ λ ⟨a, h⟩, show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } } lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) : ((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ := dif_pos h lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) : ((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ := dif_neg h end subtype_preimage section /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ /-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent to the type of dependent functions of two arguments (i.e., functions to the space of functions). This is `sigma.curry` and `sigma.uncurry` together as an equiv. -/ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := sigma.curry, inv_fun := sigma.uncurry, left_inv := sigma.uncurry_curry, right_inv := sigma.curry_uncurry } end section /-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/ @[simps apply symm_apply] def psigma_equiv_sigma {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i, β i := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and `Σ a, β₂ a`. -/ @[simps apply] def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a := ⟨λ a, ⟨a.1, F a.1 a.2⟩, λ a, ⟨a.1, (F a.1).symm a.2⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ @[simp] lemma sigma_congr_right_trans {α} {β₁ β₂ β₃ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) (G : Π a, β₂ a ≃ β₃ a) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_symm {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := by { ext1 x, cases x, refl } namespace perm /-- A family of permutations `Π a, perm (β a)` generates a permuation `perm (Σ a, β₁ a)`. -/ @[reducible] def sigma_congr_right {α} {β : α → Sort*} (F : Π a, perm (β a)) : perm (Σ a, β a) := equiv.sigma_congr_right F @[simp] lemma sigma_congr_right_trans {α} {β : α → Sort*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := equiv.sigma_congr_right_trans F G @[simp] lemma sigma_congr_right_symm {α} {β : α → Sort*} (F : Π a, perm (β a)) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := equiv.sigma_congr_right_symm F @[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := equiv.sigma_congr_right_refl end perm /-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/ @[simps apply] def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} (e : α₁ ≃ α₂) : (Σ a:α₁, β (e a)) ≃ (Σ a:α₂, β a) := ⟨λ a, ⟨e a.1, a.2⟩, λ a, ⟨e.symm a.1, @@eq.rec β a.2 (e.right_inv a.1).symm⟩, λ ⟨a, b⟩, match e.symm (e a), e.left_inv a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ e) _ (@@eq.rec β b (congr_arg e h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match e (e.symm a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ /-- Transporting a sigma type through an equivalence of the base -/ def sigma_congr_left' {α₁ α₂} {β : α₁ → Sort*} (f : α₁ ≃ α₂) : (Σ a:α₁, β a) ≃ (Σ a:α₂, β (f.symm a)) := (sigma_congr_left f.symm).symm /-- Transporting a sigma type through an equivalence of the base and a family of equivalences of matching fibers -/ def sigma_congr {α₁ α₂} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} (f : α₁ ≃ α₂) (F : ∀ a, β₁ a ≃ β₂ (f a)) : sigma β₁ ≃ sigma β₂ := (sigma_congr_right F).trans (sigma_congr_left f) /-- `sigma` type with a constant fiber is equivalent to the product. -/ @[simps apply symm_apply] def sigma_equiv_prod (α β : Type*) : (Σ_:α, β) ≃ α × β := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type is equivalent to the product. -/ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : Π a, β₁ a ≃ β) : sigma β₁ ≃ α × β := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section prod_congr variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂) /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `β₁ × α₁` and `β₂ × α₁`. -/ def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ := { to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩, inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) : prod_congr_left e (b, a) = (e a b, a) := rfl lemma prod_congr_refl_right (e : β₁ ≃ β₂) : prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `α₁ × β₁` and `α₁ × β₂`. -/ def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ := { to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩, inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) : prod_congr_right e (a, b) = (a, e a b) := rfl lemma prod_congr_refl_left (e : β₁ ≃ β₂) : prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_left_trans_prod_comm : (prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_right_trans_prod_comm : (prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_congr_right_sigma_equiv_prod : (sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) = (sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_equiv_prod_sigma_congr_right : (sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) = (prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm := by { ext ⟨a, b⟩ : 1, simp } /-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend on the first component. A typical example is a shear mapping, explaining the name of this declaration. -/ @[simps {fully_applied := ff}] def prod_shear {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := { to_fun := λ x : α₁ × β₁, (e₁ x.1, e₂ x.1 x.2), inv_fun := λ y : α₂ × β₂, (e₁.symm y.1, (e₂ $ e₁.symm y.1).symm y.2), left_inv := by { rintro ⟨x₁, y₁⟩, simp only [symm_apply_apply] }, right_inv := by { rintro ⟨x₁, y₁⟩, simp only [apply_symm_apply] } } end prod_congr namespace perm variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁) /-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to `(a, e b)` and keeping the other `(a', b)` fixed. -/ def prod_extend_right : perm (α₁ × β₁) := { to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab, inv_fun := λ ab, if ab.fst = a then (a, e.symm ab.snd) else ab, left_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] }, right_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] } } @[simp] lemma prod_extend_right_apply_eq (b : β₁) : prod_extend_right a e (a, b) = (a, e b) := if_pos rfl lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) : prod_extend_right a e (a', b) = (a', b) := if_neg h lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁} (h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a := by { contrapose! h, exact prod_extend_right_apply_ne _ h _ } @[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) : (prod_extend_right a e ab).fst = ab.fst := begin rw [prod_extend_right, coe_fn_mk], split_ifs with h, { rw h }, { refl } end end perm section /-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions `γ → α` and `γ → β`. -/ def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ open sum /-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions on `α` and on `β`. -/ def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p, sum.elim p.1 p.2, λ f, by { ext ⟨⟩; refl }, λ p, by { cases p, refl }⟩ @[simp] lemma sum_arrow_equiv_prod_arrow_apply_fst {α β γ} (f : (α ⊕ β) → γ) (a : α) : (sum_arrow_equiv_prod_arrow α β γ f).1 a = f (inl a) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_apply_snd {α β γ} (f : (α ⊕ β) → γ) (b : β) : (sum_arrow_equiv_prod_arrow α β γ f).2 b = f (inr b) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inl {α β γ} (f : α → γ) (g : β → γ) (a : α) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inl a) = f a := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inr {α β γ} (f : α → γ) (g : β → γ) (b : β) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inr b) = g b := rfl /-- Type product is right distributive with respect to type sum up to an equivalence. -/ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl q := (inl q.1, q.2) | inr q := (inr q.1, q.2) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl /-- Type product is left distributive with respect to type sum up to an equivalence. -/ def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl /-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is equivalent to the sum of products `Σ i, (α i × β)`. -/ def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) : ((Σ i, α i) × β) ≃ (Σ i, (α i × β)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, λ p, (⟨p.1, p.2.1⟩, p.2.2), λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ /-- The product `bool × α` is equivalent to `α ⊕ α`. -/ def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (unit × α) ⊕ (unit × α) : sum_prod_distrib _ _ _ ... ≃ α ⊕ α : sum_congr (punit_prod _) (punit_prod _) /-- The function type `bool → α` is equivalent to `α × α`. -/ def bool_to_equiv_prod (α : Type u) : (bool → α) ≃ α × α := calc (bool → α) ≃ ((unit ⊕ unit) → α) : (arrow_congr bool_equiv_punit_sum_punit (equiv.refl α)) ... ≃ (unit → α) × (unit → α) : sum_arrow_equiv_prod_arrow _ _ _ ... ≃ α × α : prod_congr (punit_arrow_equiv _) (punit_arrow_equiv _) @[simp] lemma bool_to_equiv_prod_apply {α : Type u} (f : bool → α) : bool_to_equiv_prod α f = (f ff, f tt) := rfl @[simp] lemma bool_to_equiv_prod_symm_apply_ff {α : Type u} (p : α × α) : (bool_to_equiv_prod α).symm p ff = p.1 := rfl @[simp] lemma bool_to_equiv_prod_symm_apply_tt {α : Type u} (p : α × α) : (bool_to_equiv_prod α).symm p tt = p.2 := rfl end section open sum nat /-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/ def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ /-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/ def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm /-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/ def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end /-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/ def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β := { to_fun := list.map e, inv_fun := list.map e.symm, left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id], right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] } /-- `fin n` is equivalent to `{m // m < n}`. -/ def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ /-- If `α` is equivalent to `β`, then `unique α` is equivalent to `unique β`. -/ def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := λ h, @equiv.unique _ _ h e.symm, inv_fun := λ h, @equiv.unique _ _ h e, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` is equivalent to `β`, then `is_empty α` is equivalent to `is_empty β`. -/ lemma is_empty_congr (e : α ≃ β) : is_empty α ↔ is_empty β := ⟨λ h, @function.is_empty _ _ h e.symm, λ h, @function.is_empty _ _ h e⟩ section open subtype /-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. For the statement where `α = β`, that is, `e : perm α`, see `perm.subtype_perm`. -/ def subtype_equiv {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := ⟨λ x, ⟨e x, (h _).1 x.2⟩, λ y, ⟨e.symm y, (h _).2 (by { simp, exact y.2 })⟩, λ ⟨x, h⟩, subtype.ext_val $ by simp, λ ⟨y, h⟩, subtype.ext_val $ by simp⟩ @[simp] lemma subtype_equiv_refl {p : α → Prop} (h : ∀ a, p a ↔ p (equiv.refl _ a) := λ a, iff.rfl) : (equiv.refl α).subtype_equiv h = equiv.refl {a : α // p a} := by { ext, refl } @[simp] lemma subtype_equiv_symm {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) : (e.subtype_equiv h).symm = e.symm.subtype_equiv (λ a, by { convert (h $ e.symm a).symm, exact (e.apply_symm_apply a).symm, }) := rfl @[simp] lemma subtype_equiv_trans {p : α → Prop} {q : β → Prop} {r : γ → Prop} (e : α ≃ β) (f : β ≃ γ) (h : ∀ (a : α), p a ↔ q (e a)) (h' : ∀ (b : β), q b ↔ r (f b)): (e.subtype_equiv h).trans (f.subtype_equiv h') = (e.trans f).subtype_equiv (λ a, (h a).trans (h' $ e a)) := rfl @[simp] lemma subtype_equiv_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) : e.subtype_equiv h x = ⟨e x, (h _).1 x.2⟩ := rfl /-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to `{x // q x}`. -/ @[simps] def subtype_equiv_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} := subtype_equiv (equiv.refl _) e /-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent to the subtype `{b // p b}`. -/ def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) : {a : α // p (e a)} ≃ {b : β // p b} := subtype_equiv e $ by simp /-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/ def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := e.symm.subtype_equiv_of_subtype.symm /-- If two predicates are equal, then the corresponding subtypes are equivalent. -/ def subtype_equiv_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_equiv (equiv.refl α) (assume a, h ▸ iff.rfl) /-- The subtypes corresponding to equal sets are equivalent. -/ @[simps apply] def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_equiv_prop h /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This version allows the “inner” predicate to depend on `h : p a`. -/ def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ @[simp] lemma subtype_subtype_equiv_subtype_exists_apply {α : Type u} (p : α → Prop) (q : subtype p → Prop) (a) : (subtype_subtype_equiv_subtype_exists p q a : α) = a := by { cases a, cases a_val, refl } /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/ def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) : {x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_equiv_right $ λ x, exists_prop @[simp] lemma subtype_subtype_equiv_subtype_inter_apply {α : Type u} (p q : α → Prop) (a) : (subtype_subtype_equiv_subtype_inter p q a : α) = a := by { cases a, cases a_val, refl } /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_equiv_right $ assume x, ⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩ @[simp] lemma subtype_subtype_equiv_subtype_apply {α : Type u} {p q : α → Prop} (h : ∀ x, q x → p x) (a : {x : subtype p // q x.1}) : (subtype_subtype_equiv_subtype h a : α) = a := by { cases a, cases a_val, refl } /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ @[simps apply symm_apply] def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) : subtype p ≃ α := ⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ ⟨⟨x, h⟩, y⟩, rfl, λ ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : subtype q, p x) ≃ Σ x : α, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2 /-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then `Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/ def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : subtype p, {x : α // f x = y}) ≃ α := calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x) ... ≃ α : sigma_preimage_equiv f /-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent to `{x // p x}`. -/ def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : subtype q, {x : α // f x = y}) ≃ subtype p := calc (Σ y : subtype q, {x : α // f x = y}) ≃ Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_equiv_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) /-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the `sigma` type such that for all `i` we have `(f i).fst = i`. -/ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ /-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent to the set of functions `Π a, {b : β a // p a b}`. -/ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.ext_val rfl }⟩ /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} : {c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) := ⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩ /-- A subtype of a `prod` is equivalent to a sigma type whose fibers are subtypes. -/ def subtype_prod_equiv_sigma_subtype {α β : Type*} (p : α → β → Prop) : {x : α × β // p x.1 x.2} ≃ Σ a, {b : β // p a b} := { to_fun := λ x, ⟨x.1.1, x.1.2, x.prop⟩, inv_fun := λ x, ⟨⟨x.1, x.2⟩, x.2.prop⟩, left_inv := λ x, by ext; refl, right_inv := λ ⟨a, b, pab⟩, rfl } end section subtype_equiv_codomain variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X} /-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x` is equivalent to the codomain `Y`. -/ def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y := (subtype_preimage _ f).trans $ @fun_unique {x' // ¬ x' ≠ x} _ $ show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _ (show unique {x' // x' = x}, from { default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h }) (subtype_equiv_right $ λ a, not_not) @[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : (subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl @[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y) (g : {g : X → Y // g ∘ coe = f}) : subtype_equiv_codomain f g = (g : X → Y) x := rfl lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) : ((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) = λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y, by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl @[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) : ((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y := rfl @[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) : ((subtype_equiv_codomain f).symm y : X → Y) x = y := dif_neg (not_not.mpr rfl) lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) : ((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ := dif_pos h end subtype_equiv_codomain /-- A set is equivalent to its image under an equivalence. -/ -- We could construct this using `equiv.set.image e s e.injective`, -- but this definition provides an explicit inverse. @[simps] def image {α β : Type*} (e : α ≃ β) (s : set α) : s ≃ e '' s := { to_fun := λ x, ⟨e x.1, by simp⟩, inv_fun := λ y, ⟨e.symm y.1, by { rcases y with ⟨-, ⟨a, ⟨m, rfl⟩⟩⟩, simpa using m, }⟩, left_inv := λ x, by simp, right_inv := λ y, by simp, }. namespace set open set /-- `univ α` is equivalent to `α`. -/ @[simps apply symm_apply] protected def univ (α) : @univ α ≃ α := ⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ /-- An empty set is equivalent to the `empty` type. -/ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty _ /-- An empty set is equivalent to a `pempty` type. -/ protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty _ /-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x, or.inl x.2⟩ | (sum.inr x) := ⟨x, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } /-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg $ λ h, H ⟨h, ha⟩ @[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ := rfl @[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ := rfl /-- A singleton set is equivalent to a `punit` type. -/ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ /-- Equal sets are equivalent. -/ @[simps apply symm_apply] protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x, h ▸ x.2⟩, inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } /-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/ protected def insert {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.subset_def]) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) @[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ := rfl @[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ := rfl @[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl /-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/ protected def sum_compl {α} (s : set α) [decidable_pred (∈ s)] : s ⊕ (sᶜ : set α) ≃ α := calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : sᶜ) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } @[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : s} : (equiv.set.sum_compl s).symm x = sum.inl x := by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx @[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x := by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx /-- `sum_diff_subset s t` is the natural equivalence between `s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/ protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] : s ⊕ (t \ s : set α) ≃ t := calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) : (equiv.set.union (by simp [inter_diff_self])).symm ... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] }) @[simp] lemma sum_diff_subset_apply_inl {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl @[simp] lemma sum_diff_subset_apply_inr {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : t \ s) : equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl lemma sum_diff_subset_symm_apply_of_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∈ s) : (equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inl], exact subtype.eq rfl, end lemma sum_diff_subset_symm_apply_of_not_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∉ s) : (equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inr], exact subtype.eq rfl, end /-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent to `s ⊕ t`. -/ protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred (∈ s)] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } /-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences `e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences between `sᶜ` and `tᶜ`. -/ protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred (∈ s)] [decidable_pred (∈ t)] (e₀ : s ≃ t) : {e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) := { to_fun := λ e, subtype_equiv e (λ a, not_congr $ iff.symm $ maps_to.mem_iff (maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩) (surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2 ⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)), inv_fun := λ e₁, subtype.mk (calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm ... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁ ... ≃ β : set.sum_compl t) (λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply, set.sum_compl_apply_inl, set.sum_compl_symm_apply]), left_inv := λ e, begin ext x, by_cases hx : x ∈ s, { simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩, sum.map_inl, sum_congr_apply, trans_apply, subtype.coe_mk, set.sum_compl_apply_inl] }, { simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, trans_apply, sum_congr_apply, subtype.coe_mk] }, end, right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans, subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] } /-- The set product of two sets is equivalent to the type product of their coercions to types. -/ protected def prod {α β} (s : set α) (t : set β) : s.prod t ≃ s × t := @subtype_prod_equiv_prod α β s t /-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩, λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ /-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/ @[simps apply] protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (H.inj_on s) lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) : (λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) := begin ext ⟨b, a, has, rfl⟩, have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2, simp [equiv.set.image, equiv.set.image_of_inj_on, hf.eq_iff, this], end /-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/ @[simps] protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ /-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm /-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/ protected def powerset {α} (S : set α) : 𝒫 S ≃ set S := { to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α), inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩, left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩, right_inv := λ x, by ext; simp } end set /-- If `f : α → β` has a left-inverse when `α` is nonempty, then `α` is computably equivalent to the range of `f`. While awkward, the `nonempty α` hypothesis on `f_inv` and `hf` allows this to be used when `α` is empty too. This hypothesis is absent on analogous definitions on stronger `equiv`s like `linear_equiv.of_left_inverse` and `ring_equiv.of_left_inverse` as their typeclass assumptions are already sufficient to ensure non-emptiness. -/ @[simps] def of_left_inverse {α β : Sort*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : α ≃ set.range f := { to_fun := λ a, ⟨f a, a, rfl⟩, inv_fun := λ b, f_inv (nonempty_of_exists b.2) b, left_inv := λ a, hf ⟨a⟩ a, right_inv := λ ⟨b, a, ha⟩, subtype.eq $ show f (f_inv ⟨a⟩ b) = b, from eq.trans (congr_arg f $ by exact ha ▸ (hf _ a)) ha } /-- If `f : α → β` has a left-inverse, then `α` is computably equivalent to the range of `f`. Note that if `α` is empty, no such `f_inv` exists and so this definition can't be used, unlike the stronger but less convenient `of_left_inverse`. -/ abbreviation of_left_inverse' {α β : Sort*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : α ≃ set.range f := of_left_inverse f (λ _, f_inv) (λ _, hf) /-- If `f : α → β` is an injective function, then domain `α` is equivalent to the range of `f`. -/ @[simps apply] noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ set.range f := equiv.of_left_inverse f (λ h, by exactI function.inv_fun f) (λ h, by exactI function.left_inverse_inv_fun hf) theorem apply_of_injective_symm {α β} (f : α → β) (hf : injective f) (b : set.range f) : f ((of_injective f hf).symm b) = b := subtype.ext_iff.1 $ (of_injective f hf).apply_symm_apply b @[simp] lemma self_comp_of_injective_symm {α β} (f : α → β) (hf : injective f) : f ∘ ((of_injective f hf).symm) = coe := funext (λ x, apply_of_injective_symm f hf x) lemma of_left_inverse_eq_of_injective {α β : Type*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : of_left_inverse f f_inv hf = of_injective f ((em (nonempty α)).elim (λ h, (hf h).injective) (λ h _ _ _, by { haveI : subsingleton α := subsingleton_of_not_nonempty h, simp })) := by { ext, simp } lemma of_left_inverse'_eq_of_injective {α β : Type*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : of_left_inverse' f f_inv hf = of_injective f hf.injective := by { ext, simp } /-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/ @[simps apply] noncomputable def of_bijective {α β} (f : α → β) (hf : bijective f) : α ≃ β := (of_injective f hf.1).trans $ (set_congr hf.2.range_eq).trans $ equiv.set.univ β lemma of_bijective_apply_symm_apply {α β} (f : α → β) (hf : bijective f) (x : β) : f ((of_bijective f hf).symm x) = x := (of_bijective f hf).apply_symm_apply x @[simp] lemma of_bijective_symm_apply_apply {α β} (f : α → β) (hf : bijective f) (x : α) : (of_bijective f hf).symm (f x) = x := (of_bijective f hf).symm_apply_apply x section variables {α' β' : Type*} (e : perm α') {p : β' → Prop} [decidable_pred p] (f : α' ≃ subtype p) /-- Extend the domain of `e : equiv.perm α` to one that is over `β` via `f : α → subtype p`, where `p : β → Prop`, permuting only the `b : β` that satisfy `p b`. This can be used to extend the domain across a function `f : α → β`, keeping everything outside of `set.range f` fixed. For this use-case `equiv` given by `f` can be constructed by `equiv.of_left_inverse'` or `equiv.of_left_inverse` when there is a known inverse, or `equiv.of_injective` in the general case.`. -/ def perm.extend_domain : perm β' := (perm_congr f e).subtype_congr (equiv.refl _) @[simp] lemma perm.extend_domain_apply_image (a : α') : e.extend_domain f (f a) = f (e a) := by simp [perm.extend_domain] lemma perm.extend_domain_apply_subtype {b : β'} (h : p b) : e.extend_domain f b = f (e (f.symm ⟨b, h⟩)) := by simp [perm.extend_domain, h] lemma perm.extend_domain_apply_not_subtype {b : β'} (h : ¬ p b) : e.extend_domain f b = b := by simp [perm.extend_domain, h] @[simp] lemma perm.extend_domain_refl : perm.extend_domain (equiv.refl _) f = equiv.refl _ := by simp [perm.extend_domain] @[simp] lemma perm.extend_domain_symm : (e.extend_domain f).symm = perm.extend_domain e.symm f := rfl lemma perm.extend_domain_trans (e e' : perm α') : (e.extend_domain f).trans (e'.extend_domain f) = perm.extend_domain (e.trans e') f := by simp [perm.extend_domain, perm_congr_trans] end /-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`. Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/ def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } section swap variable [decidable_eq α] /-- A helper function for `equiv.swap`. -/ def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ @[simp] theorem swap_self (a : α) : swap a a = equiv.refl _ := ext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := ext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases h : b = a; simp [swap_apply_def, h], } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := ext $ λ x, swap_core_swap_core _ _ _ @[simp] lemma symm_swap (a b : α) : (swap a b).symm = swap a b := rfl @[simp] lemma swap_eq_refl_iff {x y : α} : swap x y = equiv.refl _ ↔ x = y := begin refine ⟨λ h, (equiv.refl _).injective _, λ h, h ▸ (swap_self _)⟩, rw [←h, swap_apply_left, h, refl_apply] end theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } lemma swap_eq_update (i j : α) : ⇑(equiv.swap i j) = update (update id j i) i j := funext $ λ x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def] lemma comp_swap_eq_update (i j : α) (f : α → β) : f ∘ equiv.swap i j = update (update f j (f i)) i (f j) := by rw [swap_eq_update, comp_update, comp_update, comp.right_id] @[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma trans_swap_trans_symm [decidable_eq β] (a b : β) (e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) := symm_trans_swap_trans a b e.symm @[simp] lemma swap_apply_self (i j a : α) : swap i j (swap i j a) = a := by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply] /-- A function is invariant to a swap if it is equal at both elements -/ lemma apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k := begin by_cases hi : k = i, { rw [hi, swap_apply_left, hv] }, by_cases hj : k = j, { rw [hj, swap_apply_right, hv] }, rw swap_apply_of_ne_of_ne hi hj, end lemma swap_apply_eq_iff {x y z w : α} : swap x y z = w ↔ z = swap x y w := by rw [apply_eq_iff_eq_symm_apply, symm_swap] lemma swap_apply_ne_self_iff {a b x : α} : swap a b x ≠ x ↔ a ≠ b ∧ (x = a ∨ x = b) := begin by_cases hab : a = b, { simp [hab] }, by_cases hax : x = a, { simp [hax, eq_comm] }, by_cases hbx : x = b, { simp [hbx] }, simp [hab, hax, hbx, swap_apply_of_ne_of_ne] end namespace perm @[simp] lemma sum_congr_swap_refl {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : α) : equiv.perm.sum_congr (equiv.swap i j) (equiv.refl β) = equiv.swap (sum.inl i) (sum.inl j) := begin ext x, cases x, { simp [sum.map, swap_apply_def], split_ifs; refl}, { simp [sum.map, swap_apply_of_ne_of_ne] }, end @[simp] lemma sum_congr_refl_swap {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : β) : equiv.perm.sum_congr (equiv.refl α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := begin ext x, cases x, { simp [sum.map, swap_apply_of_ne_of_ne] }, { simp [sum.map, swap_apply_def], split_ifs; refl}, end end perm /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap end equiv lemma plift.eq_up_iff_down_eq {x : plift α} {y : α} : x = plift.up y ↔ x.down = y := equiv.plift.eq_symm_apply lemma function.injective.map_swap {α β : Type*} [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : f (equiv.swap x y z) = equiv.swap (f x) (f y) (f z) := begin conv_rhs { rw equiv.swap_apply_def }, split_ifs with h₁ h₂, { rw [hf h₁, equiv.swap_apply_left] }, { rw [hf h₂, equiv.swap_apply_right] }, { rw [equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) h₂)] } end namespace equiv protected lemma exists_unique_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∃! x, p x) ↔ ∃! y, q y := begin split, { rintro ⟨a, ha₁, ha₂⟩, exact ⟨f a, h.1 ha₁, λ b hb, f.symm_apply_eq.1 (ha₂ (f.symm b) (h.2 (by simpa using hb)))⟩ }, { rintro ⟨b, hb₁, hb₂⟩, exact ⟨f.symm b, h.2 (by simpa using hb₁), λ y hy, (eq_symm_apply f).2 (hb₂ _ (h.1 hy))⟩ } end protected lemma exists_unique_congr_left' {p : α → Prop} (f : α ≃ β) : (∃! x, p x) ↔ (∃! y, p (f.symm y)) := equiv.exists_unique_congr f (λx, by simp) protected lemma exists_unique_congr_left {p : β → Prop} (f : α ≃ β) : (∃! x, p (f x)) ↔ (∃! y, p y) := (equiv.exists_unique_congr_left' f.symm).symm protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) := begin split; intros h₂ x, { rw [←f.right_inv x], apply h.mp, apply h₂ }, apply h.mpr, apply h₂ end protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) := (equiv.forall_congr f.symm (λ x, h.symm)).symm -- We next build some higher arity versions of `equiv.forall_congr`. -- Although they appear to just be repeated applications of `equiv.forall_congr`, -- unification of metavariables works better with these versions. -- In particular, they are necessary in `equiv_rw`. -- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics, -- it's rare to have axioms involving more than 3 elements at once.) universes ua1 ua2 ub1 ub2 ug1 ug2 variables {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {γ₁ : Sort ug1} {γ₂ : Sort ug2} protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) : (∀x y, p x y) ↔ (∀x y, q x y) := begin apply equiv.forall_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) : (∀x y, p x y) ↔ (∀x y, q x y) := (equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := begin apply equiv.forall₂_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := (equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) : (∀x, p x) ↔ (∀y, p (f.symm y)) := equiv.forall_congr f (λx, by simp) protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) : (∀x, p (f x)) ↔ (∀y, p y) := (equiv.forall_congr_left' f.symm).symm protected lemma exists_congr_left {α β} (f : α ≃ β) {p : α → Prop} : (∃ a, p a) ↔ (∃ b, p (f.symm b)) := ⟨λ ⟨a, h⟩, ⟨f a, by simpa using h⟩, λ ⟨b, h⟩, ⟨_, h⟩⟩ protected lemma set_forall_iff {α β} (e : α ≃ β) {p : set α → Prop} : (∀ a, p a) ↔ (∀ a, p (e ⁻¹' a)) := by simpa [equiv.image_eq_preimage] using (equiv.set.congr e).forall_congr_left' protected lemma preimage_sUnion {α β} (f : α ≃ β) {s : set (set β)} : f ⁻¹' (⋃₀ s) = ⋃₀ (_root_.set.image f ⁻¹' s) := by { ext x, simp [(equiv.set.congr f).symm.exists_congr_left] } section variables (P : α → Sort w) (e : α ≃ β) /-- Transport dependent functions through an equivalence of the base space. -/ @[simps] def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) := { to_fun := λ f x, f (e.symm x), inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end, left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { dsimp, rw e.symm_apply_apply })), right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { rw e.apply_symm_apply })) } end section variables (P : β → Sort w) (e : α ≃ β) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) := (Pi_congr_left' P e.symm).symm end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a))) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibers. -/ def Pi_congr : (Π a, W a) ≃ (Π b, Z b) := (equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁) end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) := (Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm end end equiv lemma function.injective.swap_apply [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := begin by_cases hx : z = x, by simp [hx], by_cases hy : z = y, by simp [hy], rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)] end lemma function.injective.swap_comp [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := funext $ λ z, hf.swap_apply _ _ _ instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [unique α] : unique (ulift α) := equiv.ulift.unique instance {α} [unique α] : unique (plift α) := equiv.plift.unique instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq /-- If both `α` and `β` are singletons, then `α ≃ β`. -/ def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` is a singleton, then it is equivalent to any `punit`. -/ def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique /-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/ def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α := { to_fun := λ p, p.1, inv_fun := λ a, (a, a), left_inv := λ p, subsingleton.elim _ _, right_inv := λ p, subsingleton.elim _ _, } /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β] (f : α → β) (g : β → α) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- A nonempty subsingleton type is (noncomputably) equivalent to `punit`. -/ noncomputable def equiv.punit_of_nonempty_of_subsingleton {α : Sort*} [h : nonempty α] [subsingleton α] : α ≃ punit.{v} := equiv_of_subsingleton_of_subsingleton (λ _, punit.star) (λ _, h.some) /-- `unique (unique α)` is equivalent to `unique α`. -/ def unique_unique_equiv : unique (unique α) ≃ unique α := equiv_of_subsingleton_of_subsingleton (λ h, h.default) (λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }) namespace quot /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : quot ra ≃ quot rb := { to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1), inv_fun := quot.map e.symm (assume b₁ b₂ h, (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)), left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] }, right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } } /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : quot r ≃ quot r' := quot.congr (equiv.refl α) eq /-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α` by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/ protected def congr_left {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := @quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply]) end quot namespace quotient /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) : quotient ra ≃ quotient rb := quot.congr e eq /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : setoid α} (eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' := quot.congr_right eq end quotient /-- If a function is a bijection between two sets `s` and `t`, then it induces an equivalence between the the types `↥s` and ``↥t`. -/ noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set α} {t : set β} (f : α → β) (h : set.bij_on f s t) : s ≃ t := equiv.of_bijective _ h.bijective namespace function lemma update_comp_equiv {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) : update f a v ∘ g = update (f ∘ g) (g.symm a) v := by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply] lemma update_apply_equiv_apply {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') : update f a v (g a') = update (f ∘ g) (g.symm a) v a' := congr_fun (update_comp_equiv f g a v) a' end function /-- The composition of an updated function with an equiv on a subset can be expressed as an updated function. -/ lemma dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {s : set α} (e : β ≃ s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α] [∀ j, decidable (j ∈ s)] : (λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) = function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x := begin ext i, by_cases h : i ∈ s, { rw [dif_pos h, function.update_apply_equiv_apply, equiv.symm_symm, function.comp, function.update_apply, function.update_apply, dif_pos h], have h_coe : (⟨i, h⟩ : s) = e j ↔ i = e j := subtype.ext_iff.trans (by rw subtype.coe_mk), simp_rw h_coe, congr, }, { have : i ≠ e j, by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this }, simp [h, this] } end
6b007666d8cda2ab5d1a8a96ed1590afb21408fd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/identities.lean
93d50ba61afbe3f73ebfe2a68b674eeb975da648
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,758
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.derivative import tactic.linear_combination import tactic.ring_exp /-! # Theory of univariate polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The main def is `binom_expansion`. -/ noncomputable theory namespace polynomial open_locale polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring_exp Maybe use data.nat.choose to prove it. -/ /-- `(x + y)^n` can be expressed as `x^n + n*x^(n-1)*y + k * y^2` for some `k` in the ring. -/ def pow_add_expansion {R : Type*} [comm_semiring R] (x y : R) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, existsi x*z + (n+1)*x^n+z*y, calc (x + y) ^ (n + 2) = (x + y) * (x + y) ^ (n + 1) : by ring_exp ... = (x + y) * (x ^ (n + 1) + ↑(n + 1) * x ^ (n + 1 - 1) * y + z * y ^ 2) : by rw hz ... = x ^ (n + 2) + ↑(n + 2) * x ^ (n + 1) * y + (x*z + (n+1)*x^n+z*y) * y ^ 2 : by { push_cast, ring_exp! } end variables [comm_ring R] private def poly_binom_aux1 (x y : R) (e : ℕ) (a : R) : {k : R // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : R[X]) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr' with n z, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : R[X]) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by { rw poly_binom_aux2, simp [left_distrib, sum_add, mul_assoc] } /-- A polynomial `f` evaluated at `x + y` can be expressed as the evaluation of `f` at `x`, plus `y` times the (polynomial) derivative of `f` at `x`, plus some element `k : R` times `y^2`. -/ def binom_expansion (f : R[X]) (x y : R) : {k : R // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw [←eval_eq_sum], }, { rw derivative_eval, exact finset.sum_mul.symm }, { exact finset.sum_mul.symm } end /-- `x^n - y^n` can be expressed as `z * (x - y)` for some `z` in the ring. -/ def pow_sub_pow_factor (x y : R) : Π (i : ℕ), {z : R // x^i - y^i = z * (x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases @pow_sub_pow_factor (k+1) with z hz, existsi z*x + y^(k+1), linear_combination x * hz with { normalization_tactic := `[ring_exp] } end /-- For any polynomial `f`, `f.eval x - f.eval y` can be expressed as `z * (x - y)` for some `z` in the ring. -/ def eval_sub_factor (f : R[X]) (x y : R) : {z : R // f.eval x - f.eval y = z * (x - y)} := begin refine ⟨f.sum (λ i r, r * (pow_sub_pow_factor x y i).val), _⟩, delta eval eval₂, simp only [sum, ← finset.sum_sub_distrib, finset.sum_mul], dsimp, congr' with i r, rw [mul_assoc, ←(pow_sub_pow_factor x y _).prop, mul_sub], end end identities end polynomial
107ee17343b010376c9247eae391b07b43f2c25c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/subst_tact.lean
8099f53a6e9292b0d2f3acc15fee875218b5df49
[ "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
550
lean
open nat example (a b c : nat) : a = 0 → b = 1 + a → a = b → false := begin intro a0 b1 ab, subst a0 b1, state, contradiction end example (a b c : nat) : a = 0 → b = 1 + a → a = b → false := begin intro a0 b1 ab, subst a0, subst b1, state, contradiction end example (a b c : nat) : a = 0 → 1 + a = b → a = b → false := begin intro a0 b1 ab, subst a0 b1, state, contradiction end example (a b c : nat) : a = 0 → 1 + a = b → a = b → false := begin intros, subst a b, state, contradiction end
7dd992ad3f4723433fefec32efd5dba11a64b53c
ac2987d8c7832fb4a87edb6bee26141facbb6fa0
/Mathlib/Data/List/Basic.lean
520ba8564748f82082829efff590188f5f1bceb7
[ "Apache-2.0" ]
permissive
AurelienSaue/mathlib4
52204b9bd9d207c922fe0cf3397166728bb6c2e2
84271fe0875bafdaa88ac41f1b5a7c18151bd0d5
refs/heads/master
1,689,156,096,545
1,629,378,840,000
1,629,378,840,000
389,648,603
0
0
Apache-2.0
1,627,307,284,000
1,627,307,284,000
null
UTF-8
Lean
false
false
43,252
lean
import Mathlib.Logic.Basic import Mathlib.Data.Nat.Basic import Mathlib.SetNotation import Lean namespace List /-- The same as append, but with simpler defeq. (The one in the standard library is more efficient, because it is implemented in a tail recursive way.) -/ @[simp] def append' : List α → List α → List α | [], r => r | a::l, r => a :: append' l r theorem append'_eq_append : (l r : List α) → append' l r = l ++ r | [], r => rfl | a::l, r => by simp only [append', cons_append, append'_eq_append]; rfl /-- The same as length, but with simpler defeq. (The one in the standard library is more efficient, because it is implemented in a tail recursive way.) -/ @[simp] def length' : List α → ℕ | [] => 0 | a::l => l.length'.succ theorem length'_eq_length : (l : List α) → length' l = l.length | [] => rfl | a::l => by simp only [length', length_cons, length'_eq_length]; rfl theorem concat_eq_append' : ∀ (l : List α) a, concat l a = l.append' [a] | [], a => (append_nil _).symm | x::xs, a => by simp only [concat, append', concat_eq_append' xs]; rfl theorem concat_eq_append (l : List α) (a) : concat l a = l ++ [a] := (concat_eq_append' _ _).trans (append'_eq_append _ _) theorem get_cons_drop : ∀ (l : List α) i h, List.get l i h :: List.drop (i + 1) l = List.drop i l | _::_, 0, h => rfl | _::_, i+1, h => get_cons_drop _ i _ theorem drop_eq_nil_of_le' : ∀ {l : List α} {k : Nat} (h : l.length' ≤ k), l.drop k = [] | [], k, _ => by cases k <;> rfl | a::l, 0, h => by cases h | a::l, k+1, h => drop_eq_nil_of_le' (l := l) h theorem drop_eq_nil_of_le {l : List α} {k : Nat} : (h : l.length ≤ k) → l.drop k = [] := by rw [← length'_eq_length]; exact drop_eq_nil_of_le' @[simp] theorem map_nil {f : α → β} : map f [] = [] := rfl @[simp] theorem map_cons {f : α → β} : map f (b :: l) = f b :: l.map f := rfl @[simp] theorem join_nil : join ([] : List (List α)) = [] := rfl @[simp] theorem join_cons : join (a :: l : List (List α)) = a ++ join l := rfl /-! # Basic properties of Lists -/ -- instance : is_left_id (List α) has_append.append [] := -- ⟨ nil_append ⟩ -- instance : is_right_id (List α) has_append.append [] := -- ⟨ append_nil ⟩ -- instance : is_associative (List α) has_append.append := -- ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : List α) : a::l ≠ [] := by intro h; cases h theorem cons_ne_self (a : α) (l : List α) : a::l ≠ l := mt (congr_arg length') (Nat.succ_ne_self _) theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : List α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := fun Peq => List.noConfusion Peq fun Pheq Pteq => Pheq theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : List α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := fun Peq => List.noConfusion Peq (fun Pheq Pteq => Pteq) -- @[simp] theorem cons_injective {a : α} : injective (cons a) := -- assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe -- theorem cons_inj (a : α) {l l' : List α} : a::l = a::l' ↔ l = l' := -- cons_injective.eq_iff theorem exists_cons_of_ne_nil {l : List α} (h : l ≠ nil) : ∃ b L, l = b :: L := by induction l with | nil => contradiction | cons c l' ih => exact ⟨c, l', rfl⟩ /-! ### bind -/ @[simp] lemma nil_bind (f : α → List β) : List.bind [] f = [] := by simp [join, List.bind] @[simp] lemma cons_bind (x xs) (f : α → List β) : List.bind (x :: xs) f = f x ++ List.bind xs f := by simp [join, List.bind] @[simp] lemma append_bind (xs ys) (f : α → List β) : List.bind (xs ++ ys) f = List.bind xs f ++ List.bind ys f := by induction xs with | nil => rfl | cons z zs ih => simp [ih, cons_bind, List.append_assoc] /-! ### map -/ @[simp] lemma map_append (f : α → β) : ∀ l₁ l₂, map f (l₁ ++ l₂) = (map f l₁) ++ (map f l₂) := by intros l₁ l₂ induction l₁ with | nil => simp | cons a l ih => simp [cons_append, ih] lemma map_singleton (f : α → β) (a : α) : map f [a] = [f a] := rfl @[simp] lemma map_id (l : List α) : map id l = l := by induction l with | nil => simp | cons a l' ih => simp [ih] @[simp] lemma map_map (g : β → γ) (f : α → β) (l : List α) : map g (map f l) = map (g ∘ f) l := by induction l with | nil => simp | cons a l' ih => simp [ih] @[simp] lemma length_map (f : α → β) (l : List α) : length (map f l) = length l := by induction l with | nil => simp | cons a l' ih => simp [ih] /-! ### mem -/ def mem (a : α) : List α → Prop | [] => False | (b :: l) => a = b ∨ mem a l instance : Mem α (List α) := ⟨mem⟩ @[simp] lemma mem_nil (a : α) : a ∈ [] ↔ False := Iff.rfl @[simp] lemma mem_cons {a b : α} {l : List α} : a ∈ (b :: l) ↔ a = b ∨ a ∈ l := Iff.rfl lemma mem_nil_iff (a : α) : a ∈ ([] : List α) ↔ False := Iff.rfl @[simp] lemma not_mem_nil (a : α) : a ∉ ([] : List α) := not_false lemma mem_cons_self (a : α) (l : List α) : a ∈ a :: l := Or.inl rfl @[simp] lemma mem_cons_iff (a y : α) (l : List α) : a ∈ y :: l ↔ (a = y ∨ a ∈ l) := Iff.rfl lemma mem_cons_eq (a y : α) (l : List α) : (a ∈ y :: l) = (a = y ∨ a ∈ l) := rfl lemma mem_cons_of_mem (y : α) {a : α} {l : List α} : a ∈ l → a ∈ y :: l := fun H => Or.inr H lemma eq_or_mem_of_mem_cons {a y : α} {l : List α} : a ∈ y::l → a = y ∨ a ∈ l := fun h => h @[simp] lemma mem_append {a : α} {s t : List α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t := by induction s with | nil => simp | cons a s' ih => simp [or_assoc, ih] lemma mem_append_eq (a : α) (s t : List α) : (a ∈ s ++ t) = (a ∈ s ∨ a ∈ t) := propext mem_append lemma mem_append_left {a : α} {l₁ : List α} (l₂ : List α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ := mem_append.2 (Or.inl h) lemma mem_append_right {a : α} (l₁ : List α) {l₂ : List α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ := mem_append.2 (Or.inr h) lemma not_bex_nil (p : α → Prop) : ¬ (∃ x ∈ @nil α, p x) := fun ⟨x, hx, px⟩ => hx lemma ball_nil (p : α → Prop) : ∀ x, x ∈ @nil α → p x := fun x => False.elim lemma bex_cons (p : α → Prop) (a : α) (l : List α) : (∃ x ∈ (a :: l), p x) ↔ (p a ∨ ∃ x ∈ l, p x) := by split; focus intro ⟨x, h, px⟩ simp at h cases h with | inl h => { rw [h] at px; exact Or.inl px } | inr h => { exact Or.inr ⟨x, h, px⟩ } intro h apply Or.elim _ _ h { exact fun pa => ⟨a, mem_cons_self a l, pa⟩ } exact fun ⟨x, xmem, px⟩ => ⟨x, mem_cons_of_mem _ xmem, px⟩ lemma ball_cons (p : α → Prop) (a : α) (l : List α) : (∀ x ∈ (a :: l), p x) ↔ (p a ∧ ∀ x ∈ l, p x) := Iff.intro (fun al => ⟨al a (mem_cons_self _ _), fun x h => al x (mem_cons_of_mem _ h)⟩) (fun ⟨pa, al⟩ x o => o.elim (fun e => by rw [e]; exact pa) (al x)) instance decidableMem [DecidableEq α] (a : α) : ∀ (l : List α), Decidable (a ∈ l) | [] => isFalse not_false | b :: l => if h₁ : a = b then isTrue (Or.inl h₁) else match decidableMem a l with | isTrue h₂ => isTrue (Or.inr h₂) | isFalse h₂ => isFalse (not_or_intro h₁ h₂) theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := fun this : a ∈ [b] => Or.elim (fun this : a = b => this) (fun this : a ∈ [] => absurd this (not_mem_nil a)) (eq_or_mem_of_mem_cons this) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, Or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : List α} : a ∈ b::l → b ∈ l → a ∈ l := fun ainbl binl => Or.elim (fun this : a = b => by subst a; exact binl) (fun this : a ∈ l => this) (eq_or_mem_of_mem_cons ainbl) theorem _root_.decidable.List.eq_or_ne_mem_of_mem [DecidableEq α] {a b : α} {l : List α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := Decidable.byCases Or.inl fun this : a ≠ b => h.elim Or.inl $ fun h => Or.inr ⟨this, h⟩ theorem eq_or_ne_mem_of_mem {a b : α} {l : List α} : a ∈ b :: l → a = b ∨ (a ≠ b ∧ a ∈ l) := by byCases h : a = b { exact fun _ => Or.inl h } exact fun h' => Or.inr ⟨h, Or.resolve_left h' h⟩ theorem not_mem_append {a : α} {s t : List α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ (not_or _ _).mpr ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : List α} (h : a ∈ l) : l ≠ [] := by intro e; rw [e] at h; cases h theorem mem_split {a : α} {l : List α} (h : a ∈ l) : ∃ s t : List α, l = s ++ a :: t := by induction l with | nil => cases h --exact ⟨[], l, rfl⟩ | cons b l ih => cases h with | inl heq => rw [heq]; exact ⟨[], l, rfl⟩ | inr hmem => match ih hmem with | ⟨s, t, h'⟩ => refine ⟨b::s, t, ?_⟩ rw [h', cons_append] theorem mem_of_ne_of_mem {a y : α} {l : List α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := Or.elim (fun e => absurd e h₁) (fun r => r) $ eq_or_mem_of_mem_cons h₂ theorem ne_of_not_mem_cons {a b : α} {l : List α} : (a ∉ b::l) → a ≠ b := fun nin aeqb => absurd (Or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : List α} : (a ∉ b::l) → a ∉ l := fun nin nainl => absurd (Or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : List α} : a ≠ y → (a ∉ l) → (a ∉ y::l) := fun p1 p2 => fun Pain => absurd (eq_or_mem_of_mem_cons Pain) ((not_or _ _).mpr ⟨p1, p2⟩) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : List α} : (a ∉ y::l) → a ≠ y ∧ a ∉ l := fun p => And.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : List α} (h : a ∈ l) : f a ∈ map f l := by induction l with | nil => cases h | cons b l' ih => cases h with | inl h' => rw [h']; exact Or.inl rfl | inr h' => exact Or.inr $ ih h' theorem exists_of_mem_map {f : α → β} {b : β} {l : List α} (h : b ∈ List.map f l) : ∃ a, a ∈ l ∧ f a = b := by induction l with | nil => cases h | cons c l' ih => cases eq_or_mem_of_mem_cons h with | inl h => exact ⟨c, mem_cons_self _ _, h.symm⟩ | inr h => match ih h with | ⟨a, ha₁, ha₂⟩ => exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ theorem mem_map {f : α → β} {b} : ∀ {l : List α}, b ∈ l.map f ↔ ∃ a, a ∈ l ∧ b = f a | [] => by simp | b :: l => by rw [map_cons, mem_cons, mem_map]; exact ⟨fun | Or.inl h => ⟨_, Or.inl rfl, h⟩ | Or.inr ⟨l, h₁, h₂⟩ => ⟨l, Or.inr h₁, h₂⟩, fun | ⟨_, Or.inl rfl, h⟩ => Or.inl h | ⟨l, Or.inr h₁, h₂⟩ => Or.inr ⟨l, h₁, h₂⟩⟩ -- theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : List α} : -- f a ∈ map f l ↔ a ∈ l := -- ⟨fun m => let ⟨a', m', e⟩ := exists_of_mem_map m -- H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : List α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := by split { intros H j hj; exact H (f j) (mem_map_of_mem f hj) } intros H i hi match mem_map.1 hi with | ⟨j, hj, ji⟩ => rw [ji]; exact H j hj @[simp] lemma map_eq_nil {f : α → β} {l : List α} : List.map f l = [] ↔ l = [] := by split cases l with | nil => intro _; rfl | cons b l => intro h; exact List.noConfusion h intro h; rw [h]; rfl theorem mem_join {a} : ∀ {L : List (List α)}, a ∈ L.join ↔ ∃ l, l ∈ L ∧ a ∈ l | [] => by simp | b :: l => by simp only [join, mem_append, mem_join] exact ⟨fun | Or.inl h => ⟨_, Or.inl rfl, h⟩ | Or.inr ⟨l, h₁, h₂⟩ => ⟨l, Or.inr h₁, h₂⟩, fun | ⟨_, Or.inl rfl, h⟩ => Or.inl h | ⟨l, Or.inr h₁, h₂⟩ => Or.inr ⟨l, h₁, h₂⟩⟩ theorem exists_of_mem_join {a : α} {L : List (List α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : List (List α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ theorem mem_bind {f : α → List β} {b} {l : List α} : b ∈ l.bind f ↔ ∃ a, a ∈ l ∧ b ∈ f a := by simp [List.bind, mem_map, mem_join] exact ⟨fun ⟨_, ⟨a, h₁, rfl⟩, h₂⟩ => ⟨a, h₁, h₂⟩, fun ⟨a, h₁, h₂⟩ => ⟨_, ⟨a, h₁, rfl⟩, h₂⟩⟩ theorem mem_bind_of_mem {b : β} {l : List α} {f : α → List β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ List.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → List β} {f : β → γ} : ∀(l : List α), List.map f (l.bind g) = l.bind (fun a => (g a).map f) | [] => rfl | a::l => by simp only [cons_bind, map_append, bind_map l]; rfl /-! ### length -/ @[simp] lemma length_append (s t : List α) : length (s ++ t) = length s + length t := by induction s with | nil => simp | cons a s ih => simp [ih, Nat.add_comm, Nat.add_left_comm, Nat.succ_add] -- @[simp] lemma length_repeat (a : α) (n : ℕ) : length (repeat a n) = n := -- by induction n; simp [*]; refl -- @[simp] lemma length_tail (l : list α) : length (tail l) = length l - 1 := -- by cases l; refl -- -- TODO(Leo): cleanup proof after arith dec proc -- @[simp] lemma length_drop : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i -- | 0 l := rfl -- | (succ i) [] := eq.symm (nat.zero_sub (succ i)) -- | (succ i) (x::l) := calc -- length (drop (succ i) (x::l)) -- = length l - i : length_drop i l -- ... = succ (length l) - succ i : (nat.succ_sub_succ_eq_sub (length l) i).symm theorem eq_nil_of_length_eq_zero {l : List α} : length l = 0 → l = [] := by induction l with | nil => intros; rfl | cons a l ih => intro h; simp at h theorem ne_nil_of_length_eq_succ {l : List α} : ∀ {n : Nat}, length l = Nat.succ n → l ≠ [] := by induction l with | nil => intros; contradiction | cons a l ih => intros _ _ h; exact List.noConfusion h -- -- TODO: here we need min_zero -- @[simp] theorem length_map₂ (f : α → β → γ) (l₁) : -- ∀ l₂, length (map₂ f l₁ l₂) = min (length l₁) (length l₂) := by -- induction l₁ with -- | nil => -- intro l₂ -- simp -- rw [min_zero] -- | cons a l ih => _ -- -- by { induction l₁; intro l₂; cases l₂; simp [*, add_one, min_succ_succ, Nat.zero_min, Nat.min_zero] } -- @[simp] theorem length_take : ∀ (i : ℕ) (l : List α), length (take i l) = min i (length l) -- | 0 l := by simp [Nat.zero_min] -- | (succ n) [] := by simp [Nat.min_zero] -- | (succ n) (a::l) := by simp [*, Nat.min_succ_succ, add_one] -- theorem length_take_le (n) (l : List α) : length (take n l) ≤ n := -- by simp [min_le_left] -- theorem length_remove_nth : ∀ (l : List α) (i : ℕ), i < length l → length (remove_nth l i) = length l - 1 -- | [] _ h := rfl -- | (x::xs) 0 h := by simp [remove_nth] -- | (x::xs) (i+1) h := have i < length xs, from lt_of_succ_lt_succ h, -- by dsimp [remove_nth]; rw [length_remove_nth xs i this, Nat.sub_add_cancel (lt_of_le_of_lt (Nat.zero_le _) this)]; refl theorem length_eq_zero {l : List α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, fun h => by rw [h]; rfl⟩ @[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl theorem length_pos_of_mem {a : α} : ∀ {l : List α}, a ∈ l → 0 < length l | nil, h => by cases h | b::l, _ => by rw [length_cons]; exact Nat.zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : List α}, 0 < length l → ∃ a, a ∈ l | nil, h => by cases h | b::l, _ => ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : List α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, fun ⟨a, h⟩ => length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : List α} : 0 < length l → l ≠ [] := fun h1 h2 => Nat.lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : List α} : l ≠ [] → 0 < length l := fun h => Nat.pos_iff_ne_zero.2 $ fun h0 => h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : List α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ lemma exists_mem_of_ne_nil (l : List α) (h : l ≠ []) : ∃ x, x ∈ l := exists_mem_of_length_pos (length_pos_of_ne_nil h) theorem length_eq_one {l : List α} : length l = 1 ↔ ∃ a, l = [a] := by split intro h match l with | nil => contradiction | [a] => exact ⟨_, rfl⟩ | a::b::l => simp at h; contradiction exact fun ⟨a, leq⟩ => by rw [leq]; simp lemma exists_of_length_succ {n} : ∀ l : List α, l.length = n + 1 → ∃ h t, l = h :: t | [], H => absurd H.symm $ Nat.succ_ne_zero n | (h :: t), H => ⟨h, t, rfl⟩ -- @[simp] lemma length_injective_iff : injective (List.length : List α → ℕ) ↔ subsingleton α := -- begin -- split, -- { intro h, refine ⟨fun x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, -- { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, -- { refl }, { cases hl }, { cases hl }, -- congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } -- end -- @[simp] lemma length_injective [subsingleton α] : injective (length : List α → ℕ) := -- length_injective_iff.mpr $ by apply_instance /-! ### set-theoretic notation of Lists -/ lemma empty_eq : (∅ : List α) = [] := by rfl --lemma singleton_eq (x : α) : ({x} : List α) = [x] := rfl --lemma insert_neg [DecidableEq α] {x : α} {l : List α} (h : x ∉ l) : -- has_insert.insert x l = x :: l := --if_neg h --lemma insert_pos [DecidableEq α] {x : α} {l : List α} (h : x ∈ l) : -- has_insert.insert x l = l := --if_pos h -- lemma doubleton_eq [DecidableEq α] {x y : α} (h : x ≠ y) : ({x, y} : List α) = [x, y] := by -- rw [insert_neg, singleton_eq]; rwa [singleton_eq, mem_singleton] /-! ### bounded quantifiers over Lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x∈ @nil α, p x := fun x h => by cases h theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : List α}, (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := ball_cons _ _ _ theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : List α} (h : ∀ x, x ∈ a :: l → p x) : ∀ x, x ∈ l → p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq]; rfl theorem forall_mem_append {p : α → Prop} {l₁ l₂ : List α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib]; rfl theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x | ⟨_, ⟨h, _⟩⟩ => by cases h theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : List α) (h : p a) : ∃ x ∈ a :: l, p x := ⟨a, (mem_cons_self _ _), h⟩ theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : List α} : (∃ x ∈ l, p x) → ∃ x ∈ a :: l, p x | ⟨x, h, px⟩ => ⟨x, Or.inr h, px⟩ theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : List α} : (∃ x ∈ a :: l, p x) → p a ∨ ∃ x ∈ l, p x | ⟨x, xal, px⟩ => by cases xal with | inl h => rw [←h]; exact Or.inl px | inr h => exact Or.inr ⟨x, h, px⟩ theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : List α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := Iff.intro or_exists_of_exists_mem_cons (fun h => Or.elim (exists_mem_cons_of l) exists_mem_cons_of_exists h) /-! ### List subset -/ protected def subset (l₁ l₂ : List α) := ∀ {a : α}, a ∈ l₁ → a ∈ l₂ instance : Subset (List α) := ⟨List.subset⟩ @[simp] lemma nil_subset (l : List α) : [] ⊆ l := λ {b} i => False.elim (Iff.mp (mem_nil_iff b) i) @[simp] lemma subset.refl (l : List α) : l ⊆ l := λ {b} i => i lemma subset.trans {l₁ l₂ l₃ : List α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := λ {b} i => h₂ (h₁ i) @[simp] lemma subset_cons (a : α) (l : List α) : l ⊆ a::l := λ {b} i => Or.inr i lemma subset_of_cons_subset {a : α} {l₁ l₂ : List α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ := λ s {b} i => s (mem_cons_of_mem _ i) lemma cons_subset_cons {l₁ l₂ : List α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) := λ {b} hin => Or.elim (λ e : b = a => Or.inl e) (λ i : b ∈ l₁ => Or.inr (s i)) (eq_or_mem_of_mem_cons hin) @[simp] lemma subset_append_left (l₁ l₂ : List α) : l₁ ⊆ l₁++l₂ := λ {b} => mem_append_left _ @[simp] lemma subset_append_right (l₁ l₂ : List α) : l₂ ⊆ l₁++l₂ := λ {b} => mem_append_right _ lemma subset_cons_of_subset (a : α) {l₁ l₂ : List α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) := λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁) => Or.inr (s i) theorem subset_def {l₁ l₂ : List α} : l₁ ⊆ l₂ ↔ ∀ {a : α}, a ∈ l₁ → a ∈ l₂ := Iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : List α) : l ⊆ l₁ → l ⊆ l₁++l₂ := fun s => subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : List α) : l ⊆ l₂ → l ⊆ l₁++l₂ := fun s => subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : List α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]; rfl theorem cons_subset_of_subset_of_mem {a : α} {l m : List α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : List α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := fun {a} h => (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : List α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := by split { intro h; simp only [subset_def] at * split intros; apply h; apply mem_append_left; assumption intros; apply h; apply mem_append_right; assumption } { intro h; match h with | ⟨h1, h2⟩ => apply append_subset_of_subset_of_subset h1 h2 } theorem eq_nil_of_subset_nil : ∀ {l : List α}, l ⊆ [] → l = [] | [], s => rfl | (a::l), s => False.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : List α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [] from ⟨fun e => e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : List α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := fun {x} => by simp only [mem_map, not_and, exists_imp_distrib, and_imp] exact fun a h e => ⟨a, H h, e⟩ -- theorem map_subset_iff {l₁ l₂ : List α} (f : α → β) (h : injective f) : -- map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := -- begin -- refine ⟨_, map_subset f⟩, intros h2 x hx, -- rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, -- cases h hxx', exact hx' -- end @[simp] theorem mem_reverseAux (x : α) : ∀ as bs, x ∈ reverseAux as bs ↔ x ∈ as ∨ x ∈ bs | [], bs => by simp [reverseAux] | a :: as, bs => by simp [reverseAux, mem_reverseAux]; rw [←or_assoc, @or_comm (x = a)] @[simp] theorem mem_reverse (x : α) (as : List α) : x ∈ reverse as ↔ x ∈ as := by simp [reverse] -- TODO: better automation needed theorem mem_filterAux (x : α) (p : α → Bool) : ∀ as bs, x ∈ filterAux p as bs ↔ (x ∈ as ∧ p x) ∨ x ∈ bs | [], bs => by simp [filterAux] | (a :: as), bs => by simp [filterAux] cases pa : p a with | true => simp [mem_filterAux x p as (a :: bs)] split; focus intro h' cases h' with | inl h'' => exact Or.inl ⟨Or.inr h''.1, h''.2⟩ | inr h'' => cases h'' with | inl h₃ => exact Or.inl ⟨Or.inl h₃, h₃ ▸ pa⟩ | inr h₃ => exact Or.inr h₃ intro h' cases h' with | inl h'' => cases h''.1 with | inl h₃ => exact Or.inr (Or.inl h₃) | inr h₃ => exact Or.inl ⟨h₃, h''.2⟩ | inr h'' => exact Or.inr (Or.inr h'') | false => simp [mem_filterAux x p as bs] split; focus intro h' cases h' with | inl h'' => exact Or.inl ⟨Or.inr h''.1, h''.2⟩ | inr h'' => exact Or.inr h'' intro h' cases h' with | inl h'' => cases h''.1 with | inl h₃ => rw [←h₃, h''.2] at pa; contradiction | inr h₃ => exact Or.inl ⟨h₃, h''.2⟩ | inr h'' => exact Or.inr h'' theorem mem_filter (as : List α) (p : α → Bool) (x : α) : x ∈ filter p as ↔ x ∈ as ∧ p x = true := by simp [filter, mem_filterAux] /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : List α} : List.append L₁ L₂ = L₁ ++ L₂ := rfl @[simp] lemma singleton_append {x : α} {l : List α} : [x] ++ l = x :: l := rfl theorem append_ne_nil_of_ne_nil_left (s t : List α) : s ≠ [] → s ++ t ≠ [] := by induction s with | nil => intros; contradiction | cons a s ih => rw [cons_append]; intros _ h; contradiction theorem append_ne_nil_of_ne_nil_right (s t : List α) : t ≠ [] → s ++ t ≠ [] := by induction s with | nil => intros; rw [nil_append]; assumption | cons a s ih => rw [cons_append]; intros _ h; contradiction @[simp] lemma append_eq_nil {p q : List α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p with | nil => simp | cons a p => simp @[simp] lemma nil_eq_append_iff {a b : List α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] -- lemma append_eq_cons_iff {a b c : List α} {x : α} : -- a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by -- cases a with -- | nil => simp -- | cons a as => -- simp -- split -- intro h -- exact ⟨as, by simp [h]⟩ -- focus -- intro ⟨a', ⟨aeq, aseq⟩, h⟩ -- split; apply aeq -- rw [aseq, h] -- lemma cons_eq_append_iff {a b c : List α} {x : α} : -- (x :: c : List α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by -- rw [eq_comm, append_eq_cons_iff] -- lemma append_eq_append_iff {a b c d : List α} : -- a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := -- begin -- induction a generalizing c, -- case nil { rw nil_append, split, -- { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, -- { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, -- case cons : a as ih { -- cases c, -- { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], -- exact eq_comm }, -- { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, -- exists_and_distrib_left] } } -- end -- @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : List α), split_at n l = (take n l, drop n l) -- | 0 a := rfl -- | (succ n) [] := rfl -- | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] -- @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : List α), take n l ++ drop n l = l -- | 0 a := rfl -- | (succ n) [] := rfl -- | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- -- TODO(Leo): cleanup proof after arith dec proc -- theorem append_inj : -- ∀ {s₁ s₂ t₁ t₂ : List α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ -- | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ -- | (a::s₁) [] t₁ t₂ h hl := List.noConfusion $ eq_nil_of_length_eq_zero hl -- | [] (b::s₂) t₁ t₂ h hl := List.noConfusion $ eq_nil_of_length_eq_zero hl.symm -- | (a::s₁) (b::s₂) t₁ t₂ h hl := List.noConfusion h $ fun ab hap, -- let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in -- by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ -- theorem append_inj_right {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) -- (hl : length s₁ = length s₂) : t₁ = t₂ := -- (append_inj h hl).right -- theorem append_inj_left {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) -- (hl : length s₁ = length s₂) : s₁ = s₂ := -- (append_inj h hl).left -- theorem append_inj' {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : -- s₁ = s₂ ∧ t₁ = t₂ := -- append_inj h $ @Nat.add_right_cancel _ (length t₁) _ $ -- let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap -- theorem append_inj_right' {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) -- (hl : length t₁ = length t₂) : t₁ = t₂ := -- (append_inj' h hl).right -- theorem append_inj_left' {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) -- (hl : length t₁ = length t₂) : s₁ = s₂ := -- (append_inj' h hl).left -- theorem append_left_cancel {s t₁ t₂ : List α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := -- append_inj_right h rfl -- theorem append_right_cancel {s₁ s₂ t : List α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := -- append_inj_left' h rfl -- theorem append_right_injective (s : List α) : function.injective (fun t, s ++ t) := -- fun t₁ t₂, append_left_cancel -- theorem append_right_inj {t₁ t₂ : List α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := -- (append_right_injective s).eq_iff -- theorem append_left_injective (t : List α) : function.injective (fun s, s ++ t) := -- fun s₁ s₂, append_right_cancel -- theorem append_left_inj {s₁ s₂ : List α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := -- (append_left_injective t).eq_iff -- theorem map_eq_append_split {f : α → β} {l : List α} {s₁ s₂ : List β} -- (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := -- begin -- have := h, rw [← take_append_drop (length s₁) l] at this ⊢, -- rw map_append at this, -- refine ⟨_, _, rfl, append_inj this _⟩, -- rw [length_map, length_take, min_eq_left], -- rw [← length_map f l, h, length_append], -- apply Nat.le_add_right -- end /-! ### repeat -/ @[simp] def repeat (a: α): ℕ -> List α | 0 => [] | Nat.succ n => a :: repeat a n @[simp] def repeatSucc (a: α) (n: ℕ): repeat a (n + 1) = a :: repeat a n := rfl theorem exists_of_mem_bind {b : β} {l : List α} {f : α → List β} : b ∈ List.bind l f → ∃ a, a ∈ l ∧ b ∈ f a := mem_bind.1 /-! ### insert -/ section insert variable [DecidableEq α] def insert (a : α) (l : List α) := if a ∈ l then l else a :: l @[simp] theorem insert_of_mem {a : α} {l : List α} (h : a ∈ l) : insert a l = l := by simp only [insert, if_pos h]; rfl @[simp] theorem insert_of_not_mem {a : α} {l : List α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert, if_neg h]; rfl @[simp] theorem mem_insert_iff {a b : α} {l : List α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := by byCases h : b ∈ l focus rw [insert_of_mem h] split; apply Or.inr intro h cases h with | inl h' => rw [h']; exact h | inr h' => exact h' focus rw [insert_of_not_mem h]; rfl @[simp] theorem mem_insert_self (a : α) (l : List α) : a ∈ insert a l := mem_insert_iff.2 (Or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : List α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (Or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : List α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : List α} (h : a ∈ l) : length (insert a l) = length l := by rw [insert_of_mem h] @[simp] theorem length_insert_of_not_mem {a : α} {l : List α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw [insert_of_not_mem h, ←length'_eq_length, ←length'_eq_length]; rfl end insert /-! ### erasep -/ def erasep (p : α → Prop) [DecidablePred p] : List α → List α | [] => [] | (a::l) => if p a then l else a :: erasep p l section erasep variable {p : α → Prop} [DecidablePred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : List α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : List α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : List α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : List α} (h : ∀ a, a ∈ l → ¬ p a) : l.erasep p = l := by induction l with | nil => rfl | cons _ _ ih => simp [h _ (Or.inl rfl), ih (forall_mem_of_forall_mem_cons h)] theorem exists_of_erasep {l : List α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := by induction l with | nil => cases al | cons b l ih => byCases pb : p b; focus exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ focus cases al with | inl aeqb => rw [aeqb] at pa; exact False.elim $ pb pa | inr al => match ih al with | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩ => exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw [h₃, cons_append], by simp [pb, h₄]⟩ theorem exists_or_eq_self_of_erasep (p : α → Prop) [DecidablePred p] (l : List α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := by byCases h : ∃ a ∈ l, p a; focus match h with | ⟨a, ha, pa⟩ => exact Or.inr (exists_of_erasep ha pa) focus simp at h exact Or.inl (erasep_of_forall_not h) @[simp] theorem length_erasep_of_mem {l : List α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = Nat.pred (length l) := match exists_of_erasep al pa with | ⟨_, l₁, l₂, _, _, e₁, e₂⟩ => by rw [e₂]; simp [length_append, e₁]; rfl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : List α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs), l₂, h => by byCases h' : p x; focus simp [h'] simp [h'] rw [erasep_append_left pa l₂ (mem_of_ne_of_mem (mt _ h') h)] intro h cases h exact pa theorem erasep_append_right : ∀ {l₁ : List α} (l₂), (∀ b ∈ l₁, ¬ p b) → erasep p (l₁++l₂) = l₁ ++ l₂.erasep p | [], l₂, h => rfl | (x::xs), l₂, h => by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] -- theorem erasep_subList (l : List α) : l.erasep p <+ l := -- by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; -- [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : List α) : l.erasep p ⊆ l := by intro a cases exists_or_eq_self_of_erasep p l with | inl h => rw [h]; apply subset.refl | inr h => match h with | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩ => rw [h₄, h₃, mem_append, mem_append] intro | Or.inl h => exact Or.inl h | Or.inr h => exact Or.inr $ mem_cons_of_mem _ h -- the proof was: -- (erasep_subList l).subset -- theorem subList.erasep {l₁ l₂ : List α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := -- begin -- induction s, -- case List.subList.slnil { refl }, -- case List.subList.cons : l₁ l₂ a s IH { -- by_cases h : p a; simp [h], -- exacts [IH.trans (erasep_subList _), IH.cons _ _ _] }, -- case List.subList.cons2 : l₁ l₂ a s IH { -- by_cases h : p a; simp [h], -- exacts [s, IH.cons2 _ _ _] } -- end theorem mem_of_mem_erasep {a : α} {l : List α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : List α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := by refine ⟨mem_of_mem_erasep, ?_⟩ intro al refine Or.elim ?_ ?_ $ exists_or_eq_self_of_erasep p l { intro h; rw [h]; assumption } intro ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩ rw [h₄] rw [h₃] at al have : a ≠ c := by { intro h; rw [h] at pa; exact pa.elim h₂ } simp [this] at al simp [al] theorem erasep_map (f : β → α) : ∀ (l : List β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] => rfl | (b::l) => by (byCases h : p (f b)) - simp [h, erasep_map f l, @erasep_cons_of_pos β (p ∘ f) _ b l h] - simp [h, erasep_map f l, @erasep_cons_of_neg β (p ∘ f) _ b l h] -- @[simp] theorem extractp_eq_find_erasep : -- ∀ l : List α, extractp p l = (find p l, erasep p l) -- | [] => rfl -- | (a::l) => by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [DecidableEq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : List α) : (b :: l).erase a = if b = a then l else b :: l.erase a := by byCases h : a = b focus simp only [if_pos h.symm, List.erase, EqIffBeqTrue.mp h.symm]; rfl simp only [if_neg (Ne.symm h), List.erase, NeqIffBeqFalse.mp (Ne.symm h)]; rfl @[simp] theorem erase_cons_head (a : α) (l : List α) : (a :: l).erase a = l := by simp [erase_cons] @[simp] theorem erase_cons_tail {a b : α} (l : List α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; rfl theorem erase_eq_erasep (a : α) (l : List α) : l.erase a = l.erasep (Eq a) := by induction l with | nil => rfl | cons b l ih => byCases h : a = b; focus simp [h] simp [h, Ne.symm h, ih] @[simp] theorem erase_of_not_mem {a : α} {l : List α} (h : a ∉ l) : l.erase a = l := by induction l with | nil => rfl | cons b l ih => rw [mem_cons, not_or] at h rw [erase_cons, if_neg (Ne.symm h.1), ih h.2] -- TODO: ∉ should have higher priority theorem exists_erase_eq {a : α} {l : List α} (h : a ∈ l) : ∃ l₁ l₂, (a ∉ l₁) ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := match exists_of_erasep h rfl with | ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩ => by rw [erase_eq_erasep]; exact ⟨l₁, l₂, fun h => h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : List α} (h : a ∈ l) : length (l.erase a) = Nat.pred (length l) := by rw [erase_eq_erasep]; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : List α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by rfl) l₂ h theorem erase_append_right {a : α} {l₁ : List α} (l₂ : List α) (h : a ∉ l₁) : (l₁++l₂).erase a = (l₁ ++ l₂.erase a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right] intros b h' h''; rw [h''] at h; exact h h' -- theorem erase_subList (a : α) (l : List α) : l.erase a <+ l := -- by rw erase_eq_erasep; apply erasep_subList theorem erase_subset (a : α) (l : List α) : l.erase a ⊆ l := by rw [erase_eq_erasep]; apply erasep_subset --(erase_subList a l).subset -- theorem subList.erase (a : α) {l₁ l₂ : List α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := -- by simp [erase_eq_erasep]; exact subList.erasep h theorem mem_of_mem_erase {a b : α} {l : List α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : List α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw [erase_eq_erasep]; exact mem_erasep_of_neg ab.symm -- theorem erase_comm (a b : α) (l : List α) : (l.erase a).erase b = (l.erase b).erase a := -- if ab : a = b then by rw ab else -- if ha : a ∈ l then -- if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with -- | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := -- if h₁ : b ∈ l₁ then -- by rw [erase_append_left _ h₁, erase_append_left _ h₁, -- erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] -- else -- by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', -- erase_cons_tail _ ab, erase_cons_head] -- end -- else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] -- else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] -- theorem map_erase [DecidableEq β] {f : α → β} (finj : injective f) {a : α} -- (l : List α) : map f (l.erase a) = (map f l).erase (f a) := -- by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; -- ext b; simp [finj.eq_iff] -- theorem map_foldl_erase [DecidableEq β] {f : α → β} (finj : injective f) {l₁ l₂ : List α} : -- map f (foldl List.erase l₁ l₂) = foldl (fun l a, l.erase (f a)) (map f l₁) l₂ := -- by induction l₂ generalizing l₁; [refl, -- simp only [foldl_cons, map_erase finj, *]] -- @[simp] theorem count_erase_self (a : α) : -- ∀ (s : List α), count a (List.erase s a) = pred (count a s) -- | [] => by simp -- | (h :: t) := -- begin -- rw erase_cons, -- by_cases p : h = a, -- { rw [if_pos p, count_cons', if_pos p.symm], simp }, -- { rw [if_neg p, count_cons', count_cons', if_neg (fun x : a = h, p x.symm), count_erase_self], -- simp, } -- end -- @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : -- ∀ (s : List α), count a (List.erase s b) = count a s -- | [] := by simp -- | (x :: xs) := -- begin -- rw erase_cons, -- split_ifs with h, -- { rw [count_cons', h, if_neg ab], simp }, -- { rw [count_cons', count_cons', count_erase_of_ne] } -- end end erase -- /-! ### union -/ section variable [DecidableEq α] protected def union (l₁ l₂ : List α) : List α := foldr insert l₂ l₁ @[simp] theorem nil_union (l : List α) : nil.union l = l := by simp [List.union, foldr] @[simp] theorem cons_union (a : α) (l₁ l₂ : List α) : (a :: l₁).union l₂ = insert a (l₁.union l₂) := by simp [List.union, foldr] @[simp] theorem mem_union_iff [DecidableEq α] {x : α} {l₁ l₂ : List α} : x ∈ l₁.union l₂ ↔ x ∈ l₁ ∨ x ∈ l₂ := by induction l₁ with | nil => simp | cons a l' ih => simp [ih, or_assoc] end -- /-! ### inter -/ protected def inter [DecidableEq α] (l₁ l₂ : List α) : List α := filter (fun a => a ∈ l₂) l₁ @[simp] theorem mem_inter_iff [DecidableEq α] {x : α} {l₁ l₂ : List α} : x ∈ l₁.inter l₂ ↔ x ∈ l₁ ∧ x ∈ l₂ := by induction l₁ with | nil => simp [List.inter, mem_filter] | cons a l' ih => simp [List.inter, mem_filter, decide_eq_true_iff (x ∈ l₂)] end List
b1794fb0d0b0032addbcd55ccff635e7b8a23be9
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/equiv/encodable/lattice.lean
9234d0292146bbee99ae6379968fba341723bf94
[ "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
1,968
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import data.equiv.encodable.basic import data.finset.basic import data.set.pairwise /-! # Lattice operations on encodable types Lemmas about lattice and set operations on encodable types ## Implementation Notes This is a separate file, to avoid unnecessary imports in basic files. Previously some of these results were in the `measure_theory` folder. -/ open set namespace encodable variables {α : Type*} {β : Type*} [encodable β] lemma supr_decode₂ [complete_lattice α] (f : β → α) : (⨆ (i : ℕ) (b ∈ decode₂ β i), f b) = (⨆ b, f b) := by { rw [supr_comm], simp [mem_decode₂] } lemma Union_decode₂ (f : β → set α) : (⋃ (i : ℕ) (b ∈ decode₂ β i), f b) = (⋃ b, f b) := supr_decode₂ f @[elab_as_eliminator] lemma Union_decode₂_cases {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode₂ β n, f b) := match decode₂ β n with | none := by { simp, apply H0 } | (some b) := by { convert H1 b, simp [ext_iff] } end theorem Union_decode₂_disjoint_on {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on λ i, ⋃ b ∈ decode₂ β i, f b) := begin rintro i j ij x ⟨h₁, h₂⟩, revert h₁ h₂, simp, intros b₁ e₁ h₁ b₂ e₂ h₂, refine hd _ _ _ ⟨h₁, h₂⟩, cases encodable.mem_decode₂.1 e₁, cases encodable.mem_decode₂.1 e₂, exact mt (congr_arg _) ij end end encodable namespace finset lemma nonempty_encodable {α} (t : finset α) : nonempty $ encodable {i // i ∈ t} := begin classical, induction t using finset.induction with x t hx ih, { refine ⟨⟨λ _, 0, λ _, none, λ ⟨x,y⟩, y.rec _⟩⟩ }, { cases ih with ih, exactI ⟨encodable.of_equiv _ (finset.subtype_insert_equiv_option hx)⟩ } end end finset
86028de8acba45cd9769d9ac3c61a12d605f8335
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/quotient.lean
f8e1379161ef68333404bc53a10fde1e1da8b402
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,792
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.algebra.basic import linear_algebra.basic /-! # Quotients by submodules * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. -/ -- For most of this file we work over a noncommutative ring section ring namespace submodule variables {R M : Type*} {r : R} {x y : M} [ring R] [add_comm_group M] [module R M] variables (p p' : submodule R M) open linear_map -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (@_root_.quotient.mk _ (quotient_rel p) x) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : has_sub (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a - b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩ @[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl instance : add_comm_group (quotient p) := { zero := (0 : quotient p), add := (+), neg := has_neg.neg, sub := has_sub.sub, add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, simp only [←mk_add p, quot_mk_eq_mk, add_assoc] }, zero_add := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, quot_mk_eq_mk, zero_add] }, add_zero := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, add_zero, quot_mk_eq_mk] }, add_comm := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, quot_mk_eq_mk, add_comm] }, add_left_neg := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, ←mk_neg p, quot_mk_eq_mk, add_left_neg] }, sub_eq_add_neg := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, ←mk_neg p, ←mk_sub p, sub_eq_add_neg, quot_mk_eq_mk] }, nsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, nsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, nsmul_succ' := by { rintros n ⟨⟩, simp only [nat.succ_eq_one_add, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul], refl }, zsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, zsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, zsmul_succ' := by { rintros n ⟨⟩, simp [nat.succ_eq_add_one, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul, add_smul, add_comm], refl }, zsmul_neg' := by { rintros n ⟨x⟩, simp_rw [zsmul_neg_succ_of_nat, coe_nat_zsmul], refl }, } section has_scalar variables {S : Type*} [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] (P : submodule R M) instance has_scalar' : has_scalar S (quotient P) := ⟨λ a, quotient.map' ((•) a) $ λ x y h, by simpa [smul_sub] using P.smul_mem (a • 1 : R) h⟩ /-- Shortcut to help the elaborator in the common case. -/ instance has_scalar : has_scalar R (quotient P) := quotient.has_scalar' P @[simp] theorem mk_smul (r : S) (x : M) : (mk (r • x) : quotient P) = r • mk x := rfl instance (T : Type*) [has_scalar T R] [has_scalar T M] [is_scalar_tower T R M] [smul_comm_class S T M] : smul_comm_class S T P.quotient := { smul_comm := λ x y, quotient.ind' $ by exact λ z, congr_arg mk (smul_comm _ _ _) } instance (T : Type*) [has_scalar T R] [has_scalar T M] [is_scalar_tower T R M] [has_scalar S T] [is_scalar_tower S T M] : is_scalar_tower S T P.quotient := { smul_assoc := λ x y, quotient.ind' $ by exact λ z, congr_arg mk (smul_assoc _ _ _) } end has_scalar section module variables {S : Type*} instance mul_action' [monoid S] [has_scalar S R] [mul_action S M] [is_scalar_tower S R M] (P : submodule R M) : mul_action S (quotient P) := function.surjective.mul_action mk (surjective_quot_mk _) P^.quotient.mk_smul instance mul_action (P : submodule R M) : mul_action R (quotient P) := quotient.mul_action' P instance distrib_mul_action' [monoid S] [has_scalar S R] [distrib_mul_action S M] [is_scalar_tower S R M] (P : submodule R M) : distrib_mul_action S (quotient P) := function.surjective.distrib_mul_action ⟨mk, rfl, λ _ _, rfl⟩ (surjective_quot_mk _) P^.quotient.mk_smul instance distrib_mul_action (P : submodule R M) : distrib_mul_action R (quotient P) := quotient.distrib_mul_action' P instance module' [semiring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] (P : submodule R M) : module S (quotient P) := function.surjective.module _ ⟨mk, rfl, λ _ _, rfl⟩ (surjective_quot_mk _) P^.quotient.mk_smul instance module (P : submodule R M) : module R (quotient P) := quotient.module' P variables (S) /-- The quotient of `P` as an `S`-submodule is the same as the quotient of `P` as an `R`-submodule, where `P : submodule R M`. -/ def restrict_scalars_equiv [ring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] (P : submodule R M) : (P.restrict_scalars S).quotient ≃ₗ[S] P.quotient := { map_add' := λ x y, quotient.induction_on₂' x y (λ x' y', rfl), map_smul' := λ c x, quotient.induction_on' x (λ x', rfl), ..quotient.congr_right $ λ _ _, iff.rfl } @[simp] lemma restrict_scalars_equiv_mk [ring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] (P : submodule R M) (x : M) : restrict_scalars_equiv S P (mk x) = mk x := rfl @[simp] lemma restrict_scalars_equiv_symm_mk [ring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] (P : submodule R M) (x : M) : (restrict_scalars_equiv S P).symm (mk x) = mk x := rfl end module lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := set_like.exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient section variables {M₂ : Type*} [add_comm_group M₂] [module R M₂] lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := { to_fun := quotient.mk, map_add' := by simp, map_smul' := by simp } @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl end variables {R₂ M₂ : Type*} [ring R₂] [add_comm_group M₂] [module R₂ M₂] {τ₁₂ : R →+* R₂} /-- Two `linear_map`s from a quotient module are equal if their compositions with `submodule.mkq` are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma linear_map_qext ⦃f g : p.quotient →ₛₗ[τ₁₂] M₂⦄ (h : f.comp p.mkq = g.comp p.mkq) : f = g := linear_map.ext $ λ x, quotient.induction_on' x $ (linear_map.congr_fun h : _) /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₛₗ[τ₁₂] M₂) (h : p ≤ f.ker) : p.quotient →ₛₗ[τ₁₂] M₂ := { to_fun := λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, map_add' := by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, map_smul' := by rintro a ⟨x⟩; exact f.map_smulₛₗ a x } @[simp] theorem liftq_apply (f : M →ₛₗ[τ₁₂] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₛₗ[τ₁₂] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] variables (q : submodule R₂ M₂) /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₛₗ[τ₁₂] M₂) (h : p ≤ comap f q) : p.quotient →ₛₗ[τ₁₂] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₛₗ[τ₁₂] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₛₗ[τ₁₂] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₛₗ[τ₁₂] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₛₗ[τ₁₂] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (h) : range (p.liftq f h) = range f := by simpa only [range_eq_map] using map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₛₗ[τ₁₂] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl lemma span_preimage_eq [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R₂ s).comap f := begin suffices : (span R₂ s).comap f ≤ span R (f ⁻¹' s), { exact le_antisymm (span_preimage_le f s) this, }, have hk : ker f ≤ span R (f ⁻¹' s), { let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, }, rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy, exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), }, rw ← left_eq_sup at hk, rw f.range_coe at h₁, rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁], exact inf_le_right, end end submodule open submodule namespace linear_map section ring variables {R M R₂ M₂ R₃ M₃ : Type*} variables [ring R] [ring R₂] [ring R₃] variables [add_comm_monoid M] [add_comm_group M₂] [add_comm_monoid M₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] [ring_hom_surjective τ₁₂] lemma range_mkq_comp (f : M →ₛₗ[τ₁₂] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₃] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₛₗ[τ₁₂] M₂} (h : ∀ (u v : M₂ →ₗ[R₂] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R₂] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end ring end linear_map open linear_map namespace submodule variables {R M : Type*} {r : R} {x y : M} [ring R] [add_comm_group M] [module R M] variables (p p' : submodule R M) /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = p') : p.quotient ≃ₗ[R] p'.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel p') (equiv.refl _) $ λ a b, by { subst h, refl } } @[simp] lemma quot_equiv_of_eq_mk (h : p = p') (x : M) : submodule.quot_equiv_of_eq p p' h (submodule.quotient.mk x) = submodule.quotient.mk x := rfl end submodule end ring section comm_ring variables {R M M₂ : Type*} {r : R} {x y : M} [comm_ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂] (p : submodule R M) (q : submodule R M₂) namespace submodule /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext, refl, }, map_smul' := λ c f, by { ext, refl, } } end submodule end comm_ring
2fbea62bd004e923feaf7fa41501562757db7a5b
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/order_of_element.lean
72e1ff1bb22c07e303f05ca48da2f1cce6b12d32
[ "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
33,540
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, Julian Kuelshammer -/ import algebra.hom.iterate import data.nat.modeq import data.set.pointwise import dynamics.periodic_pts import group_theory.index /-! # Order of an element This file defines the order of an element of a finite group. For a finite group `G` the order of `x ∈ G` is the minimal `n ≥ 1` such that `x ^ n = 1`. ## Main definitions * `is_of_fin_order` is a predicate on an element `x` of a monoid `G` saying that `x` is of finite order. * `is_of_fin_add_order` is the additive analogue of `is_of_fin_order`. * `order_of x` defines the order of an element `x` of a monoid `G`, by convention its value is `0` if `x` has infinite order. * `add_order_of` is the additive analogue of `order_of`. ## Tags order of an element -/ open function nat open_locale pointwise universes u v variables {G : Type u} {A : Type v} variables {x y : G} {a b : A} {n m : ℕ} section monoid_add_monoid variables [monoid G] [add_monoid A] section is_of_fin_order @[to_additive] lemma is_periodic_pt_mul_iff_pow_eq_one (x : G) : is_periodic_pt ((*) x) n 1 ↔ x ^ n = 1 := by rw [is_periodic_pt, is_fixed_pt, mul_left_iterate, mul_one] /-- `is_of_fin_add_order` is a predicate on an element `a` of an additive monoid to be of finite order, i.e. there exists `n ≥ 1` such that `n • a = 0`.-/ def is_of_fin_add_order (a : A) : Prop := (0 : A) ∈ periodic_pts ((+) a) /-- `is_of_fin_order` is a predicate on an element `x` of a monoid to be of finite order, i.e. there exists `n ≥ 1` such that `x ^ n = 1`.-/ @[to_additive is_of_fin_add_order] def is_of_fin_order (x : G) : Prop := (1 : G) ∈ periodic_pts ((*) x) lemma is_of_fin_add_order_of_mul_iff : is_of_fin_add_order (additive.of_mul x) ↔ is_of_fin_order x := iff.rfl lemma is_of_fin_order_of_add_iff : is_of_fin_order (multiplicative.of_add a) ↔ is_of_fin_add_order a := iff.rfl @[to_additive is_of_fin_add_order_iff_nsmul_eq_zero] lemma is_of_fin_order_iff_pow_eq_one (x : G) : is_of_fin_order x ↔ ∃ n, 0 < n ∧ x ^ n = 1 := by { convert iff.rfl, simp [is_periodic_pt_mul_iff_pow_eq_one] } /-- Elements of finite order are of finite order in submonoids.-/ @[to_additive is_of_fin_add_order_iff_coe] lemma is_of_fin_order_iff_coe (H : submonoid G) (x : H) : is_of_fin_order x ↔ is_of_fin_order (x : G) := by { rw [is_of_fin_order_iff_pow_eq_one, is_of_fin_order_iff_pow_eq_one], norm_cast } /-- The image of an element of finite order has finite order. -/ @[to_additive add_monoid_hom.is_of_fin_order "The image of an element of finite additive order has finite additive order."] lemma monoid_hom.is_of_fin_order {H : Type v} [monoid H] (f : G →* H) {x : G} (h : is_of_fin_order x) : is_of_fin_order $ f x := (is_of_fin_order_iff_pow_eq_one _).mpr $ begin rcases (is_of_fin_order_iff_pow_eq_one _).mp h with ⟨n, npos, hn⟩, exact ⟨n, npos, by rw [←f.map_pow, hn, f.map_one]⟩, end /-- If a direct product has finite order then so does each component. -/ @[to_additive "If a direct product has finite additive order then so does each component."] lemma is_of_fin_order.apply {η : Type*} {Gs : η → Type*} [∀ i, monoid (Gs i)] {x : Π i, Gs i} (h : is_of_fin_order x) : ∀ i, is_of_fin_order (x i) := begin rcases (is_of_fin_order_iff_pow_eq_one _).mp h with ⟨n, npos, hn⟩, exact λ _, (is_of_fin_order_iff_pow_eq_one _).mpr ⟨n, npos, (congr_fun hn.symm _).symm⟩, end /-- 1 is of finite order in any monoid. -/ @[to_additive "0 is of finite order in any additive monoid."] lemma is_of_fin_order_one : is_of_fin_order (1 : G) := (is_of_fin_order_iff_pow_eq_one 1).mpr ⟨1, _root_.one_pos, one_pow 1⟩ end is_of_fin_order /-- `order_of x` is the order of the element `x`, i.e. the `n ≥ 1`, s.t. `x ^ n = 1` if it exists. Otherwise, i.e. if `x` is of infinite order, then `order_of x` is `0` by convention.-/ @[to_additive add_order_of "`add_order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `n • a = 0` if it exists. Otherwise, i.e. if `a` is of infinite order, then `add_order_of a` is `0` by convention."] noncomputable def order_of (x : G) : ℕ := minimal_period ((*) x) 1 @[simp] lemma add_order_of_of_mul_eq_order_of (x : G) : add_order_of (additive.of_mul x) = order_of x := rfl @[simp] lemma order_of_of_add_eq_add_order_of (a : A) : order_of (multiplicative.of_add a) = add_order_of a := rfl @[to_additive add_order_of_pos'] lemma order_of_pos' (h : is_of_fin_order x) : 0 < order_of x := minimal_period_pos_of_mem_periodic_pts h @[to_additive add_order_of_nsmul_eq_zero] lemma pow_order_of_eq_one (x : G) : x ^ order_of x = 1 := begin convert is_periodic_pt_minimal_period ((*) x) _, rw [order_of, mul_left_iterate, mul_one], end @[to_additive add_order_of_eq_zero] lemma order_of_eq_zero (h : ¬ is_of_fin_order x) : order_of x = 0 := by rwa [order_of, minimal_period, dif_neg] @[to_additive add_order_of_eq_zero_iff] lemma order_of_eq_zero_iff : order_of x = 0 ↔ ¬ is_of_fin_order x := ⟨λ h H, (order_of_pos' H).ne' h, order_of_eq_zero⟩ @[to_additive add_order_of_eq_zero_iff'] lemma order_of_eq_zero_iff' : order_of x = 0 ↔ ∀ n : ℕ, 0 < n → x ^ n ≠ 1 := by simp_rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one, not_exists, not_and] /-- A group element has finite order iff its order is positive. -/ @[to_additive add_order_of_pos_iff "A group element has finite additive order iff its order is positive."] lemma order_of_pos_iff : 0 < order_of x ↔ is_of_fin_order x := by rwa [iff_not_comm.mp order_of_eq_zero_iff, pos_iff_ne_zero] @[to_additive nsmul_ne_zero_of_lt_add_order_of'] lemma pow_ne_one_of_lt_order_of' (n0 : n ≠ 0) (h : n < order_of x) : x ^ n ≠ 1 := λ j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_mul_iff_pow_eq_one x).mpr j) @[to_additive add_order_of_le_of_nsmul_eq_zero] lemma order_of_le_of_pow_eq_one (hn : 0 < n) (h : x ^ n = 1) : order_of x ≤ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_mul_iff_pow_eq_one) @[simp, to_additive] lemma order_of_one : order_of (1 : G) = 1 := by rw [order_of, one_mul_eq_id, minimal_period_id] @[simp, to_additive add_monoid.order_of_eq_one_iff] lemma order_of_eq_one_iff : order_of x = 1 ↔ x = 1 := by rw [order_of, is_fixed_point_iff_minimal_period_eq_one, is_fixed_pt, mul_one] @[to_additive nsmul_eq_mod_add_order_of] lemma pow_eq_mod_order_of {n : ℕ} : x ^ n = x ^ (n % order_of x) := calc x ^ n = x ^ (n % order_of x + order_of x * (n / order_of x)) : by rw [nat.mod_add_div] ... = x ^ (n % order_of x) : by simp [pow_add, pow_mul, pow_order_of_eq_one] @[to_additive add_order_of_dvd_of_nsmul_eq_zero] lemma order_of_dvd_of_pow_eq_one (h : x ^ n = 1) : order_of x ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_mul_iff_pow_eq_one _).mpr h) @[to_additive add_order_of_dvd_iff_nsmul_eq_zero] lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of x ∣ n ↔ x ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ @[to_additive add_order_of_map_dvd] lemma order_of_map_dvd {H : Type*} [monoid H] (ψ : G →* H) (x : G) : order_of (ψ x) ∣ order_of x := by { apply order_of_dvd_of_pow_eq_one, rw [←map_pow, pow_order_of_eq_one], apply map_one } @[to_additive] lemma exists_pow_eq_self_of_coprime (h : n.coprime (order_of x)) : ∃ m : ℕ, (x ^ n) ^ m = x := begin by_cases h0 : order_of x = 0, { rw [h0, coprime_zero_right] at h, exact ⟨1, by rw [h, pow_one, pow_one]⟩ }, by_cases h1 : order_of x = 1, { exact ⟨0, by rw [order_of_eq_one_iff.mp h1, one_pow, one_pow]⟩ }, obtain ⟨m, hm⟩ := exists_mul_mod_eq_one_of_coprime h (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, h1⟩), exact ⟨m, by rw [←pow_mul, pow_eq_mod_order_of, hm, pow_one]⟩, end /-- If `x^n = 1`, but `x^(n/p) ≠ 1` for all prime factors `p` of `r`, then `x` has order `n` in `G`. -/ @[to_additive add_order_of_eq_of_nsmul_and_div_prime_nsmul] theorem order_of_eq_of_pow_and_pow_div_prime (hn : 0 < n) (hx : x^n = 1) (hd : ∀ p : ℕ, p.prime → p ∣ n → x^(n/p) ≠ 1) : order_of x = n := begin -- Let `a` be `n/(order_of x)`, and show `a = 1` cases exists_eq_mul_right_of_dvd (order_of_dvd_of_pow_eq_one hx) with a ha, suffices : a = 1, by simp [this, ha], -- Assume `a` is not one... by_contra, have a_min_fac_dvd_p_sub_one : a.min_fac ∣ n, { obtain ⟨b, hb⟩ : ∃ (b : ℕ), a = b * a.min_fac := exists_eq_mul_left_of_dvd a.min_fac_dvd, rw [hb, ←mul_assoc] at ha, exact dvd.intro_left (order_of x * b) ha.symm, }, -- Use the minimum prime factor of `a` as `p`. refine hd a.min_fac (nat.min_fac_prime h) a_min_fac_dvd_p_sub_one _, rw [←order_of_dvd_iff_pow_eq_one, nat.dvd_div_iff (a_min_fac_dvd_p_sub_one), ha, mul_comm, nat.mul_dvd_mul_iff_left (order_of_pos' _)], { exact nat.min_fac_dvd a, }, { rw is_of_fin_order_iff_pow_eq_one, exact Exists.intro n (id ⟨hn, hx⟩) }, end @[to_additive add_order_of_eq_add_order_of_iff] lemma order_of_eq_order_of_iff {H : Type*} [monoid H] {y : H} : order_of x = order_of y ↔ ∀ n : ℕ, x ^ n = 1 ↔ y ^ n = 1 := by simp_rw [← is_periodic_pt_mul_iff_pow_eq_one, ← minimal_period_eq_minimal_period_iff, order_of] @[to_additive add_order_of_injective] lemma order_of_injective {H : Type*} [monoid H] (f : G →* H) (hf : function.injective f) (x : G) : order_of (f x) = order_of x := by simp_rw [order_of_eq_order_of_iff, ←f.map_pow, ←f.map_one, hf.eq_iff, iff_self, forall_const] @[simp, norm_cast, to_additive] lemma order_of_submonoid {H : submonoid G} (y : H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y @[to_additive] lemma order_of_units {y : Gˣ} : order_of (y : G) = order_of y := order_of_injective (units.coe_hom G) units.ext y variables (x) @[to_additive add_order_of_nsmul'] lemma order_of_pow' (h : n ≠ 0) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd h, simp only [order_of, mul_left_iterate], end variables (a) (n) @[to_additive add_order_of_nsmul''] lemma order_of_pow'' (h : is_of_fin_order x) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd' h, simp only [order_of, mul_left_iterate], end @[to_additive] lemma commute.order_of_mul_dvd_lcm {x y : G} (h : commute x y) : order_of (x * y) ∣ nat.lcm (order_of x) (order_of y) := begin convert function.commute.minimal_period_of_comp_dvd_lcm h.function_commute_mul_left, rw [order_of, comp_mul_left], end @[to_additive add_order_of_add_dvd_mul_add_order_of] lemma commute.order_of_mul_dvd_mul_order_of {x y : G} (h : commute x y) : order_of (x * y) ∣ (order_of x) * (order_of y) := dvd_trans h.order_of_mul_dvd_lcm (lcm_dvd_mul _ _) @[to_additive add_order_of_add_eq_mul_add_order_of_of_coprime] lemma commute.order_of_mul_eq_mul_order_of_of_coprime {x y : G} (h : commute x y) (hco : nat.coprime (order_of x) (order_of y)) : order_of (x * y) = (order_of x) * (order_of y) := begin convert h.function_commute_mul_left.minimal_period_of_comp_eq_mul_of_coprime hco, simp only [order_of, comp_mul_left], end /-- Commuting elements of finite order are closed under multiplication. -/ @[to_additive "Commuting elements of finite additive order are closed under addition."] lemma commute.is_of_fin_order_mul {x} (h : commute x y) (hx : is_of_fin_order x) (hy : is_of_fin_order y) : is_of_fin_order (x * y) := order_of_pos_iff.mp $ pos_of_dvd_of_pos h.order_of_mul_dvd_mul_order_of $ mul_pos (order_of_pos' hx) (order_of_pos' hy) section p_prime variables {a x n} {p : ℕ} [hp : fact p.prime] include hp @[to_additive add_order_of_eq_prime] lemma order_of_eq_prime (hg : x ^ p = 1) (hg1 : x ≠ 1) : order_of x = p := minimal_period_eq_prime ((is_periodic_pt_mul_iff_pow_eq_one _).mpr hg) (by rwa [is_fixed_pt, mul_one]) @[to_additive add_order_of_eq_prime_pow] lemma order_of_eq_prime_pow (hnot : ¬ x ^ p ^ n = 1) (hfin : x ^ p ^ (n + 1) = 1) : order_of x = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_mul_iff_pow_eq_one, end omit hp -- An example on how to determine the order of an element of a finite group. example : order_of (-1 : ℤˣ) = 2 := order_of_eq_prime (int.units_sq _) dec_trivial end p_prime end monoid_add_monoid section cancel_monoid variables [left_cancel_monoid G] (x y) @[to_additive nsmul_injective_of_lt_add_order_of] lemma pow_injective_of_lt_order_of (hn : n < order_of x) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := iterate_injective_of_lt_minimal_period hn hm (by simpa only [mul_left_iterate, mul_one]) @[to_additive mem_multiples_iff_mem_range_add_order_of'] lemma mem_powers_iff_mem_range_order_of' [decidable_eq G] (hx : 0 < order_of x) : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' hx (λ i, pow_eq_mod_order_of.symm) lemma pow_eq_one_iff_modeq : x ^ n = 1 ↔ n ≡ 0 [MOD (order_of x)] := by rw [modeq_zero_iff_dvd, order_of_dvd_iff_pow_eq_one] lemma pow_eq_pow_iff_modeq : x ^ n = x ^ m ↔ n ≡ m [MOD (order_of x)] := begin wlog hmn : m ≤ n, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le hmn, rw [← mul_one (x ^ m), pow_add, mul_left_cancel_iff, pow_eq_one_iff_modeq], exact ⟨λ h, nat.modeq.add_left _ h, λ h, nat.modeq.add_left_cancel' _ h⟩, end end cancel_monoid section group variables [group G] [add_group A] {x a} {i : ℤ} /-- Inverses of elements of finite order have finite order. -/ @[to_additive "Inverses of elements of finite additive order have finite additive order."] lemma is_of_fin_order.inv {x : G} (hx : is_of_fin_order x) : is_of_fin_order x⁻¹ := (is_of_fin_order_iff_pow_eq_one _).mpr $ begin rcases (is_of_fin_order_iff_pow_eq_one x).mp hx with ⟨n, npos, hn⟩, refine ⟨n, npos, by simp_rw [inv_pow, hn, inv_one]⟩, end /-- Inverses of elements of finite order have finite order. -/ @[simp, to_additive "Inverses of elements of finite additive order have finite additive order."] lemma is_of_fin_order_inv_iff {x : G} : is_of_fin_order x⁻¹ ↔ is_of_fin_order x := ⟨λ h, inv_inv x ▸ h.inv, is_of_fin_order.inv⟩ @[to_additive add_order_of_dvd_iff_zsmul_eq_zero] lemma order_of_dvd_iff_zpow_eq_one : (order_of x : ℤ) ∣ i ↔ x ^ i = 1 := begin rcases int.eq_coe_or_neg i with ⟨i, rfl|rfl⟩, { rw [int.coe_nat_dvd, order_of_dvd_iff_pow_eq_one, zpow_coe_nat] }, { rw [dvd_neg, int.coe_nat_dvd, zpow_neg, inv_eq_one, zpow_coe_nat, order_of_dvd_iff_pow_eq_one] } end @[simp, to_additive] lemma order_of_inv (x : G) : order_of x⁻¹ = order_of x := by simp [order_of_eq_order_of_iff] @[simp, norm_cast, to_additive] lemma order_of_subgroup {H : subgroup G} (y: H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y @[to_additive zsmul_eq_mod_add_order_of] lemma zpow_eq_mod_order_of : x ^ i = x ^ (i % order_of x) := calc x ^ i = x ^ (i % order_of x + order_of x * (i / order_of x)) : by rw [int.mod_add_div] ... = x ^ (i % order_of x) : by simp [zpow_add, zpow_mul, pow_order_of_eq_one] @[to_additive nsmul_inj_iff_of_add_order_of_eq_zero] lemma pow_inj_iff_of_order_of_eq_zero (h : order_of x = 0) {n m : ℕ} : x ^ n = x ^ m ↔ n = m := begin rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one] at h, push_neg at h, induction n with n IH generalizing m, { cases m, { simp }, { simpa [eq_comm] using h m.succ m.zero_lt_succ } }, { cases m, { simpa using h n.succ n.zero_lt_succ }, { simp [pow_succ, IH] } } end @[to_additive] lemma pow_inj_mod {n m : ℕ} : x ^ n = x ^ m ↔ n % order_of x = m % order_of x := begin cases (order_of x).zero_le.eq_or_lt with hx hx, { simp [pow_inj_iff_of_order_of_eq_zero, hx.symm] }, rw [pow_eq_mod_order_of, @pow_eq_mod_order_of _ _ _ m], exact ⟨pow_injective_of_lt_order_of _ (nat.mod_lt _ hx) (nat.mod_lt _ hx), λ h, congr_arg _ h⟩ end end group section comm_monoid variables [comm_monoid G] /-- Elements of finite order are closed under multiplication. -/ @[to_additive "Elements of finite additive order are closed under addition."] lemma is_of_fin_order.mul (hx : is_of_fin_order x) (hy : is_of_fin_order y) : is_of_fin_order (x * y) := (commute.all x y).is_of_fin_order_mul hx hy end comm_monoid section fintype variables [fintype G] [fintype A] section finite_monoid variables [monoid G] [add_monoid A] open_locale big_operators @[to_additive sum_card_add_order_of_eq_card_nsmul_eq_zero] lemma sum_card_order_of_eq_card_pow_eq_one [decidable_eq G] (hn : 0 < n) : ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = (finset.univ.filter (λ x : G, x ^ n = 1)).card := calc ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume x, suffices : order_of x ≤ n ∧ order_of x ∣ n ↔ x ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) end finite_monoid section finite_cancel_monoid -- TODO: Of course everything also works for right_cancel_monoids. variables [left_cancel_monoid G] [add_left_cancel_monoid A] -- TODO: Use this to show that a finite left cancellative monoid is a group. @[to_additive] lemma exists_pow_eq_one (x : G) : is_of_fin_order x := begin refine (is_of_fin_order_iff_pow_eq_one _).mpr _, obtain ⟨i, j, a_eq, ne⟩ : ∃(i j : ℕ), x ^ i = x ^ j ∧ i ≠ j := by simpa only [not_forall, exists_prop, injective] using (not_injective_infinite_fintype (λi:ℕ, x^i)), wlog h'' : j ≤ i, refine ⟨i - j, tsub_pos_of_lt (lt_of_le_of_ne h'' ne.symm), mul_right_injective (x^j) _⟩, rw [mul_one, ← pow_add, ← a_eq, add_tsub_cancel_of_le h''], end @[to_additive add_order_of_le_card_univ] lemma order_of_le_card_univ : order_of x ≤ fintype.card G := finset.le_card_of_inj_on_range ((^) x) (assume n _, finset.mem_univ _) (assume i hi j hj, pow_injective_of_lt_order_of x hi hj) /-- This is the same as `order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative monoid.-/ @[to_additive add_order_of_pos "This is the same as `add_order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative additive monoid."] lemma order_of_pos (x : G) : 0 < order_of x := order_of_pos' (exists_pow_eq_one x) open nat /-- This is the same as `order_of_pow'` and `order_of_pow''` but with one assumption less which is automatic in the case of a finite cancellative monoid.-/ @[to_additive add_order_of_nsmul "This is the same as `add_order_of_nsmul'` and `add_order_of_nsmul` but with one assumption less which is automatic in the case of a finite cancellative additive monoid."] lemma order_of_pow (x : G) : order_of (x ^ n) = order_of x / gcd (order_of x) n := order_of_pow'' _ _ (exists_pow_eq_one _) @[to_additive mem_multiples_iff_mem_range_add_order_of] lemma mem_powers_iff_mem_range_order_of [decidable_eq G] : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (order_of_pos x) (assume i, pow_eq_mod_order_of.symm) @[to_additive decidable_multiples] noncomputable instance decidable_powers [decidable_eq G] : decidable_pred (∈ submonoid.powers x) := begin assume y, apply decidable_of_iff' (y ∈ (finset.range (order_of x)).image ((^) x)), exact mem_powers_iff_mem_range_order_of end /--The equivalence between `fin (order_of x)` and `submonoid.powers x`, sending `i` to `x ^ i`."-/ @[to_additive fin_equiv_multiples "The equivalence between `fin (add_order_of a)` and `add_submonoid.multiples a`, sending `i` to `i • a`."] noncomputable def fin_equiv_powers (x : G) : fin (order_of x) ≃ (submonoid.powers x : set G) := equiv.of_bijective (λ n, ⟨x ^ ↑n, ⟨n, rfl⟩⟩) ⟨λ ⟨i, hi⟩ ⟨j, hj⟩ ij, subtype.mk_eq_mk.2 (pow_injective_of_lt_order_of x hi hj (subtype.mk_eq_mk.1 ij)), λ ⟨_, i, rfl⟩, ⟨⟨i % order_of x, mod_lt i (order_of_pos x)⟩, subtype.eq pow_eq_mod_order_of.symm⟩⟩ @[simp, to_additive fin_equiv_multiples_apply] lemma fin_equiv_powers_apply {x : G} {n : fin (order_of x)} : fin_equiv_powers x n = ⟨x ^ ↑n, n, rfl⟩ := rfl @[simp, to_additive fin_equiv_multiples_symm_apply] lemma fin_equiv_powers_symm_apply (x : G) (n : ℕ) {hn : ∃ (m : ℕ), x ^ m = x ^ n} : ((fin_equiv_powers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by rw [equiv.symm_apply_eq, fin_equiv_powers_apply, subtype.mk_eq_mk, pow_eq_mod_order_of, fin.coe_mk] /-- The equivalence between `submonoid.powers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ @[to_additive multiples_equiv_multiples "The equivalence between `submonoid.multiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`."] noncomputable def powers_equiv_powers (h : order_of x = order_of y) : (submonoid.powers x : set G) ≃ (submonoid.powers y : set G) := (fin_equiv_powers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_powers y)) @[simp, to_additive multiples_equiv_multiples_apply] lemma powers_equiv_powers_apply (h : order_of x = order_of y) (n : ℕ) : powers_equiv_powers h ⟨x ^ n, n, rfl⟩ = ⟨y ^ n, n, rfl⟩ := begin rw [powers_equiv_powers, equiv.trans_apply, equiv.trans_apply, fin_equiv_powers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_powers_symm_apply], simp [h] end @[to_additive add_order_of_eq_card_multiples] lemma order_eq_card_powers [decidable_eq G] : order_of x = fintype.card (submonoid.powers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_powers x⟩) end finite_cancel_monoid section finite_group variables [group G] [add_group A] @[to_additive] lemma exists_zpow_eq_one (x : G) : ∃ (i : ℤ) (H : i ≠ 0), x ^ (i : ℤ) = 1 := begin rcases exists_pow_eq_one x with ⟨w, hw1, hw2⟩, refine ⟨w, int.coe_nat_ne_zero.mpr (ne_of_gt hw1), _⟩, rw zpow_coe_nat, exact (is_periodic_pt_mul_iff_pow_eq_one _).mp hw2, end open subgroup @[to_additive mem_multiples_iff_mem_zmultiples] lemma mem_powers_iff_mem_zpowers : y ∈ submonoid.powers x ↔ y ∈ zpowers x := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of x).nat_abs, by rwa [← zpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos x))), ← zpow_eq_mod_order_of]⟩⟩ @[to_additive multiples_eq_zmultiples] lemma powers_eq_zpowers (x : G) : (submonoid.powers x : set G) = zpowers x := set.ext $ λ x, mem_powers_iff_mem_zpowers @[to_additive mem_zmultiples_iff_mem_range_add_order_of] lemma mem_zpowers_iff_mem_range_order_of [decidable_eq G] : y ∈ subgroup.zpowers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := by rw [← mem_powers_iff_mem_zpowers, mem_powers_iff_mem_range_order_of] @[to_additive decidable_zmultiples] noncomputable instance decidable_zpowers [decidable_eq G] : decidable_pred (∈ subgroup.zpowers x) := begin simp_rw ←set_like.mem_coe, rw ← powers_eq_zpowers, exact decidable_powers, end /-- The equivalence between `fin (order_of x)` and `subgroup.zpowers x`, sending `i` to `x ^ i`. -/ @[to_additive fin_equiv_zmultiples "The equivalence between `fin (add_order_of a)` and `subgroup.zmultiples a`, sending `i` to `i • a`."] noncomputable def fin_equiv_zpowers (x : G) : fin (order_of x) ≃ (subgroup.zpowers x : set G) := (fin_equiv_powers x).trans (equiv.set.of_eq (powers_eq_zpowers x)) @[simp, to_additive fin_equiv_zmultiples_apply] lemma fin_equiv_zpowers_apply {n : fin (order_of x)} : fin_equiv_zpowers x n = ⟨x ^ (n : ℕ), n, zpow_coe_nat x n⟩ := rfl @[simp, to_additive fin_equiv_zmultiples_symm_apply] lemma fin_equiv_zpowers_symm_apply (x : G) (n : ℕ) {hn : ∃ (m : ℤ), x ^ m = x ^ n} : ((fin_equiv_zpowers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by { rw [fin_equiv_zpowers, equiv.symm_trans_apply, equiv.set.of_eq_symm_apply], exact fin_equiv_powers_symm_apply x n } /-- The equivalence between `subgroup.zpowers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ @[to_additive zmultiples_equiv_zmultiples "The equivalence between `subgroup.zmultiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`."] noncomputable def zpowers_equiv_zpowers (h : order_of x = order_of y) : (subgroup.zpowers x : set G) ≃ (subgroup.zpowers y : set G) := (fin_equiv_zpowers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_zpowers y)) @[simp, to_additive zmultiples_equiv_zmultiples_apply] lemma zpowers_equiv_zpowers_apply (h : order_of x = order_of y) (n : ℕ) : zpowers_equiv_zpowers h ⟨x ^ n, n, zpow_coe_nat x n⟩ = ⟨y ^ n, n, zpow_coe_nat y n⟩ := begin rw [zpowers_equiv_zpowers, equiv.trans_apply, equiv.trans_apply, fin_equiv_zpowers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_zpowers_symm_apply], simp [h] end @[to_additive add_order_eq_card_zmultiples] lemma order_eq_card_zpowers [decidable_eq G] : order_of x = fintype.card (subgroup.zpowers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_zpowers x⟩) open quotient_group /- TODO: use cardinal theory, introduce `card : set G → ℕ`, or setup decidability for cosets -/ @[to_additive add_order_of_dvd_card_univ] lemma order_of_dvd_card_univ : order_of x ∣ fintype.card G := begin classical, have ft_prod : fintype ((G ⧸ zpowers x) × zpowers x), from fintype.of_equiv G group_equiv_quotient_times_subgroup, have ft_s : fintype (zpowers x), from @fintype.prod_right _ _ _ ft_prod _, have ft_cosets : fintype (G ⧸ zpowers x), from @fintype.prod_left _ _ _ ft_prod ⟨⟨1, (zpowers x).one_mem⟩⟩, have eq₁ : fintype.card G = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card G = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of x = @fintype.card _ ft_s, from calc order_of x = _ : order_eq_card_zpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, exact dvd.intro (@fintype.card (G ⧸ subgroup.zpowers x) ft_cosets) (by rw [eq₁, eq₂, mul_comm]) end @[simp, to_additive card_nsmul_eq_zero] lemma pow_card_eq_one : x ^ fintype.card G = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ x _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] @[to_additive] lemma subgroup.pow_index_mem {G : Type*} [group G] (H : subgroup G) [fintype (G ⧸ H)] [normal H] (g : G) : g ^ index H ∈ H := by rw [←eq_one_iff, quotient_group.coe_pow H, index_eq_card, pow_card_eq_one] @[to_additive] lemma pow_eq_mod_card (n : ℕ) : x ^ n = x ^ (n % fintype.card G) := by rw [pow_eq_mod_order_of, ←nat.mod_mod_of_dvd n order_of_dvd_card_univ, ← pow_eq_mod_order_of] @[to_additive] lemma zpow_eq_mod_card (n : ℤ) : x ^ n = x ^ (n % fintype.card G) := by rw [zpow_eq_mod_order_of, ← int.mod_mod_of_dvd n (int.coe_nat_dvd.2 order_of_dvd_card_univ), ← zpow_eq_mod_order_of] /-- If `gcd(|G|,n)=1` then the `n`th power map is a bijection -/ @[to_additive "If `gcd(|G|,n)=1` then the smul by `n` is a bijection", simps] def pow_coprime (h : nat.coprime (fintype.card G) n) : G ≃ G := { to_fun := λ g, g ^ n, inv_fun := λ g, g ^ (nat.gcd_b (fintype.card G) n), left_inv := λ g, by { have key : g ^ _ = g ^ _ := congr_arg (λ n : ℤ, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [zpow_add, zpow_mul, zpow_mul, zpow_coe_nat, zpow_coe_nat, zpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_zpow, one_mul, eq_comm] at key }, right_inv := λ g, by { have key : g ^ _ = g ^ _ := congr_arg (λ n : ℤ, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [zpow_add, zpow_mul, zpow_mul', zpow_coe_nat, zpow_coe_nat, zpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_zpow, one_mul, eq_comm] at key } } @[simp, to_additive] lemma pow_coprime_one (h : nat.coprime (fintype.card G) n) : pow_coprime h 1 = 1 := one_pow n @[simp, to_additive] lemma pow_coprime_inv (h : nat.coprime (fintype.card G) n) {g : G} : pow_coprime h g⁻¹ = (pow_coprime h g)⁻¹ := inv_pow g n @[to_additive add_inf_eq_bot_of_coprime] lemma inf_eq_bot_of_coprime {G : Type*} [group G] {H K : subgroup G} [fintype H] [fintype K] (h : nat.coprime (fintype.card H) (fintype.card K)) : H ⊓ K = ⊥ := begin refine (H ⊓ K).eq_bot_iff_forall.mpr (λ x hx, _), rw [←order_of_eq_one_iff, ←nat.dvd_one, ←h.gcd_eq_one, nat.dvd_gcd_iff], exact ⟨(congr_arg (∣ fintype.card H) (order_of_subgroup ⟨x, hx.1⟩)).mpr order_of_dvd_card_univ, (congr_arg (∣ fintype.card K) (order_of_subgroup ⟨x, hx.2⟩)).mpr order_of_dvd_card_univ⟩, end variable (a) /-- TODO: Generalise to `submonoid.powers`.-/ @[to_additive image_range_add_order_of] lemma image_range_order_of [decidable_eq G] : finset.image (λ i, x ^ i) (finset.range (order_of x)) = (zpowers x : set G).to_finset := by { ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_zpowers_iff_mem_range_order_of] } /-- TODO: Generalise to `finite_cancel_monoid`. -/ @[to_additive gcd_nsmul_card_eq_zero_iff] lemma pow_gcd_card_eq_one_iff : x ^ n = 1 ↔ x ^ (gcd n (fintype.card G)) = 1 := ⟨λ h, pow_gcd_eq_one _ h $ pow_card_eq_one, λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card G) in by rw [hm, pow_mul, h, one_pow]⟩ end finite_group end fintype section pow_is_subgroup /-- A nonempty idempotent subset of a finite cancellative monoid is a submonoid -/ @[to_additive "A nonempty idempotent subset of a finite cancellative add monoid is a submonoid"] def submonoid_of_idempotent {M : Type*} [left_cancel_monoid M] [fintype M] (S : set M) (hS1 : S.nonempty) (hS2 : S * S = S) : submonoid M := have pow_mem : ∀ a : M, a ∈ S → ∀ n : ℕ, a ^ (n + 1) ∈ S := λ a ha, nat.rec (by rwa [zero_add, pow_one]) (λ n ih, (congr_arg2 (∈) (pow_succ a (n + 1)).symm hS2).mp (set.mul_mem_mul ha ih)), { carrier := S, one_mem' := by { obtain ⟨a, ha⟩ := hS1, rw [←pow_order_of_eq_one a, ← tsub_add_cancel_of_le (succ_le_of_lt (order_of_pos a))], exact pow_mem a ha (order_of a - 1) }, mul_mem' := λ a b ha hb, (congr_arg2 (∈) rfl hS2).mp (set.mul_mem_mul ha hb) } /-- A nonempty idempotent subset of a finite group is a subgroup -/ @[to_additive "A nonempty idempotent subset of a finite add group is a subgroup"] def subgroup_of_idempotent {G : Type*} [group G] [fintype G] (S : set G) (hS1 : S.nonempty) (hS2 : S * S = S) : subgroup G := { carrier := S, inv_mem' := λ a ha, show a⁻¹ ∈ submonoid_of_idempotent S hS1 hS2, by { rw [←one_mul a⁻¹, ←pow_one a, ←pow_order_of_eq_one a, ←pow_sub a (order_of_pos a)], exact pow_mem ha (order_of a - 1) }, .. submonoid_of_idempotent S hS1 hS2 } /-- If `S` is a nonempty subset of a finite group `G`, then `S ^ |G|` is a subgroup -/ @[to_additive smul_card_add_subgroup "If `S` is a nonempty subset of a finite add group `G`, then `|G| • S` is a subgroup", simps] def pow_card_subgroup {G : Type*} [group G] [fintype G] (S : set G) (hS : S.nonempty) : subgroup G := have one_mem : (1 : G) ∈ (S ^ fintype.card G) := by { obtain ⟨a, ha⟩ := hS, rw ← pow_card_eq_one, exact set.pow_mem_pow ha (fintype.card G) }, subgroup_of_idempotent (S ^ (fintype.card G)) ⟨1, one_mem⟩ begin classical, refine (set.eq_of_subset_of_card_le (λ b hb, (congr_arg (∈ _) (one_mul b)).mp (set.mul_mem_mul one_mem hb)) (ge_of_eq _)).symm, change _ = fintype.card (_ * _ : set G), rw [←pow_add, group.card_pow_eq_card_pow_card_univ S (fintype.card G) le_rfl, group.card_pow_eq_card_pow_card_univ S (fintype.card G + fintype.card G) le_add_self], end end pow_is_subgroup section linear_ordered_ring variable [linear_ordered_ring G] lemma order_of_abs_ne_one (h : |x| ≠ 1) : order_of x = 0 := begin rw order_of_eq_zero_iff', intros n hn hx, replace hx : |x| ^ n = 1 := by simpa only [abs_one, abs_pow] using congr_arg abs hx, cases h.lt_or_lt with h h, { exact ((pow_lt_one (abs_nonneg x) h hn.ne').ne hx).elim }, { exact ((one_lt_pow h hn.ne').ne' hx).elim } end lemma linear_ordered_ring.order_of_le_two : order_of x ≤ 2 := begin cases ne_or_eq (|x|) 1 with h h, { simp [order_of_abs_ne_one h] }, rcases eq_or_eq_neg_of_abs_eq h with rfl | rfl, { simp }, apply order_of_le_of_pow_eq_one; norm_num end end linear_ordered_ring
d9cf14fff39a19fbf2288bee42efe10949a451a6
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/nat/default.lean
a7f30c0e411c12ddefa020ae0871f9f6b70c16eb
[ "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
245
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import .basic .order .sub .div .gcd .bquant .sqrt .pairing .power .find .fact .parity
32226e75f1a0006250c25fae7c1b7512b4f798e8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/definition.lean
00aeb837d5444c0c3e3776499cee34dc89571299
[ "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
207
lean
inductive Foo where | foo example : Foo := let c := Foo.foo c --^ textDocument/typeDefinition def f (x : Nat) : Nat := match x with | 0 => 1 | y + 1 => y --^ textDocument/declaration
33375f4edb3aa7c99c0682ae1b8f4daf2e365498
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/sanitychecks.lean
cedde21e588f6620b11af2bf6cca027902a2a4be
[ "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
776
lean
theorem unsound : False := -- Error unsound partial theorem unsound : False := -- Error unsound unsafe theorem unsound : False := -- Error unsound constant unsound : False -- Error axiom magic : False -- OK partial def foo (x : Nat) : Nat := foo x -- OK unsafe def unsound2 : False := unsound -- OK partial def unsound3 : False := unsound3 -- Error partial def unsound4 (x : Unit) : False := unsound4 () -- Error partial def badcast1 (x : Nat) : Bool := unsafeCast x -- Error: partial cannot use unsafe constant partial def badcast2 (x : Nat) : Bool := if x == 0 then unsafeCast x -- Error: partial cannot use unsafe constant else badcast2 (x + 1) unsafe def badcast3 (x : Nat) : Bool := -- OK if x == 0 then unsafeCast x else badcast3 (x + 1)
1a9a6ec8da8eee2b3ef6279c7cc1e5cf7fffda84
56762daf61566a2baf390b5d77988c29c75187e3
/src/derivations.lean
6091c36d3e336c24f09789e2289ceb5fc12f1179
[]
no_license
Nicknamen/lie_group
de173ce5f1ffccb945ba05dca23ff27daef0e3b4
e0d5c4f859654e3dea092702f1320c3c72a49983
refs/heads/master
1,674,937,428,196
1,607,213,423,000
1,607,213,423,000
275,196,635
0
0
null
null
null
null
UTF-8
Lean
false
false
4,941
lean
import ring_theory.algebra import tactic /- IMPORTANT TODO: generalize this theory to bimodules. Important cases for mathematical physics are left out. -/ open algebra ring_hom @[protect_proj, ancestor add_left_cancel_semigroup add_comm_monoid] class add_left_cancel_comm_monoid (M : Type*) extends add_left_cancel_semigroup M, add_comm_monoid M variables (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] (M : Type*) [add_left_cancel_monoid M] [semimodule A M] def transitive_scalar (R : Type*) (A : Type*) (M : Type*) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule A M] : has_scalar R M := { smul := λ r m, ((algebra_map R A) r) • m, } def transitive_module (R : Type*) (A : Type*) (M : Type*) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule A M] : semimodule R M := { smul_add := λ r x y, smul_add _ _ _, smul_zero := λ r, smul_zero _, zero_smul := λ x, show algebra_map R A 0 • x = 0, by rw [map_zero, zero_smul], one_smul := λ x, show algebra_map R A 1 • x = x, by rw [map_one, one_smul], mul_smul := λ r s x, show algebra_map R A (r * s) • x = algebra_map R A r • algebra_map R A s • x, by rw [map_mul, mul_smul], add_smul := λ r s x, show algebra_map R A (r + s) • x = algebra_map R A r • x + algebra_map R A s • x, by rw [map_add, add_smul], .. transitive_scalar R A M } class compatible_semimodule (R : Type*) (A : Type*) [comm_semiring R] [semiring A] [algebra R A] (M : Type*) [add_comm_monoid M] [semimodule A M] [semimodule R M] := (compatible {r : R} {m : M} : r • m = ((algebra_map R A) r) • m) structure derivation [semimodule A M] [semimodule R M] [compatible_semimodule R A M] extends A →ₗ[R] M := (leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a) section variables {R} {A} {M} [semimodule R M] [compatible_semimodule R A M] namespace derivation instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩ instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) := ⟨λ D, D.to_linear_map⟩ lemma one_mul_one (M : Type*) [monoid M] : 1 * 1 = 1 := one_mul 1 section variables {R A} (D : derivation R A M) (r : R) (a b : A) @[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b @[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D @[simp] lemma map_mul : D (a * b) = a • D b + b • D a := D.leibniz' _ _ @[simp] lemma leibniz : D (a * b) = b • D a + a • D b := (D.leibniz' a b).trans $ add_comm _ _ @[simp] lemma map_algebra_map : D 1 = 0 := begin have h : D 1 = D (1 * 1) := by rw mul_one, rw [leibniz D 1 1, one_smul] at h, exact add_left_cancel_monoid, end @[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 := begin rw [←mul_one r, monoid_hom.map_mul (algebra_map R A).to_monoid_hom r 1], end variables [comm_ring R] [ring A] [algebra R A] [add_comm_group M] [module A M] @[simp] lemma map_neg : D (-a) = -D a := is_add_group_hom.map_neg D a @[simp] lemma map_sub : D (a - b) = D a - D b := is_add_group_hom.map_sub D a b variables {D1 D2 : derivation R A} lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 := by cases D1; cases D2; congr'; exact linear_map.coe_injective H @[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 := coe_injective $ funext H instance : add_comm_group (derivation R A) := by refine { add := λ D1 D2, ⟨λ a, D1 a + D2 a, λ a1 a2, by rw [D1.map_add, D2.map_add, add_comm₄], λ a1 a2, by rw [D1.map_mul, D2.map_mul, smul_add, smul_add, add_comm₄], λ r, by rw [D1.map_algebra_map, D2.map_algebra_map, add_zero]⟩, zero := ⟨λ a, 0, λ a1 a2, by rw add_zero, λ a1 a2, by rw [smul_zero, smul_zero, add_zero], λ r, rfl⟩, neg := λ D, ⟨λ a, -D a, λ a1 a2, by rw [D.map_add, neg_add], λ a1 a2, by rw [D.map_mul, neg_add, smul_neg, smul_neg], λ r, by rw [D.map_algebra_map, neg_zero]⟩, .. } instance : module A (derivation R A) := { smul := λ a D, ⟨λ b, a • D b, λ a1 a2, by rw [D.map_add, smul_add], λ a1 a2, by rw [D.map_mul, smul_add, smul_smul, smul_smul, mul_comm, mul_smul, mul_comm, mul_smul], λ s, by rw [D.map_algebra_map, smul_zero]⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul A _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul A _ } variables {R A M} def comp {N : Type*} [add_comm_group N] [module A N] (D : derivation R A M) (f : M →ₗ[A] N) : derivation R A N := { to_fun := λ a, f (D a), add := λ a1 a2, by rw [D.map_add, f.map_add], mul := λ a1 a2, by rw [D.map_mul, f.map_add, f.map_smul, f.map_smul], algebra := λ r, by rw [D.map_algebra_map, f.map_zero] } end derivation end
aa18e1fda5599c983d78886a48117855832a831c
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/breen_deligne/suitable.lean
ff4a03b64820ca9feec15d9d17cbb5961c80b62e
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,534
lean
import breen_deligne.basic import data.real.nnreal import for_mathlib.free_abelian_group import for_mathlib.add_monoid_hom open_locale nnreal big_operators namespace breen_deligne variables {k l m n : ℕ} variables (r' : ℝ≥0) (S : Type*) (c c₁ c₂ c₃ : ℝ≥0) [fintype S] namespace basic_universal_map variables (f : basic_universal_map m n) /-- Addition goes from `Mbar r' S c` to `Mbar r' S c'` for suitable `c'`. This predicate says what *suitable* means for basic universal maps. See Lemma 9.11 of [Analytic]. -/ def suitable (f : basic_universal_map m n) (c₁ c₂ : ℝ≥0) : Prop := ∀ i, (∑ j, ↑(f i j).nat_abs) * c₁ ≤ c₂ attribute [class] suitable lemma sup_mul_le (f : basic_universal_map m n) (c₁ c₂ : ℝ≥0) [h : f.suitable c₁ c₂] : (finset.univ.sup $ λ i, ∑ j, ↑(f i j).nat_abs) * c₁ ≤ c₂ := begin by_cases H : c₁ = 0, { unfreezingI {subst H}, rw mul_zero, exact zero_le' }, rw [mul_comm, nnreal.mul_le_iff_le_inv H, finset.sup_le_iff], rintro i -, rw [← nnreal.mul_le_iff_le_inv H, mul_comm], apply h end instance suitable_of_mul_left (f : basic_universal_map m n) [h : f.suitable c₁ c₂] : f.suitable (c * c₁) (c * c₂) := λ i, by { rw mul_left_comm, exact mul_le_mul' le_rfl (h i) } -- move this lemma nat_abs_sum_le_sum_nat_abs {ι : Type*} (s : finset ι) (f : ι → ℤ) : (∑ i in s, f i).nat_abs ≤ ∑ i in s, (f i).nat_abs := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty, int.nat_abs_zero] }, { intros i s his IH, simp only [his, finset.sum_insert, not_false_iff], exact (int.nat_abs_add_le _ _).trans (add_le_add le_rfl IH) } end -- this cannot be an instance, because c₂ cannot be inferred lemma suitable_comp {g : basic_universal_map m n} {f : basic_universal_map l m} {c₁ : ℝ≥0} (c₂ : ℝ≥0) {c₃ : ℝ≥0} [hg : g.suitable c₂ c₃] [hf : f.suitable c₁ c₂] : (g.comp f).suitable c₁ c₃ := begin intro i, simp only [← nat.coe_cast_ring_hom, ← ring_hom.map_sum, comp, matrix.mul_apply], calc ↑(∑ k, (∑ j, g i j * f j k).nat_abs) * c₁ ≤ ↑(∑ j, (g i j).nat_abs * ∑ k, (f j k).nat_abs) * c₁ : _ -- proof below ... = ∑ j, ↑(g i j).nat_abs * ((∑ k, ↑(f j k).nat_abs) * c₁) : _ -- proof below ... ≤ ∑ j, ↑(g i j).nat_abs * c₂ : _ -- proof below ... ≤ c₃ : by { rw ← finset.sum_mul, exact hg i }, { refine mul_le_mul' _ le_rfl, rw nat.cast_le, simp only [finset.mul_sum], rw finset.sum_comm, apply finset.sum_le_sum, rintro k -, simp only [← int.nat_abs_mul], apply nat_abs_sum_le_sum_nat_abs }, { simp only [← nat.coe_cast_ring_hom, ring_hom.map_sum, ring_hom.map_mul, finset.sum_mul, mul_assoc] }, { apply finset.sum_le_sum, rintro j -, exact mul_le_mul' le_rfl (hf j) } end @[priority 1001] instance zero_suitable : (0 : basic_universal_map m n).suitable c₁ c₂ := λ i, by simp only [nat.cast_zero, zero_mul, zero_le', finset.sum_const_zero, matrix.zero_apply, int.nat_abs_zero] end basic_universal_map namespace universal_map open free_abelian_group /-- A univeral map `f` is `suitable c₁ c₂` if all of the matrices `g` occuring in the formal sum `f` satisfy `g.suitable c₁ c₂`. This definition is tailored in such a way that we get a sensible `(LCC_Mbar_pow V S r' c₂ n) ⟶ (LCC_Mbar_pow V S r' c₁ m)` if `f.suitable c₁ c₂`. See Lemma 9.11 of [Analytic]. -/ def suitable (c₁ c₂ : ℝ≥0) (f : universal_map m n) : Prop := ∀ g ∈ f.support, basic_universal_map.suitable g c₁ c₂ attribute [class] suitable lemma suitable_of_mem_support (f : universal_map m n) (c₁ c₂ : ℝ≥0) (g : basic_universal_map m n) (hg : g ∈ f.support) [h : f.suitable c₁ c₂] : g.suitable c₁ c₂ := h g hg lemma suitable_free_predicate (c₁ c₂ : ℝ≥0) : free_predicate (@suitable m n c₁ c₂) := by { intro x, simp only [suitable, forall_eq, finset.mem_singleton, support_of] } lemma suitable_congr (f g : universal_map m n) (c₁ c₂ : ℝ≥0) (h : f = g) : f.suitable c₁ c₂ ↔ g.suitable c₁ c₂ := by subst h end universal_map namespace basic_universal_map open free_abelian_group instance suitable_of (f : basic_universal_map m n) (c₁ c₂ : ℝ≥0) [f.suitable c₁ c₂] : universal_map.suitable c₁ c₂ (of f) := begin intros g hg, rw [support_of, finset.mem_singleton] at hg, rwa hg end instance suitable_of_suitable_of (f : basic_universal_map m n) (c₁ c₂ : ℝ≥0) [h : universal_map.suitable c₁ c₂ (of f)] : f.suitable c₁ c₂ := h f $ by simp only [finset.mem_singleton, support_of] end basic_universal_map namespace universal_map open free_abelian_group @[simp] lemma suitable_of_iff (f : basic_universal_map m n) (c₁ c₂ : ℝ≥0) : suitable c₁ c₂ (of f) ↔ f.suitable c₁ c₂ := ⟨by {introI h, apply_instance}, by {introI h, apply_instance}⟩ instance suitable_zero : (0 : universal_map m n).suitable c₁ c₂ := (suitable_free_predicate c₁ c₂).zero instance suitable_neg (f : universal_map m n) (c₁ c₂ : ℝ≥0) [h : f.suitable c₁ c₂] : suitable c₁ c₂ (-f) := (suitable_free_predicate c₁ c₂).neg h @[simp] lemma suitable_neg_iff (f : universal_map m n) (c₁ c₂ : ℝ≥0) : suitable c₁ c₂ (-f) ↔ f.suitable c₁ c₂ := (suitable_free_predicate c₁ c₂).neg_iff instance suitable_add {f g : universal_map m n} {c₁ c₂ : ℝ≥0} [hf : f.suitable c₁ c₂] [hg : g.suitable c₁ c₂] : suitable c₁ c₂ (f + g) := (suitable_free_predicate c₁ c₂).add hf hg lemma suitable_smul_iff (k : ℤ) (hk : k ≠ 0) (f : universal_map m n) (c₁ c₂ : ℝ≥0) : suitable c₁ c₂ (k • f) ↔ f.suitable c₁ c₂ := (suitable_free_predicate c₁ c₂).smul_iff k hk instance suitable_of_mul_left (f : universal_map m n) [h : f.suitable c₁ c₂] : f.suitable (c * c₁) (c * c₂) := λ g hg, @basic_universal_map.suitable_of_mul_left _ _ _ _ _ _ (h g hg) -- this cannot be an instance, because c₂ cannot be inferred lemma suitable.comp {g : universal_map m n} {f : universal_map l m} {c₁ : ℝ≥0} (c₂ : ℝ≥0) {c₃ : ℝ≥0} [hg : g.suitable c₂ c₃] [hf : f.suitable c₁ c₂] : (comp g f).suitable c₁ c₃ := begin apply free_abelian_group.induction_on_free_predicate (suitable c₂ c₃) (suitable_free_predicate c₂ c₃) g hg; unfreezingI { clear_dependent g }, { simpa only [pi.zero_apply, add_monoid_hom.coe_zero, add_monoid_hom.map_zero] using breen_deligne.universal_map.suitable_zero _ _ }, { intros g hg, apply free_abelian_group.induction_on_free_predicate (suitable c₁ c₂) (suitable_free_predicate c₁ c₂) f hf; unfreezingI { clear_dependent f }, { simp only [add_monoid_hom.map_zero], apply_instance }, { intros f hf, rw comp_of, rw suitable_of_iff at hf hg ⊢, resetI, exact breen_deligne.basic_universal_map.suitable_comp c₂ }, { intros g hg H, simpa only [add_monoid_hom.map_neg, suitable_neg_iff] }, { intros g₁ g₂ hg₁ hg₂ H₁ H₂, simp only [add_monoid_hom.map_add], resetI, apply_instance } }, { intros f hf H, simpa only [pi.neg_apply, add_monoid_hom.map_neg, suitable_neg_iff, add_monoid_hom.coe_neg] }, { intros f₁ f₂ hf₁ hf₂ H₁ H₂, simp only [add_monoid_hom.coe_add, add_monoid_hom.map_add, pi.add_apply], resetI, apply_instance } end end universal_map namespace package /-- A sequence of nonnegative real numbers `c' 0`, `c' 1`, ... is *suitable* with respect to a Breen--Deligne package `BD`, if for all `i : ℕ`, the constants `c' (i+1)` and `c' i` are suitable with respect to the universal map `BD.map i`. This definition ensures that we get a well-defined complex of normed groups `LCC_Mbar_pow V S r' (c' i) (BD.rank i)`, induced by the maps `BD.map i`. -/ class suitable (BD : package) (c' : ℕ → ℝ≥0) : Prop := (universal_suitable : ∀ i, (BD.map i).suitable (c' (i+1)) (c' i)) variables (BD : package) (c' : ℕ → ℝ≥0) (i : ℕ) [BD.suitable c'] instance basic_suitable_of_suitable : ((BD.map i).suitable (c' (i+1)) (c' i)) := suitable.universal_suitable i instance suitable_of_suitable : ((universal_map.comp (BD.map i) (BD.map (i+1))).suitable (c' (i+2)) (c' i)) := universal_map.suitable.comp (c' (i + 1)) end package end breen_deligne
4da8c6ede4e19979d0b72f8bdc6fa38e4fdfb73d
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/sum.lean
455b92d9ff3a6d17f403e32adc7851b1652639a5
[ "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
3,159
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro More theorems about the sum type. -/ universes u v variables {α : Type u} {β : Type v} open sum @[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) := ⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩ @[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) := ⟨λ h, match h with | ⟨inl a, h⟩ := or.inl ⟨a, h⟩ | ⟨inr b, h⟩ := or.inr ⟨b, h⟩ end, λ h, match h with | or.inl ⟨a, h⟩ := ⟨inl a, h⟩ | or.inr ⟨b, h⟩ := ⟨inr b, h⟩ end⟩ namespace sum @[simp] theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b := ⟨inl.inj, congr_arg _⟩ @[simp] theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b := ⟨inr.inj, congr_arg _⟩ @[simp] theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b. @[simp] theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a. section variables (ra : α → α → Prop) (rb : β → β → Prop) /-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`, otherwise use the respective order on `α` or `β`. -/ inductive lex : α ⊕ β → α ⊕ β → Prop | inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂) | inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂) | sep (a b) : lex (inl a) (inr b) variables {ra rb} @[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ := ⟨λ h, by cases h; assumption, lex.inl _⟩ @[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ := ⟨λ h, by cases h; assumption, lex.inr _⟩ @[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) := λ h, by cases h attribute [simp] lex.sep theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) := begin induction aca with a H IH, constructor, intros y h, cases h with a' _ h', exact IH _ h' end theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) := begin induction acb with b H IH, constructor, intros y h, cases h with _ _ _ b' _ h' a, { exact IH _ h' }, { exact aca _ } end theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) := have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a), ⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩ end /-- Swap the factors of a sum type -/ @[simp] def swap : α ⊕ β → β ⊕ α | (inl a) := inr a | (inr b) := inl b @[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x := by cases x; refl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) := funext $ swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap end sum
7a182e9981ce8be52e343455890fe92111dec87f
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/canonize.lean
b221d7a2e6f6f28044d8c583c88c5e2be2f2fc27
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,441
lean
import .cosette_tactics .TDP open tactic section canonize meta inductive canonize_term_repr : Type | sig : expr → list name → canonize_term_repr | prod : list expr → canonize_term_repr meta def expr_to_canonize_term_repr (ex : expr) : tactic canonize_term_repr := match sigma_expr_to_sigma_repr ex with | ⟨[], e⟩ := canonize_term_repr.prod <$> product_to_repr e | repr := function.uncurry canonize_term_repr.sig <$> sigma_repr_to_closed_body_expr repr end private meta definition rw_kc_in_prod_repr (kc : key_constraint) (assumptions : list expr) : expr → tactic (expr × expr) | `(denoteProj %%k₁ %%t ≃ denoteProj %%k₂ %%t') := let is_denote_r (tup : expr) (e : expr) : bool := match e with | `(denote_r %%R %%tup') := R = kc.table ∧ tup' = tup | _ := ff end in if k₁ = k₂ ∧ k₁ = kc.column ∧ assumptions.any (is_denote_r t) ∧ assumptions.any (is_denote_r t') then return (t, t') else failed | _ := failed private meta def mk_key_lhs (kc : key_constraint) (t t' : expr) : tactic (list expr) := monad.mapm to_expr [ ``(denoteProj %%kc.column %%t ≃ denoteProj %%kc.column %%t') , ``(denote_r %%kc.table %%t) , ``(denote_r %%kc.table %%t') ] private meta def mk_key_rhs (kc : key_constraint) (t t' : expr) : tactic (list expr) := monad.mapm to_expr [``(%%t≃%%t'), ``(denote_r %%kc.table %%t)] meta definition canonize : tactic unit := let rewrite_constraint_occurence (kc : key_constraint) (e : expr) : tactic unit := do repr ← expr_to_canonize_term_repr e, match repr with | canonize_term_repr.sig body lconsts := do body_terms ← product_to_repr body, (t, t') ← list.foldr (<|>) failed $ list.map (rw_kc_in_prod_repr kc body_terms) body_terms, key_terms ← mk_key_lhs kc t t', let non_key_terms := body_terms.remove_first_of_each key_terms, let body' := key_terms ++ non_key_terms, rewritten_key_terms ← mk_key_rhs kc t t', let rewritten_body := rewritten_key_terms ++ non_key_terms, intermediate_body_expr ← repr_to_product body', rewritten_body_expr ← repr_to_product rewritten_body, intermediate_sigma_repr ← closed_sigma_repr_to_sigma_repr intermediate_body_expr lconsts, rewritten_sigma_repr ← closed_sigma_repr_to_sigma_repr rewritten_body_expr lconsts, intermediate_expr ← sigma_repr_to_sigma_expr intermediate_sigma_repr, rewritten_expr ← sigma_repr_to_sigma_expr rewritten_sigma_repr, eq_lemma ← tactic.to_expr ``(%%e = %%rewritten_expr), lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, to_expr ``(@eq.trans _ %%e %%intermediate_expr %%rewritten_expr) >>= apply, repeat_n lconsts.length `[apply congr_arg usr.sig, funext], ac_refl, repeat_n lconsts.length `[apply congr_arg usr.sig, funext], to_expr ``(isKey_times_const %%kc.column %%kc.table %%kc.name) >>= rewrite_target, ac_refl, eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name | canonize_term_repr.prod terms := do (t, t') ← list.foldr (<|>) failed $ list.map (rw_kc_in_prod_repr kc terms) terms, key_terms ← mk_key_lhs kc t t', let non_key_terms := terms.remove_first_of_each key_terms, let body' := terms ++ non_key_terms, rewritten_key_terms ← mk_key_rhs kc t t', let rewritten_body := rewritten_key_terms ++ non_key_terms, intermediate_expr ← repr_to_product body', rewritten_expr ← repr_to_product rewritten_body, eq_lemma ← tactic.to_expr ``(%%e = %%rewritten_expr), lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, to_expr ``(@eq.trans _ %%e %%intermediate_expr %%rewritten_expr) >>= apply, ac_refl, rewrite_target kc.name, ac_refl, eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name end in do constraints ← find_keys, monad.mapm' (λ kc, repeat $ get_lhs >>= rewrite_constraint_occurence kc) constraints, monad.mapm' (λ kc, repeat $ get_rhs >>= rewrite_constraint_occurence kc) constraints end canonize
ce935dd6bf8de6cee531671cb404e9f1c484703e
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Declaration.lean
320e926b9d0cc1a50e8e697e1ff1896041f2cdf6
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,485
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean /-- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` Constructor are: the definitional height and the flag `selfOpt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during Type checking. Remark: the ReducibilityHints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the Elaborator. The ReducibilityHints are used by the kernel (and Elaborator). Moreover, the ReducibilityHints cannot be changed after a declaration is added to the kernel. -/ inductive ReducibilityHints := | opaque : ReducibilityHints | «abbrev» : ReducibilityHints | regular : UInt32 → ReducibilityHints @[export lean_mk_reducibility_hints_regular] def mkReducibilityHintsRegularEx (h : UInt32) : ReducibilityHints := ReducibilityHints.regular h @[export lean_reducibility_hints_get_height] def ReducibilityHints.getHeightEx (h : ReducibilityHints) : UInt32 := match h with | ReducibilityHints.regular h => h | _ => 0 namespace ReducibilityHints instance : Inhabited ReducibilityHints := ⟨opaque⟩ def lt : ReducibilityHints → ReducibilityHints → Bool | «abbrev», «abbrev» => false | «abbrev», _ => true | regular d₁, regular d₂ => d₁ < d₂ | regular _, opaque => true | _, _ => false end ReducibilityHints /-- Base structure for `AxiomVal`, `DefinitionVal`, `TheoremVal`, `InductiveVal`, `ConstructorVal`, `RecursorVal` and `QuotVal`. -/ structure ConstantVal := (name : Name) (lparams : List Name) (type : Expr) instance : Inhabited ConstantVal := ⟨{ name := arbitrary, lparams := arbitrary, type := arbitrary }⟩ structure AxiomVal extends ConstantVal := (isUnsafe : Bool) @[export lean_mk_axiom_val] def mkAxiomValEx (name : Name) (lparams : List Name) (type : Expr) (isUnsafe : Bool) : AxiomVal := { name := name, lparams := lparams, type := type, isUnsafe := isUnsafe } @[export lean_axiom_val_is_unsafe] def AxiomVal.isUnsafeEx (v : AxiomVal) : Bool := v.isUnsafe structure DefinitionVal extends ConstantVal := (value : Expr) (hints : ReducibilityHints) (isUnsafe : Bool) @[export lean_mk_definition_val] def mkDefinitionValEx (name : Name) (lparams : List Name) (type : Expr) (val : Expr) (hints : ReducibilityHints) (isUnsafe : Bool) : DefinitionVal := { name := name, lparams := lparams, type := type, value := val, hints := hints, isUnsafe := isUnsafe } @[export lean_definition_val_is_unsafe] def DefinitionVal.isUnsafeEx (v : DefinitionVal) : Bool := v.isUnsafe structure TheoremVal extends ConstantVal := (value : Expr) /- Value for an opaque constant declaration `constant x : t := e` -/ structure OpaqueVal extends ConstantVal := (value : Expr) (isUnsafe : Bool) @[export lean_mk_opaque_val] def mkOpaqueValEx (name : Name) (lparams : List Name) (type : Expr) (val : Expr) (isUnsafe : Bool) : OpaqueVal := { name := name, lparams := lparams, type := type, value := val, isUnsafe := isUnsafe } @[export lean_opaque_val_is_unsafe] def OpaqueVal.isUnsafeEx (v : OpaqueVal) : Bool := v.isUnsafe structure Constructor := (name : Name) (type : Expr) structure InductiveType := (name : Name) (type : Expr) (ctors : List Constructor) /-- Declaration object that can be sent to the kernel. -/ inductive Declaration := | axiomDecl (val : AxiomVal) | defnDecl (val : DefinitionVal) | thmDecl (val : TheoremVal) | opaqueDecl (val : OpaqueVal) | quotDecl | mutualDefnDecl (defns : List DefinitionVal) -- All definitions must be marked as `unsafe` | inductDecl (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) instance : Inhabited Declaration := ⟨Declaration.quotDecl⟩ @[export lean_mk_inductive_decl] def mkInductiveDeclEs (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) : Declaration := Declaration.inductDecl lparams nparams types isUnsafe @[export lean_is_unsafe_inductive_decl] def Declaration.isUnsafeInductiveDeclEx : Declaration → Bool | Declaration.inductDecl _ _ _ isUnsafe => isUnsafe | _ => false @[specialize] def Declaration.foldExprM {α} {m : Type → Type} [Monad m] (d : Declaration) (f : α → Expr → m α) (a : α) : m α := match d with | Declaration.quotDecl => pure a | Declaration.axiomDecl { type := type, .. } => f a type | Declaration.defnDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.opaqueDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.thmDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.mutualDefnDecl vals => vals.foldlM (fun a v => do let a ← f a v.type; f a v.value) a | Declaration.inductDecl _ _ inductTypes _ => inductTypes.foldlM (fun a inductType => do let a ← f a inductType.type inductType.ctors.foldlM (fun a ctor => f a ctor.type) a) a @[inline] def Declaration.forExprM {m : Type → Type} [Monad m] (d : Declaration) (f : Expr → m Unit) : m Unit := d.foldExprM (fun _ a => f a) () /-- The kernel compiles (mutual) inductive declarations (see `inductiveDecls`) into a set of - `Declaration.inductDecl` (for each inductive datatype in the mutual Declaration), - `Declaration.ctorDecl` (for each Constructor in the mutual Declaration), - `Declaration.recDecl` (automatically generated recursors). This data is used to implement iota-reduction efficiently and compile nested inductive declarations. A series of checks are performed by the kernel to check whether a `inductiveDecls` is valid or not. -/ structure InductiveVal extends ConstantVal := (nparams : Nat) -- Number of parameters (nindices : Nat) -- Number of indices (all : List Name) -- List of all (including this one) inductive datatypes in the mutual declaration containing this one (ctors : List Name) -- List of all constructors for this inductive datatype (isRec : Bool) -- `true` Iff it is recursive (isUnsafe : Bool) (isReflexive : Bool) @[export lean_mk_inductive_val] def mkInductiveValEx (name : Name) (lparams : List Name) (type : Expr) (nparams nindices : Nat) (all ctors : List Name) (isRec isUnsafe isReflexive : Bool) : InductiveVal := { name := name, lparams := lparams, type := type, nparams := nparams, nindices := nindices, all := all, ctors := ctors, isRec := isRec, isUnsafe := isUnsafe, isReflexive := isReflexive } @[export lean_inductive_val_is_rec] def InductiveVal.isRecEx (v : InductiveVal) : Bool := v.isRec @[export lean_inductive_val_is_unsafe] def InductiveVal.isUnsafeEx (v : InductiveVal) : Bool := v.isUnsafe @[export lean_inductive_val_is_reflexive] def InductiveVal.isReflexiveEx (v : InductiveVal) : Bool := v.isReflexive def InductiveVal.nctors (v : InductiveVal) : Nat := v.ctors.length structure ConstructorVal extends ConstantVal := (induct : Name) -- Inductive Type this Constructor is a member of (cidx : Nat) -- Constructor index (i.e., Position in the inductive declaration) (nparams : Nat) -- Number of parameters in inductive datatype `induct` (nfields : Nat) -- Number of fields (i.e., arity - nparams) (isUnsafe : Bool) @[export lean_mk_constructor_val] def mkConstructorValEx (name : Name) (lparams : List Name) (type : Expr) (induct : Name) (cidx nparams nfields : Nat) (isUnsafe : Bool) : ConstructorVal := { name := name, lparams := lparams, type := type, induct := induct, cidx := cidx, nparams := nparams, nfields := nfields, isUnsafe := isUnsafe } @[export lean_constructor_val_is_unsafe] def ConstructorVal.isUnsafeEx (v : ConstructorVal) : Bool := v.isUnsafe instance : Inhabited ConstructorVal := ⟨{ toConstantVal := arbitrary, induct := arbitrary, cidx := 0, nparams := 0, nfields := 0, isUnsafe := true }⟩ /-- Information for reducing a recursor -/ structure RecursorRule := (ctor : Name) -- Reduction rule for this Constructor (nfields : Nat) -- Number of fields (i.e., without counting inductive datatype parameters) (rhs : Expr) -- Right hand side of the reduction rule structure RecursorVal extends ConstantVal := (all : List Name) -- List of all inductive datatypes in the mutual declaration that generated this recursor (nparams : Nat) -- Number of parameters (nindices : Nat) -- Number of indices (nmotives : Nat) -- Number of motives (nminors : Nat) -- Number of minor premises (rules : List RecursorRule) -- A reduction for each Constructor (k : Bool) -- It supports K-like reduction (isUnsafe : Bool) @[export lean_mk_recursor_val] def mkRecursorValEx (name : Name) (lparams : List Name) (type : Expr) (all : List Name) (nparams nindices nmotives nminors : Nat) (rules : List RecursorRule) (k isUnsafe : Bool) : RecursorVal := { name := name, lparams := lparams, type := type, all := all, nparams := nparams, nindices := nindices, nmotives := nmotives, nminors := nminors, rules := rules, k := k, isUnsafe := isUnsafe } @[export lean_recursor_k] def RecursorVal.kEx (v : RecursorVal) : Bool := v.k @[export lean_recursor_is_unsafe] def RecursorVal.isUnsafeEx (v : RecursorVal) : Bool := v.isUnsafe def RecursorVal.getMajorIdx (v : RecursorVal) : Nat := v.nparams + v.nmotives + v.nminors + v.nindices def RecursorVal.getInduct (v : RecursorVal) : Name := v.name.getPrefix inductive QuotKind := | type -- `Quot` | ctor -- `Quot.mk` | lift -- `Quot.lift` | ind -- `Quot.ind` structure QuotVal extends ConstantVal := (kind : QuotKind) @[export lean_mk_quot_val] def mkQuotValEx (name : Name) (lparams : List Name) (type : Expr) (kind : QuotKind) : QuotVal := { name := name, lparams := lparams, type := type, kind := kind } @[export lean_quot_val_kind] def QuotVal.kindEx (v : QuotVal) : QuotKind := v.kind /-- Information associated with constant declarations. -/ inductive ConstantInfo := | axiomInfo (val : AxiomVal) | defnInfo (val : DefinitionVal) | thmInfo (val : TheoremVal) | opaqueInfo (val : OpaqueVal) | quotInfo (val : QuotVal) | inductInfo (val : InductiveVal) | ctorInfo (val : ConstructorVal) | recInfo (val : RecursorVal) namespace ConstantInfo def toConstantVal : ConstantInfo → ConstantVal | defnInfo {toConstantVal := d, ..} => d | axiomInfo {toConstantVal := d, ..} => d | thmInfo {toConstantVal := d, ..} => d | opaqueInfo {toConstantVal := d, ..} => d | quotInfo {toConstantVal := d, ..} => d | inductInfo {toConstantVal := d, ..} => d | ctorInfo {toConstantVal := d, ..} => d | recInfo {toConstantVal := d, ..} => d def isUnsafe : ConstantInfo → Bool | defnInfo v => v.isUnsafe | axiomInfo v => v.isUnsafe | thmInfo v => false | opaqueInfo v => v.isUnsafe | quotInfo v => false | inductInfo v => v.isUnsafe | ctorInfo v => v.isUnsafe | recInfo v => v.isUnsafe def name (d : ConstantInfo) : Name := d.toConstantVal.name def lparams (d : ConstantInfo) : List Name := d.toConstantVal.lparams def type (d : ConstantInfo) : Expr := d.toConstantVal.type def value? : ConstantInfo → Option Expr | defnInfo {value := r, ..} => some r | thmInfo {value := r, ..} => some r | _ => none def hasValue : ConstantInfo → Bool | defnInfo {value := r, ..} => true | thmInfo {value := r, ..} => true | _ => false def value! : ConstantInfo → Expr | defnInfo {value := r, ..} => r | thmInfo {value := r, ..} => r | _ => panic! "declaration with value expected" def hints : ConstantInfo → ReducibilityHints | defnInfo {hints := r, ..} => r | _ => ReducibilityHints.opaque def isCtor : ConstantInfo → Bool | ctorInfo _ => true | _ => false @[extern "lean_instantiate_type_lparams"] constant instantiateTypeLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr @[extern "lean_instantiate_value_lparams"] constant instantiateValueLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr end ConstantInfo def mkRecName (declName : Name) : Name := Name.mkStr declName "rec" end Lean
2c47c6a3f81ce9c594fc41e622a0d7092052d4e1
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Deriving/Repr.lean
3f2a3950eebf13747341e3749edb1c8ee9e5f5a5
[ "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,132
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.Meta.Transform import Lean.Meta.Inductive import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util namespace Lean.Elab.Deriving.Repr open Lean.Parser.Term open Meta open Std def mkReprHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do let prec ← `(prec) let header ← mkHeader ctx `Repr 1 indVal return { header with binders := header.binders.push (← `(explicitBinderF| (prec : Nat))) } def mkBodyForStruct (ctx : Context) (header : Header) (indVal : InductiveVal) : TermElabM Syntax := do let ctorVal ← getConstInfoCtor indVal.ctors.head! let fieldNames ← getStructureFields (← getEnv) indVal.name let numParams := indVal.numParams let target := mkIdent header.targetNames[0] forallTelescopeReducing ctorVal.type fun xs _ => do let mut fields : Syntax ← `(Format.nil) let mut first := true if xs.size != numParams + fieldNames.size then throwError! "'deriving Repr' failed, unexpected number of fields in structure" for i in [:fieldNames.size] do let fieldName := fieldNames[i] let fieldNameLit := Syntax.mkStrLit (toString fieldName) let x := xs[numParams + i] if first then first := false else fields ← `($fields ++ "," ++ Format.line) if (← isType x <||> isProof x) then fields ← `($fields ++ $fieldNameLit ++ " := " ++ "_") else fields ← `($fields ++ $fieldNameLit ++ " := " ++ repr ($target.$(mkIdent fieldName):ident)) `(Format.bracket "{ " $fields:term " }") def mkBodyForInduct (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkAlts : TermElabM (Array Syntax) := do let mut alts := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) let mut ctorArgs := #[] let mut rhs := Syntax.mkStrLit (toString ctorInfo.name) rhs ← `(Format.text $rhs) -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.numParams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] let a := mkIdent (← mkFreshUserName `a) ctorArgs := ctorArgs.push a if (← inferType x).isAppOf indVal.name then rhs ← `($rhs ++ Format.line ++ $(mkIdent auxFunName):ident $a:ident maxPrec!) else rhs ← `($rhs ++ Format.line ++ reprArg $a) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*)) `(matchAltExpr| | $[$patterns:term],* => Repr.addAppParen (Format.group (Format.nest (if prec >= maxPrec! then 1 else 2) ($rhs:term))) prec) alts := alts.push alt return alts def mkBody (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do if isStructure (← getEnv) indVal.name then mkBodyForStruct ctx header indVal else mkBodyForInduct ctx header indVal auxFunName def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do let auxFunName ← ctx.auxFunNames[i] let indVal ← ctx.typeInfos[i] let header ← mkReprHeader ctx indVal let mut body ← mkBody ctx header indVal auxFunName if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx `Repr header.argNames body ← mkLet letDecls body let binders := header.binders if ctx.usePartial then `(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : Format := $body:term) else `(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : Format := $body:term) def mkMutualBlock (ctx : Context) : TermElabM Syntax := do let mut auxDefs := #[] for i in [:ctx.typeInfos.size] do auxDefs := auxDefs.push (← mkAuxFunction ctx i) `(mutual $auxDefs:command* end) private def mkReprInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do let ctx ← mkContext "repr" declNames[0] let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `Repr declNames) trace[Elab.Deriving.repr]! "\n{cmds}" return cmds open Command def mkReprInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) && declNames.size > 0 then let cmds ← liftTermElabM none <| mkReprInstanceCmds declNames cmds.forM elabCommand return true else return false builtin_initialize registerBuiltinDerivingHandler `Repr mkReprInstanceHandler registerTraceClass `Elab.Deriving.repr end Lean.Elab.Deriving.Repr
a11aa1cdbd57b2acc6272dc1372297c079dea1f1
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Data/Occurrences.lean
a12b7dc20a37013185783262bd1de8ada6f61417
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
810
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Lean inductive Occurrences | all | pos (idxs : List Nat) | neg (idxs : List Nat) namespace Occurrences instance : Inhabited Occurrences := ⟨all⟩ def contains : Occurrences → Nat → Bool | all, _ => true | pos idxs, idx => idxs.contains idx | neg idxs, idx => !idxs.contains idx def isAll : Occurrences → Bool | all => true | _ => false def beq : Occurrences → Occurrences → Bool | all, all => true | pos is₁, pos is₂ => is₁ == is₂ | neg is₁, neg is₂ => is₁ == is₂ | _, _ => false instance : BEq Occurrences := ⟨beq⟩ end Occurrences end Lean
a30a02e4b73a5eb030fb1d7cfae501dfd313f9c9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/disjointed.lean
ebb4a8605efd947f375c4ef805ec155b0680c3ef
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,193
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, Yaël Dillies -/ import order.partial_sups /-! # Consecutive differences of sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the way to make a sequence of elements into a sequence of disjoint elements with the same partial sups. For a sequence `f : ℕ → α`, this new sequence will be `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 ⊔ f 1)`. It is actually unique, as `disjointed_unique` shows. ## Main declarations * `disjointed f`: The sequence `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 ⊔ f 1)`, .... * `partial_sups_disjointed`: `disjointed f` has the same partial sups as `f`. * `disjoint_disjointed`: The elements of `disjointed f` are pairwise disjoint. * `disjointed_unique`: `disjointed f` is the only pairwise disjoint sequence having the same partial sups as `f`. * `supr_disjointed`: `disjointed f` has the same supremum as `f`. Limiting case of `partial_sups_disjointed`. We also provide set notation variants of some lemmas. ## TODO Find a useful statement of `disjointed_rec_succ`. One could generalize `disjointed` to any locally finite bot preorder domain, in place of `ℕ`. Related to the TODO in the module docstring of `order.partial_sups`. -/ variables {α β : Type*} section generalized_boolean_algebra variables [generalized_boolean_algebra α] /-- If `f : ℕ → α` is a sequence of elements, then `disjointed f` is the sequence formed by subtracting each element from the nexts. This is the unique disjoint sequence whose partial sups are the same as the original sequence. -/ def disjointed (f : ℕ → α) : ℕ → α | 0 := f 0 | (n + 1) := f (n + 1) \ (partial_sups f n) @[simp] lemma disjointed_zero (f : ℕ → α) : disjointed f 0 = f 0 := rfl lemma disjointed_succ (f : ℕ → α) (n : ℕ) : disjointed f (n + 1) = f (n + 1) \ (partial_sups f n) := rfl lemma disjointed_le_id : disjointed ≤ (id : (ℕ → α) → ℕ → α) := begin rintro f n, cases n, { refl }, { exact sdiff_le } end lemma disjointed_le (f : ℕ → α) : disjointed f ≤ f := disjointed_le_id f lemma disjoint_disjointed (f : ℕ → α) : pairwise (disjoint on disjointed f) := begin refine (symmetric.pairwise_on disjoint.symm _).2 (λ m n h, _), cases n, { exact (nat.not_lt_zero _ h).elim }, exact disjoint_sdiff_self_right.mono_left ((disjointed_le f m).trans (le_partial_sups_of_le f (nat.lt_add_one_iff.1 h))), end /-- An induction principle for `disjointed`. To define/prove something on `disjointed f n`, it's enough to define/prove it for `f n` and being able to extend through diffs. -/ def disjointed_rec {f : ℕ → α} {p : α → Sort*} (hdiff : ∀ ⦃t i⦄, p t → p (t \ f i)) : ∀ ⦃n⦄, p (f n) → p (disjointed f n) | 0 := id | (n + 1) := λ h, begin suffices H : ∀ k, p (f (n + 1) \ partial_sups f k), { exact H n }, rintro k, induction k with k ih, { exact hdiff h }, rw [partial_sups_succ, ←sdiff_sdiff_left], exact hdiff ih, end @[simp] lemma disjointed_rec_zero {f : ℕ → α} {p : α → Sort*} (hdiff : ∀ ⦃t i⦄, p t → p (t \ f i)) (h₀ : p (f 0)) : disjointed_rec hdiff h₀ = h₀ := rfl -- TODO: Find a useful statement of `disjointed_rec_succ`. lemma monotone.disjointed_eq {f : ℕ → α} (hf : monotone f) (n : ℕ) : disjointed f (n + 1) = f (n + 1) \ f n := by rw [disjointed_succ, hf.partial_sups_eq] @[simp] lemma partial_sups_disjointed (f : ℕ → α) : partial_sups (disjointed f) = partial_sups f := begin ext n, induction n with k ih, { rw [partial_sups_zero, partial_sups_zero, disjointed_zero] }, { rw [partial_sups_succ, partial_sups_succ, disjointed_succ, ih, sup_sdiff_self_right] } end /-- `disjointed f` is the unique sequence that is pairwise disjoint and has the same partial sups as `f`. -/ lemma disjointed_unique {f d : ℕ → α} (hdisj : pairwise (disjoint on d)) (hsups : partial_sups d = partial_sups f) : d = disjointed f := begin ext n, cases n, { rw [←partial_sups_zero d, hsups, partial_sups_zero, disjointed_zero] }, suffices h : d n.succ = partial_sups d n.succ \ partial_sups d n, { rw [h, hsups, partial_sups_succ, disjointed_succ, sup_sdiff, sdiff_self, bot_sup_eq] }, rw [partial_sups_succ, sup_sdiff, sdiff_self, bot_sup_eq, eq_comm, sdiff_eq_self_iff_disjoint], suffices h : ∀ m ≤ n, disjoint (partial_sups d m) (d n.succ), { exact h n le_rfl }, rintro m hm, induction m with m ih, { exact hdisj (nat.succ_ne_zero _).symm }, rw [partial_sups_succ, disjoint_iff, inf_sup_right, sup_eq_bot_iff, ←disjoint_iff, ←disjoint_iff], exact ⟨ih (nat.le_of_succ_le hm), hdisj (nat.lt_succ_of_le hm).ne⟩, end end generalized_boolean_algebra section complete_boolean_algebra variables [complete_boolean_algebra α] lemma supr_disjointed (f : ℕ → α) : (⨆ n, disjointed f n) = (⨆ n, f n) := supr_eq_supr_of_partial_sups_eq_partial_sups (partial_sups_disjointed f) lemma disjointed_eq_inf_compl (f : ℕ → α) (n : ℕ) : disjointed f n = f n ⊓ (⨅ i < n, (f i)ᶜ) := begin cases n, { rw [disjointed_zero, eq_comm, inf_eq_left], simp_rw le_infi_iff, exact λ i hi, (i.not_lt_zero hi).elim }, simp_rw [disjointed_succ, partial_sups_eq_bsupr, sdiff_eq, compl_supr], congr, ext i, rw nat.lt_succ_iff, end end complete_boolean_algebra /-! ### Set notation variants of lemmas -/ lemma disjointed_subset (f : ℕ → set α) (n : ℕ) : disjointed f n ⊆ f n := disjointed_le f n lemma Union_disjointed {f : ℕ → set α} : (⋃ n, disjointed f n) = (⋃ n, f n) := supr_disjointed f lemma disjointed_eq_inter_compl (f : ℕ → set α) (n : ℕ) : disjointed f n = f n ∩ (⋂ i < n, (f i)ᶜ) := disjointed_eq_inf_compl f n lemma preimage_find_eq_disjointed (s : ℕ → set α) (H : ∀ x, ∃ n, x ∈ s n) [∀ x n, decidable (x ∈ s n)] (n : ℕ) : (λ x, nat.find (H x)) ⁻¹' {n} = disjointed s n := by { ext x, simp [nat.find_eq_iff, disjointed_eq_inter_compl] }
c6f6b8871d5aa9b75b62c534e1b900bc9cf12aab
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/Frontend.lean
fbffcb803ee92711f243cd84295a75b42012e1e8
[ "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
4,756
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Elab.Import import Lean.Elab.Command import Lean.Util.Profile namespace Lean.Elab.Frontend structure State where commandState : Command.State parserState : Parser.ModuleParserState cmdPos : String.Pos commands : Array Syntax := #[] structure Context where inputCtx : Parser.InputContext abbrev FrontendM := ReaderT Context $ StateRefT State IO def setCommandState (commandState : Command.State) : FrontendM Unit := modify fun s => { s with commandState := commandState } @[inline] def runCommandElabM (x : Command.CommandElabM α) : FrontendM α := do let ctx ← read let s ← get let cmdCtx : Command.Context := { cmdPos := s.cmdPos, fileName := ctx.inputCtx.fileName, fileMap := ctx.inputCtx.fileMap } match (← liftM <| EIO.toIO' <| (x cmdCtx).run s.commandState) with | Except.error e => throw <| IO.Error.userError s!"unexpected internal error: {← e.toMessageData.toString}" | Except.ok (a, sNew) => setCommandState sNew; return a def elabCommandAtFrontend (stx : Syntax) : FrontendM Unit := do runCommandElabM do let infoTreeEnabled := (← getInfoState).enabled if checkTraceOption (← getOptions) `Elab.info then enableInfoTree Command.elabCommandTopLevel stx enableInfoTree infoTreeEnabled def updateCmdPos : FrontendM Unit := do modify fun s => { s with cmdPos := s.parserState.pos } def getParserState : FrontendM Parser.ModuleParserState := do pure (← get).parserState def getCommandState : FrontendM Command.State := do pure (← get).commandState def setParserState (ps : Parser.ModuleParserState) : FrontendM Unit := modify fun s => { s with parserState := ps } def setMessages (msgs : MessageLog) : FrontendM Unit := modify fun s => { s with commandState := { s.commandState with messages := msgs } } def getInputContext : FrontendM Parser.InputContext := do pure (← read).inputCtx def processCommand : FrontendM Bool := do updateCmdPos let cmdState ← getCommandState let ictx ← getInputContext let pstate ← getParserState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let pos := ictx.fileMap.toPosition pstate.pos match profileit "parsing" scope.opts fun _ => Parser.parseCommand ictx pmctx pstate cmdState.messages with | (cmd, ps, messages) => modify fun s => { s with commands := s.commands.push cmd } setParserState ps setMessages messages if Parser.isEOI cmd || Parser.isExitCommand cmd then pure true -- Done else profileitM IO.Error "elaboration" scope.opts <| elabCommandAtFrontend cmd pure false partial def processCommands : FrontendM Unit := do let done ← processCommand unless done do processCommands end Frontend open Frontend def IO.processCommands (inputCtx : Parser.InputContext) (parserState : Parser.ModuleParserState) (commandState : Command.State) : IO State := do let (_, s) ← (Frontend.processCommands.run { inputCtx := inputCtx }).run { commandState := commandState, parserState := parserState, cmdPos := parserState.pos } pure s def process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment × MessageLog) := do let fileName := fileName.getD "<input>" let inputCtx := Parser.mkInputContext input fileName let s ← IO.processCommands inputCtx { : Parser.ModuleParserState } (Command.mkState env {} opts) pure (s.commandState.env, s.commandState.messages) builtin_initialize registerOption `printMessageEndPos { defValue := false, descr := "print end position of each message in addition to start position" } registerTraceClass `Elab.info def getPrintMessageEndPos (opts : Options) : Bool := opts.getBool `printMessageEndPos false @[export lean_run_frontend] def runFrontend (input : String) (opts : Options) (fileName : String) (mainModuleName : Name) (trustLevel : UInt32 := 0) : IO (Environment × Bool) := do let inputCtx := Parser.mkInputContext input fileName let (header, parserState, messages) ← Parser.parseHeader inputCtx let (env, messages) ← processHeader header opts messages inputCtx trustLevel let env := env.setMainModule mainModuleName let s ← IO.processCommands inputCtx parserState (Command.mkState env messages opts) for msg in s.commandState.messages.toList do IO.print (← msg.toString (includeEndPos := getPrintMessageEndPos opts)) pure (s.commandState.env, !s.commandState.messages.hasErrors) end Lean.Elab
5d2a106ccd43b3740dbd39e457e772e2fb36fe4e
5aaf2c36656c8e760e9c8e4d3b19422402d70634
/src/tut1.lean
3214e199cd3fb140cad684dc9e27fac8bc84cc49
[]
no_license
BassemSafieldeen/Lean-tutorials
535746ccf8d4419419f4fcb544c1687dc564b537
031a14fa9700898e9895c9d41be8495275618c46
refs/heads/main
1,673,748,866,999
1,605,459,118,000
1,605,459,118,000
307,048,364
0
0
null
null
null
null
UTF-8
Lean
false
false
634
lean
---- STRUCTURES IN LEAN /-- A type is a foo if the specified axioms are satisfied: -/ class foo (α : Type) := (axiom_1 : 4 = 4) (axiom_2 : 5 = 5) /-- Some foos are also bar if an additional axiom is satisfied: -/ class bar (α : Type) extends foo α := (axiom_3 : 6 = 6) /-- Let's prove a theorem. Theorem: If a type α is bar it is also foo. -/ theorem foo_of_bar (α : Type) : bar α → foo α := begin intro, split, {refl}, {refl}, end /-- Let's prove another theorem: If a type α is foo then 4 = 4. -/ theorem four_eq_four_of_foo (α : Type) : foo α → 4 = 4 := begin intro, exact a.axiom_1, end
58a1ffbd36faaef9ccc3352b1511eab01a294823
246309748072bf9f8da313401699689ebbecd94d
/src/topology/sheaves/local_predicate.lean
2c8f850743050678825f5b959a17e10b33964a48
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
13,374
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import topology.sheaves.sheaf_of_functions import topology.sheaves.stalks /-! # Functions satisfying a local predicate form a sheaf. At this stage, in `topology/sheaves/sheaf_of_functions.lean` we've proved that not-necessarily-continuous functions from a topological space into some type (or type family) form a sheaf. Why do the continuous functions form a sheaf? The point is just that continuity is a local condition, so one can use the lifting condition for functions to provide a candidate lift, then verify that the lift is actually continuous by using the factorisation condition for the lift (which guarantees that on each open set it agrees with the functions being lifted, which were assumed to be continuous). This file abstracts this argument to work for any collection of dependent functions on a topological space satisfying a "local predicate". As an application, we check that continuity is a local predicate in this sense, and provide * `Top.sheaf_condition.to_Top`: continuous functions into a topological space form a sheaf A sheaf constructed in this way has a natural map `stalk_to_fiber` from the stalks to the types in the ambient type family. We give conditions sufficient to show that this map is injective and/or surjective. -/ universe v noncomputable theory variables {X : Top.{v}} variables (T : X → Type v) open topological_space open opposite open category_theory open category_theory.limits namespace Top /-- Given a topological space `X : Top` and a type family `T : X → Type`, a `P : prelocal_predicate T` consists of: * a family of predicates `P.pred`, one for each `U : opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate. -/ structure prelocal_predicate := (pred : Π {U : opens X}, (Π x : U, T x) → Prop) (res : ∀ {U V : opens X} (i : U ⟶ V) (f : Π x : V, T x) (h : pred f), pred (λ x : U, f (i x))) variables (X) /-- Continuity is a "prelocal" predicate on functions to a fixed topological space `T`. -/ @[simps] def continuous_prelocal (T : Top.{v}) : prelocal_predicate (λ x : X, T) := { pred := λ U f, continuous f, res := λ U V i f h, continuous.comp h (opens.open_embedding_of_le (le_of_hom i)).continuous, } /-- Satisfying the inhabited linter. -/ instance inhabited_prelocal_predicate (T : Top.{v}) : inhabited (prelocal_predicate (λ x : X, T)) := ⟨continuous_prelocal X T⟩ variables {X} /-- Given a topological space `X : Top` and a type family `T : X → Type`, a `P : local_predicate T` consists of: * a family of predicates `P.pred`, one for each `U : opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate, and * a proof that given some `f : Π x : U, T x`, if for every `x : U` we can find an open set `x ∈ V ≤ U` so that the restriction of `f` to `V` satisfies the predicate, then `f` itself satisfies the predicate. -/ structure local_predicate extends prelocal_predicate T := (locality : ∀ {U : opens X} (f : Π x : U, T x) (w : ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (i : V ⟶ U), pred (λ x : V, f (i x : U))), pred f) variables (X) /-- Continuity is a "local" predicate on functions to a fixed topological space `T`. -/ def continuous_local (T : Top.{v}) : local_predicate (λ x : X, T) := { locality := λ U f w, begin apply continuous_iff_continuous_at.2, intro x, specialize w x, rcases w with ⟨V, m, i, w⟩, dsimp at w, rw continuous_iff_continuous_at at w, specialize w ⟨x, m⟩, simpa using (opens.open_embedding_of_le (le_of_hom i)).continuous_at_iff.1 w, end, ..continuous_prelocal X T } /-- Satisfying the inhabited linter. -/ instance inhabited_local_predicate (T : Top.{v}) : inhabited (local_predicate _) := ⟨continuous_local X T⟩ variables {X T} /-- Given a `P : prelocal_predicate`, we can always construct a `local_predicate` by asking that the condition from `P` holds locally near every point. -/ def prelocal_predicate.sheafify {T : X → Type v} (P : prelocal_predicate T) : local_predicate T := { pred := λ U f, ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (i : V ⟶ U), P.pred (λ x : V, f (i x : U)), res := λ V U i f w x, begin specialize w (i x), rcases w with ⟨V', m', i', p⟩, refine ⟨V ⊓ V', ⟨x.2,m'⟩, opens.inf_le_left _ _, _⟩, convert P.res (opens.inf_le_right V V') _ p, end, locality := λ U f w x, begin specialize w x, rcases w with ⟨V, m, i, p⟩, specialize p ⟨x.1, m⟩, rcases p with ⟨V', m', i', p'⟩, exact ⟨V', m', i' ≫ i, p'⟩, end } lemma prelocal_predicate.sheafify_of {T : X → Type v} {P : prelocal_predicate T} {U : opens X} {f : Π x : U, T x} (h : P.pred f) : P.sheafify.pred f := λ x, ⟨U, x.2, 𝟙 _, by { convert h, ext ⟨y, w⟩, refl, }⟩ /-- The subpresheaf of dependent functions on `X` satisfying the "pre-local" predicate `P`. -/ @[simps] def subpresheaf_to_Types (P : prelocal_predicate T) : presheaf (Type v) X := { obj := λ U, { f : Π x : unop U, T x // P.pred f }, map := λ U V i f, ⟨λ x, f.1 (i.unop x), P.res i.unop f.1 f.2⟩ }. namespace subpresheaf_to_Types variables (P : prelocal_predicate T) /-- The natural transformation including the subpresheaf of functions satisfying a local predicate into the presheaf of all functions. -/ def subtype : subpresheaf_to_Types P ⟶ presheaf_to_Types X T := { app := λ U f, f.1 } open Top.sheaf_condition /-- The natural transformation from the sheaf condition diagram for functions satisfying a local predicate to the sheaf condition diagram for arbitrary functions, given by forgetting that the local predicate holds. -/ def diagram_subtype {ι : Type v} (U : ι → opens X) : diagram (subpresheaf_to_Types P) U ⟶ diagram (presheaf_to_Types X T) U := { app := λ j, walking_parallel_pair.rec_on j (pi.map (λ i f, f.1)) (pi.map (λ p f, f.1)), naturality' := by rintro ⟨_|_⟩ ⟨_|_⟩ f; cases f; refl, } /-- The functions satisfying a local predicate satisfy the sheaf condition. -/ def sheaf_condition (P : local_predicate T) : sheaf_condition (subpresheaf_to_Types P.to_prelocal_predicate) := λ ι U, begin refine fork.is_limit.mk _ _ _ _, { intros s f, fsplit, -- First, we use the fact that not necessarily continuous functions form a sheaf, -- to provide the lift. { let s' := (cones.postcompose (diagram_subtype P.to_prelocal_predicate U)).obj s, exact (to_Types X T U).lift s' f, }, -- Second, we need to do the actual work, proving this lift satisfies the predicate. { dsimp, -- We work locally, apply P.locality, -- so that once we're at a particular point `x`, we can select some open set `x ∈ U i`. rintro ⟨x, mem⟩, change x ∈ (supr U).val at mem, simp at mem, choose i hi using mem, use U i, use hi, use (opens.le_supr U i), -- Now our goal is to show that the previously chosen lift, -- when restricted to that `U i`, satisfies the predicate. -- This follows from the factorisation condition, and -- the fact that the underlying presheaf is a presheaf of functions satisfying the predicate. let s' := (cones.postcompose (diagram_subtype P.to_prelocal_predicate U)).obj s, have fac_i := ((to_Types X T U).fac s' walking_parallel_pair.zero) =≫ pi.π _ i, simp only [sheaf_condition.res, limit.lift_π, cones.postcompose_obj_π, sheaf_condition.fork_π_app_walking_parallel_pair_zero, fan.mk_π_app, nat_trans.comp_app, category.assoc] at fac_i, have fac_i_f := congr_fun fac_i f, simp only [diagram_subtype, discrete.nat_trans_app, types_comp_apply, presheaf_to_Types_map, limit.map_π, subtype.val_eq_coe] at fac_i_f, erw fac_i_f, apply subtype.property, }, }, { -- Proving the factorisation condition is straightforward: -- we observe that checking equality of functions satisfying a predicate reduces to -- checking equality of the underlying functions, -- and use the factorisation condition for the sheaf condition for functions. intros s, ext i f : 2, apply subtype.coe_injective, exact congr_fun (((to_Types X T U).fac _ walking_parallel_pair.zero) =≫ pi.π _ i) _, }, { -- Similarly for proving the uniqueness condition, after a certain amount of bookkeeping. intros s m w, ext f : 1, apply subtype.coe_injective, let s' := (cones.postcompose (diagram_subtype P.to_prelocal_predicate U)).obj s, refine congr_fun ((to_Types X T U).uniq s' _ _) f, -- We "just" need to fix up our `w` to match the missing `w` argument. -- Unfortunately, it's still gross. intro j, specialize w j, dsimp [s'], rw ←w, clear w, simp only [category.assoc], rcases j with ⟨_|_⟩, { apply limit.hom_ext, intro i, simp only [category.assoc, limit.map_π], ext f' ⟨x, mem⟩, refl, }, { apply limit.hom_ext, intro i, simp only [category.assoc, limit.map_π], ext f' ⟨x, mem⟩, refl, }, }, end end subpresheaf_to_Types /-- The subsheaf of the sheaf of all dependently typed functions satisfying the local predicate `P`. -/ @[simps] def subsheaf_to_Types (P : local_predicate T) : sheaf (Type v) X := { presheaf := subpresheaf_to_Types P.to_prelocal_predicate, sheaf_condition := subpresheaf_to_Types.sheaf_condition P }. /-- There is a canonical map from the stalk to the original fiber. -/ def stalk_to_fiber (P : local_predicate T) (x : X) : (subsheaf_to_Types P).presheaf.stalk x ⟶ T x := begin refine colimit.desc _ { X := T x, ι := { app := λ U f, _, naturality' := _ } }, { exact f.1 ⟨x, (unop U).2⟩, }, { tidy, } end @[simp] lemma stalk_to_fiber_germ (P : local_predicate T) (U : opens X) (x : U) (f) : stalk_to_fiber P x ((subsheaf_to_Types P).presheaf.germ x f) = f.1 x := begin dsimp [presheaf.germ, stalk_to_fiber], cases x, simp, refl, end /-- The `stalk_to_fiber` map is surjective at `x` if every point in the fiber `T x` has an allowed section passing through it. -/ lemma stalk_to_fiber_surjective (P : local_predicate T) (x : X) (w : ∀ (t : T x), ∃ (U : open_nhds x) (f : Π y : U.1, T y) (h : P.pred f), f ⟨x, U.2⟩ = t) : function.surjective (stalk_to_fiber P x) := λ t, begin rcases w t with ⟨U, f, h, rfl⟩, fsplit, { exact (subsheaf_to_Types P).presheaf.germ ⟨x, U.2⟩ ⟨f, h⟩, }, { exact stalk_to_fiber_germ _ _ _ ⟨f, h⟩, } end /-- The `stalk_to_fiber` map is injective at `x` if any two allowed sections which agree at `x` agree on some neighborhood of `x`. -/ lemma stalk_to_fiber_injective (P : local_predicate T) (x : X) (w : ∀ (U V : open_nhds x) (fU : Π y : U.1, T y) (hU : P.pred fU) (fV : Π y : V.1, T y) (hV : P.pred fV) (e : fU ⟨x, U.2⟩ = fV ⟨x, V.2⟩), ∃ (W : open_nhds x) (iU : W ⟶ U) (iV : W ⟶ V), ∀ (w : W.1), fU (iU w : U.1) = fV (iV w : V.1)) : function.injective (stalk_to_fiber P x) := λ tU tV h, begin -- We promise to provide all the ingredients of the proof later: let Q : ∃ (W : (open_nhds x)ᵒᵖ) (s : Π w : (unop W).1, T w) (hW : P.pred s), tU = quot.mk _ ⟨W, ⟨s, hW⟩⟩ ∧ tV = quot.mk _ ⟨W, ⟨s, hW⟩⟩ := _, { choose W s hW e using Q, exact e.1.trans e.2.symm, }, -- Then use induction to pick particular representatives of `tU tV : stalk x` induction tU, induction tV, { -- Decompose everything into its constituent parts: dsimp, rcases tU with ⟨U, ⟨fU, hU⟩⟩, rcases tV with ⟨V, ⟨fV, hV⟩⟩, specialize w (unop U) (unop V) fU hU fV hV h, rcases w with ⟨W, iU, iV, w⟩, -- and put it back together again in the correct order. refine ⟨(op W), (λ w, fU (iU w : (unop U).1)), P.res _ _ hU, _⟩, exact ⟨quot.sound ⟨iU.op, subtype.eq rfl⟩, quot.sound ⟨iV.op, subtype.eq (funext w)⟩⟩, }, { refl, }, -- proof irrelevance { refl, }, -- proof irrelevance end /-- Some repackaging: the presheaf of functions satisfying `continuous_prelocal` is just the same thing as the presheaf of continuous functions. -/ def subpresheaf_continuous_prelocal_iso_presheaf_to_Top (T : Top.{v}) : subpresheaf_to_Types (continuous_prelocal X T) ≅ presheaf_to_Top X T := nat_iso.of_components (λ X, { hom := by { rintro ⟨f, c⟩, exact ⟨f, c⟩, }, inv := by { rintro ⟨f, c⟩, exact ⟨f, c⟩, }, hom_inv_id' := by { ext ⟨f, p⟩ x, refl, }, inv_hom_id' := by { ext ⟨f, p⟩ x, refl, }, }) (by tidy) /-- The sheaf of continuous functions on `X` with values in a space `T`. -/ def sheaf_to_Top (T : Top.{v}) : sheaf (Type v) X := { presheaf := presheaf_to_Top X T, sheaf_condition := sheaf_condition_equiv_of_iso (subpresheaf_continuous_prelocal_iso_presheaf_to_Top T) (subpresheaf_to_Types.sheaf_condition (continuous_local X T)), } end Top
e518a205b2635bd330b9cf68971464342d7a62cd
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/reflect.lean
924f2d4df3e7e1211ca0390ac43ccb2ce59e1926
[ "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
38
lean
#eval to_string $ (reflect 0).to_expr