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
65fd4e5664cc6fc1000f0a0bd9e10c9faef29ac7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/traversable/lemmas.lean
c3814364d2cfd1f3a27d5c0e279c6f60895ab322
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,063
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Lemmas about traversing collections. Inspired by: The Essence of the Iterator Pattern Jeremy Gibbons and Bruno César dos Santos Oliveira In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377−402. 2009. <http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf> -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.traversable.basic import Mathlib.control.applicative import Mathlib.PostPort universes u namespace Mathlib namespace traversable /-- The natural applicative transformation from the identity functor to `F`, defined by `pure : Π {α}, α → F α`. -/ def pure_transformation (F : Type u → Type u) [Applicative F] [is_lawful_applicative F] : applicative_transformation id F := applicative_transformation.mk pure sorry sorry @[simp] theorem pure_transformation_apply (F : Type u → Type u) [Applicative F] [is_lawful_applicative F] {α : Type u} (x : id α) : coe_fn (pure_transformation F) α x = pure x := rfl theorem map_eq_traverse_id {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {β : Type u} {γ : Type u} (f : β → γ) : Functor.map f = traverse (id.mk ∘ f) := funext fun (y : t β) => Eq.symm (is_lawful_traversable.traverse_eq_map_id f y) theorem map_traverse {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} [Applicative F] [is_lawful_applicative F] {α : Type u} {β : Type u} {γ : Type u} (g : α → F β) (f : β → γ) (x : t α) : Functor.map f <$> traverse g x = traverse (Functor.map f ∘ g) x := sorry theorem traverse_map {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} [Applicative F] [is_lawful_applicative F] {α : Type u} {β : Type u} {γ : Type u} (f : β → F γ) (g : α → β) (x : t α) : traverse f (g <$> x) = traverse (f ∘ g) x := sorry theorem pure_traverse {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} [Applicative F] [is_lawful_applicative F] {α : Type u} (x : t α) : traverse pure x = pure x := eq.mp (Eq._oldrec (Eq.refl (traverse pure x = pure (traverse id.mk x))) (is_lawful_traversable.id_traverse x)) (Eq.symm (is_lawful_traversable.naturality (pure_transformation F) id.mk x)) theorem id_sequence {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {α : Type u} (x : t α) : sequence (id.mk <$> x) = id.mk x := sorry theorem comp_sequence {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} (x : t (F (G α))) : sequence (functor.comp.mk <$> x) = functor.comp.mk (sequence <$> sequence x) := sorry theorem naturality' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} (η : applicative_transformation F G) (x : t (F α)) : coe_fn η (t α) (sequence x) = sequence (coe_fn η α <$> x) := sorry theorem traverse_id {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {α : Type u} : traverse id.mk = id.mk := sorry theorem traverse_comp {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} {γ : Type u} (g : α → F β) (h : β → G γ) : traverse (functor.comp.mk ∘ Functor.map h ∘ g) = functor.comp.mk ∘ Functor.map (traverse h) ∘ traverse g := sorry theorem traverse_eq_map_id' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {β : Type u} {γ : Type u} (f : β → γ) : traverse (id.mk ∘ f) = id.mk ∘ Functor.map f := sorry -- @[functor_norm] theorem traverse_map' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {G : Type u → Type u} [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} {γ : Type u} (g : α → β) (h : β → G γ) : traverse (h ∘ g) = traverse h ∘ Functor.map g := sorry theorem map_traverse' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {G : Type u → Type u} [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} {γ : Type u} (g : α → G β) (h : β → γ) : traverse (Functor.map h ∘ g) = Functor.map (Functor.map h) ∘ traverse g := sorry theorem naturality_pf {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} (η : applicative_transformation F G) (f : α → F β) : traverse (coe_fn η β ∘ f) = coe_fn η (t β) ∘ traverse f := sorry
b28cf09516ec3edef2d0c4957841624980a18f91
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/unusedWarningAtStructUpdate.lean
e75f7e85a6f1f287923e8539bab156c24e19605d
[ "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
174
lean
set_option linter.unusedVariables true structure Ctx where s : String def f (s : String) : ReaderT Ctx Id Unit := withReader (fun ctx => { ctx with s := s }) (pure ())
64603066869c45ce4066846d9130692fc0592630
63abd62053d479eae5abf4951554e1064a4c45b4
/src/analysis/normed_space/bounded_linear_maps.lean
91d1a39711935f054404220b634619f70117a1e8
[ "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
20,563
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Continuous linear functions -- functions between normed vector spaces which are bounded and linear. -/ import analysis.normed_space.multilinear noncomputable theory open_locale classical big_operators topological_space open filter (tendsto) open metric variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] /-- A function `f` satisfies `is_bounded_linear_map 𝕜 f` if it is linear and satisfies the inequality `∥ f x ∥ ≤ M * ∥ x ∥` for some positive constant `M`. -/ structure is_bounded_linear_map (𝕜 : Type*) [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E → F) extends is_linear_map 𝕜 f : Prop := (bound : ∃ M, 0 < M ∧ ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥) lemma is_linear_map.with_bound {f : E → F} (hf : is_linear_map 𝕜 f) (M : ℝ) (h : ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥) : is_bounded_linear_map 𝕜 f := ⟨ hf, classical.by_cases (assume : M ≤ 0, ⟨1, zero_lt_one, assume x, le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩) (assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩ /-- A continuous linear map satisfies `is_bounded_linear_map` -/ lemma continuous_linear_map.is_bounded_linear_map (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 f := { bound := f.bound, ..f.to_linear_map.is_linear } namespace is_bounded_linear_map /-- Construct a linear map from a function `f` satisfying `is_bounded_linear_map 𝕜 f`. -/ def to_linear_map (f : E → F) (h : is_bounded_linear_map 𝕜 f) : E →ₗ[𝕜] F := (is_linear_map.mk' _ h.to_is_linear_map) /-- Construct a continuous linear map from is_bounded_linear_map -/ def to_continuous_linear_map {f : E → F} (hf : is_bounded_linear_map 𝕜 f) : E →L[𝕜] F := { cont := let ⟨C, Cpos, hC⟩ := hf.bound in linear_map.continuous_of_bound _ C hC, ..to_linear_map f hf} lemma zero : is_bounded_linear_map 𝕜 (λ (x:E), (0:F)) := (0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map 𝕜 (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] lemma fst : is_bounded_linear_map 𝕜 (λ x : E × F, x.1) := begin refine (linear_map.fst 𝕜 E F).is_linear.with_bound 1 (λx, _), rw one_mul, exact le_max_left _ _ end lemma snd : is_bounded_linear_map 𝕜 (λ x : E × F, x.2) := begin refine (linear_map.snd 𝕜 E F).is_linear.with_bound 1 (λx, _), rw one_mul, exact le_max_right _ _ end variables { f g : E → F } lemma smul (c : 𝕜) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, c • f e) := let ⟨hlf, M, hMp, hM⟩ := hf in (c • hlf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x, calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x) ... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (hM _) (norm_nonneg _) ... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm lemma neg (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1 : 𝕜) • f e), { funext, simp }, exact smul (-1) hf end lemma add (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e + g e) := let ⟨hlf, Mf, hMfp, hMf⟩ := hf in let ⟨hlg, Mg, hMgp, hMg⟩ := hg in (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x, calc ∥f x + g x∥ ≤ Mf * ∥x∥ + Mg * ∥x∥ : norm_add_le_of_le (hMf x) (hMg x) ... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul lemma sub (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e - g e) := add hf (neg hg) lemma comp {g : F → G} (hg : is_bounded_linear_map 𝕜 g) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (g ∘ f) := (hg.to_continuous_linear_map.comp hf.to_continuous_linear_map).is_bounded_linear_map protected lemma tendsto (x : E) (hf : is_bounded_linear_map 𝕜 f) : tendsto f (𝓝 x) (𝓝 (f x)) := let ⟨hf, M, hMp, hM⟩ := hf in tendsto_iff_norm_tendsto_zero.2 $ squeeze_zero (assume e, norm_nonneg _) (assume e, calc ∥f e - f x∥ = ∥hf.mk' f (e - x)∥ : by rw (hf.mk' _).map_sub e x; refl ... ≤ M * ∥e - x∥ : hM (e - x)) (suffices tendsto (λ (e : E), M * ∥e - x∥) (𝓝 x) (𝓝 (M * 0)), by simpa, tendsto_const_nhds.mul (lim_norm _)) lemma continuous (hf : is_bounded_linear_map 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λ _, hf.tendsto _ lemma lim_zero_bounded_linear_map (hf : is_bounded_linear_map 𝕜 f) : tendsto f (𝓝 0) (𝓝 0) := (hf.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 hf.continuous 0 section open asymptotics filter theorem is_O_id {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := h.bound in is_O.of_bound _ (mem_sets_of_superset univ_mem_sets (λ x _, hM x)) theorem is_O_comp {E : Type*} {g : F → G} (hg : is_bounded_linear_map 𝕜 g) {f : E → F} (l : filter E) : is_O (λ x', g (f x')) f l := (hg.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := is_O_comp h l end end is_bounded_linear_map section variables {ι : Type*} [decidable_eq ι] [fintype ι] /-- Taking the cartesian product of two continuous linear maps is a bounded linear operation. -/ lemma is_bounded_linear_map_prod_iso : is_bounded_linear_map 𝕜 (λ(p : (E →L[𝕜] F) × (E →L[𝕜] G)), (p.1.prod p.2 : (E →L[𝕜] (F × G)))) := begin refine is_linear_map.with_bound ⟨λu v, rfl, λc u, rfl⟩ 1 (λp, _), simp only [norm, one_mul], refine continuous_linear_map.op_norm_le_bound _ (le_trans (norm_nonneg _) (le_max_left _ _)) (λu, _), simp only [norm, continuous_linear_map.prod, max_le_iff], split, { calc ∥p.1 u∥ ≤ ∥p.1∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _ ... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) }, { calc ∥p.2 u∥ ≤ ∥p.2∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _ ... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ : mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _) } end /-- Taking the cartesian product of two continuous multilinear maps is a bounded linear operation. -/ lemma is_bounded_linear_map_prod_multilinear {E : ι → Type*} [∀i, normed_group (E i)] [∀i, normed_space 𝕜 (E i)] : is_bounded_linear_map 𝕜 (λ p : (continuous_multilinear_map 𝕜 E F) × (continuous_multilinear_map 𝕜 E G), p.1.prod p.2) := { map_add := λ p₁ p₂, by { ext1 m, refl }, map_smul := λ c p, by { ext1 m, refl }, bound := ⟨1, zero_lt_one, λ p, begin rw one_mul, apply continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λ m, _), rw [continuous_multilinear_map.prod_apply, norm_prod_le_iff], split, { exact le_trans (p.1.le_op_norm m) (mul_le_mul_of_nonneg_right (norm_fst_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) }, { exact le_trans (p.2.le_op_norm m) (mul_le_mul_of_nonneg_right (norm_snd_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) }, end⟩ } /-- Given a fixed continuous linear map `g`, associating to a continuous multilinear map `f` the continuous multilinear map `f (g m₁, ..., g mₙ)` is a bounded linear operation. -/ lemma is_bounded_linear_map_continuous_multilinear_map_comp_linear (g : G →L[𝕜] E) : is_bounded_linear_map 𝕜 (λ f : continuous_multilinear_map 𝕜 (λ (i : ι), E) F, f.comp_continuous_linear_map (λ _, g)) := begin refine is_linear_map.with_bound ⟨λ f₁ f₂, by { ext m, refl }, λ c f, by { ext m, refl }⟩ (∥g∥ ^ (fintype.card ι)) (λ f, _), apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _), { apply_rules [mul_nonneg, pow_nonneg, norm_nonneg] }, calc ∥f (g ∘ m)∥ ≤ ∥f∥ * ∏ i, ∥g (m i)∥ : f.le_op_norm _ ... ≤ ∥f∥ * ∏ i, (∥g∥ * ∥m i∥) : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), exact finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, g.le_op_norm _) end ... = ∥g∥ ^ fintype.card ι * ∥f∥ * ∏ i, ∥m i∥ : by { simp [finset.prod_mul_distrib, finset.card_univ], ring } end end section bilinear_map variable (𝕜) /-- A map `f : E × F → G` satisfies `is_bounded_bilinear_map 𝕜 f` if it is bilinear and continuous. -/ structure is_bounded_bilinear_map (f : E × F → G) : Prop := (add_left : ∀(x₁ x₂ : E) (y : F), f (x₁ + x₂, y) = f (x₁, y) + f (x₂, y)) (smul_left : ∀(c : 𝕜) (x : E) (y : F), f (c • x, y) = c • f (x,y)) (add_right : ∀(x : E) (y₁ y₂ : F), f (x, y₁ + y₂) = f (x, y₁) + f (x, y₂)) (smul_right : ∀(c : 𝕜) (x : E) (y : F), f (x, c • y) = c • f (x,y)) (bound : ∃C>0, ∀(x : E) (y : F), ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥) variable {𝕜} variable {f : E × F → G} protected lemma is_bounded_bilinear_map.is_O (h : is_bounded_bilinear_map 𝕜 f) : asymptotics.is_O f (λ p : E × F, ∥p.1∥ * ∥p.2∥) ⊤ := let ⟨C, Cpos, hC⟩ := h.bound in asymptotics.is_O.of_bound _ $ filter.eventually_of_forall $ λ ⟨x, y⟩, by simpa [mul_assoc] using hC x y lemma is_bounded_bilinear_map.is_O_comp {α : Type*} (H : is_bounded_bilinear_map 𝕜 f) {g : α → E} {h : α → F} {l : filter α} : asymptotics.is_O (λ x, f (g x, h x)) (λ x, ∥g x∥ * ∥h x∥) l := H.is_O.comp_tendsto le_top protected lemma is_bounded_bilinear_map.is_O' (h : is_bounded_bilinear_map 𝕜 f) : asymptotics.is_O f (λ p : E × F, ∥p∥ * ∥p∥) ⊤ := h.is_O.trans (asymptotics.is_O_fst_prod'.norm_norm.mul asymptotics.is_O_snd_prod'.norm_norm) lemma is_bounded_bilinear_map.map_sub_left (h : is_bounded_bilinear_map 𝕜 f) {x y : E} {z : F} : f (x - y, z) = f (x, z) - f(y, z) := calc f (x - y, z) = f (x + (-1 : 𝕜) • y, z) : by simp [sub_eq_add_neg] ... = f (x, z) + (-1 : 𝕜) • f (y, z) : by simp only [h.add_left, h.smul_left] ... = f (x, z) - f (y, z) : by simp [sub_eq_add_neg] lemma is_bounded_bilinear_map.map_sub_right (h : is_bounded_bilinear_map 𝕜 f) {x : E} {y z : F} : f (x, y - z) = f (x, y) - f (x, z) := calc f (x, y - z) = f (x, y + (-1 : 𝕜) • z) : by simp [sub_eq_add_neg] ... = f (x, y) + (-1 : 𝕜) • f (x, z) : by simp only [h.add_right, h.smul_right] ... = f (x, y) - f (x, z) : by simp [sub_eq_add_neg] lemma is_bounded_bilinear_map.is_bounded_linear_map_left (h : is_bounded_bilinear_map 𝕜 f) (y : F) : is_bounded_linear_map 𝕜 (λ x, f (x, y)) := { map_add := λ x x', h.add_left _ _ _, map_smul := λ c x, h.smul_left _ _ _, bound := begin rcases h.bound with ⟨C, C_pos, hC⟩, refine ⟨C * (∥y∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ x, _⟩, have : ∥y∥ ≤ ∥y∥ + 1, by simp [zero_le_one], calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y ... ≤ C * ∥x∥ * (∥y∥ + 1) : by apply_rules [norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos, mul_nonneg] ... = C * (∥y∥ + 1) * ∥x∥ : by ring end } lemma is_bounded_bilinear_map.is_bounded_linear_map_right (h : is_bounded_bilinear_map 𝕜 f) (x : E) : is_bounded_linear_map 𝕜 (λ y, f (x, y)) := { map_add := λ y y', h.add_right _ _ _, map_smul := λ c y, h.smul_right _ _ _, bound := begin rcases h.bound with ⟨C, C_pos, hC⟩, refine ⟨C * (∥x∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ y, _⟩, have : ∥x∥ ≤ ∥x∥ + 1, by simp [zero_le_one], calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y ... ≤ C * (∥x∥ + 1) * ∥y∥ : by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos] end } lemma is_bounded_bilinear_map_smul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × E), p.1 • p.2) := { add_left := add_smul, smul_left := λc x y, by simp [smul_smul], add_right := smul_add, smul_right := λc x y, by simp [smul_smul, mul_comm], bound := ⟨1, zero_lt_one, λx y, by simp [norm_smul]⟩ } lemma is_bounded_bilinear_map_smul_algebra {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜' × E), p.1 • p.2) := { add_left := add_smul, smul_left := λ c x y, by simp [smul_assoc], add_right := smul_add, smul_right := λ c x y, by simp [smul_assoc, smul_algebra_smul_comm], bound := ⟨1, zero_lt_one, λ x y, by simp [norm_smul] ⟩ } lemma is_bounded_bilinear_map_mul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_smul lemma is_bounded_bilinear_map_comp : is_bounded_bilinear_map 𝕜 (λ(p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) := { add_left := λx₁ x₂ y, begin ext z, change y (x₁ z + x₂ z) = y (x₁ z) + y (x₂ z), rw y.map_add end, smul_left := λc x y, begin ext z, change y (c • (x z)) = c • y (x z), rw continuous_linear_map.map_smul end, add_right := λx y₁ y₂, rfl, smul_right := λc x y, rfl, bound := ⟨1, zero_lt_one, λx y, calc ∥continuous_linear_map.comp ((x, y).snd) ((x, y).fst)∥ ≤ ∥y∥ * ∥x∥ : continuous_linear_map.op_norm_comp_le _ _ ... = 1 * ∥x∥ * ∥ y∥ : by ring ⟩ } lemma continuous_linear_map.is_bounded_linear_map_comp_left (g : continuous_linear_map 𝕜 F G) : is_bounded_linear_map 𝕜 (λ(f : E →L[𝕜] F), continuous_linear_map.comp g f) := is_bounded_bilinear_map_comp.is_bounded_linear_map_left _ lemma continuous_linear_map.is_bounded_linear_map_comp_right (f : continuous_linear_map 𝕜 E F) : is_bounded_linear_map 𝕜 (λ(g : F →L[𝕜] G), continuous_linear_map.comp g f) := is_bounded_bilinear_map_comp.is_bounded_linear_map_right _ lemma is_bounded_bilinear_map_apply : is_bounded_bilinear_map 𝕜 (λp : (E →L[𝕜] F) × E, p.1 p.2) := { add_left := by simp, smul_left := by simp, add_right := by simp, smul_right := by simp, bound := ⟨1, zero_lt_one, by simp [continuous_linear_map.le_op_norm]⟩ } /-- The function `continuous_linear_map.smul_right`, associating to a continuous linear map `f : E → 𝕜` and a scalar `c : F` the tensor product `f ⊗ c` as a continuous linear map from `E` to `F`, is a bounded bilinear map. -/ lemma is_bounded_bilinear_map_smul_right : is_bounded_bilinear_map 𝕜 (λp, (continuous_linear_map.smul_right : (E →L[𝕜] 𝕜) → F → (E →L[𝕜] F)) p.1 p.2) := { add_left := λm₁ m₂ f, by { ext z, simp [add_smul] }, smul_left := λc m f, by { ext z, simp [mul_smul] }, add_right := λm f₁ f₂, by { ext z, simp [smul_add] }, smul_right := λc m f, by { ext z, simp [smul_smul, mul_comm] }, bound := ⟨1, zero_lt_one, λm f, by simp⟩ } /-- The composition of a continuous linear map with a continuous multilinear map is a bounded bilinear operation. -/ lemma is_bounded_bilinear_map_comp_multilinear {ι : Type*} {E : ι → Type*} [decidable_eq ι] [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space 𝕜 (E i)] : is_bounded_bilinear_map 𝕜 (λ p : (F →L[𝕜] G) × (continuous_multilinear_map 𝕜 E F), p.1.comp_continuous_multilinear_map p.2) := { add_left := λ g₁ g₂ f, by { ext m, refl }, smul_left := λ c g f, by { ext m, refl }, add_right := λ g f₁ f₂, by { ext m, simp }, smul_right := λ c g f, by { ext m, simp }, bound := ⟨1, zero_lt_one, λ g f, begin apply continuous_multilinear_map.op_norm_le_bound _ _ (λm, _), { apply_rules [mul_nonneg, zero_le_one, norm_nonneg] }, calc ∥g (f m)∥ ≤ ∥g∥ * ∥f m∥ : g.le_op_norm _ ... ≤ ∥g∥ * (∥f∥ * ∏ i, ∥m i∥) : mul_le_mul_of_nonneg_left (f.le_op_norm _) (norm_nonneg _) ... = 1 * ∥g∥ * ∥f∥ * ∏ i, ∥m i∥ : by ring end⟩ } /-- Definition of the derivative of a bilinear map `f`, given at a point `p` by `q ↦ f(p.1, q.2) + f(q.1, p.2)` as in the standard formula for the derivative of a product. We define this function here a bounded linear map from `E × F` to `G`. The fact that this is indeed the derivative of `f` is proved in `is_bounded_bilinear_map.has_fderiv_at` in `fderiv.lean`-/ def is_bounded_bilinear_map.linear_deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : (E × F) →ₗ[𝕜] G := { to_fun := λq, f (p.1, q.2) + f (q.1, p.2), map_add' := λq₁ q₂, begin change f (p.1, q₁.2 + q₂.2) + f (q₁.1 + q₂.1, p.2) = f (p.1, q₁.2) + f (q₁.1, p.2) + (f (p.1, q₂.2) + f (q₂.1, p.2)), simp [h.add_left, h.add_right], abel end, map_smul' := λc q, begin change f (p.1, c • q.2) + f (c • q.1, p.2) = c • (f (p.1, q.2) + f (q.1, p.2)), simp [h.smul_left, h.smul_right, smul_add] end } /-- The derivative of a bounded bilinear map at a point `p : E × F`, as a continuous linear map from `E × F` to `G`. -/ def is_bounded_bilinear_map.deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : (E × F) →L[𝕜] G := (h.linear_deriv p).mk_continuous_of_exists_bound $ begin rcases h.bound with ⟨C, Cpos, hC⟩, refine ⟨C * ∥p.1∥ + C * ∥p.2∥, λq, _⟩, calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _) ... ≤ C * ∥p.1∥ * ∥q∥ + C * ∥q∥ * ∥p.2∥ : begin apply add_le_add, exact mul_le_mul_of_nonneg_left (le_max_right _ _) (mul_nonneg (le_of_lt Cpos) (norm_nonneg _)), apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), exact mul_le_mul_of_nonneg_left (le_max_left _ _) (le_of_lt Cpos), end ... = (C * ∥p.1∥ + C * ∥p.2∥) * ∥q∥ : by ring end @[simp] lemma is_bounded_bilinear_map_deriv_coe (h : is_bounded_bilinear_map 𝕜 f) (p q : E × F) : h.deriv p q = f (p.1, q.2) + f (q.1, p.2) := rfl variables (𝕜) /-- The function `lmul_left_right : 𝕜' × 𝕜' → (𝕜' →L[𝕜] 𝕜')` is a bounded bilinear map. -/ lemma continuous_linear_map.lmul_left_right_is_bounded_bilinear (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : is_bounded_bilinear_map 𝕜 (continuous_linear_map.lmul_left_right 𝕜 𝕜') := { add_left := λ v₁ v₂ w, by {ext t, simp [add_comm, add_mul]}, smul_left := λ c v w, by {ext, simp }, add_right := λ v w₁ w₂, by {ext t, simp [add_comm, mul_add]}, smul_right := λ c v w, by {ext, simp }, bound := begin refine ⟨1, by linarith, _⟩, intros v w, rw one_mul, apply continuous_linear_map.lmul_left_right_norm_le, end } variables {𝕜} /-- Given a bounded bilinear map `f`, the map associating to a point `p` the derivative of `f` at `p` is itself a bounded linear map. -/ lemma is_bounded_bilinear_map.is_bounded_linear_map_deriv (h : is_bounded_bilinear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λp : E × F, h.deriv p) := begin rcases h.bound with ⟨C, Cpos, hC⟩, refine is_linear_map.with_bound ⟨λp₁ p₂, _, λc p, _⟩ (C + C) (λp, _), { ext q, simp [h.add_left, h.add_right], abel }, { ext q, simp [h.smul_left, h.smul_right, smul_add] }, { refine continuous_linear_map.op_norm_le_bound _ (mul_nonneg (add_nonneg (le_of_lt Cpos) (le_of_lt Cpos)) (norm_nonneg _)) (λq, _), calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _) ... ≤ C * ∥p∥ * ∥q∥ + C * ∥q∥ * ∥p∥ : by apply_rules [add_le_add, mul_le_mul, norm_nonneg, le_of_lt Cpos, le_refl, le_max_left, le_max_right, mul_nonneg] ... = (C + C) * ∥p∥ * ∥q∥ : by ring }, end end bilinear_map
bdb47e2c6fe6edb82d5b5eb1f218938c240817ad
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/category/Cat.lean
cb487d840051b9658a534702ba4b925786cda8c1
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
1,814
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 category_theory.concrete_category import category_theory.eq_to_hom /-! # Category of categories This file contains the definition of the category `Cat` of all categories. In this category objects are categories and morphisms are functors between these categories. ## Implementation notes Though `Cat` is not a concrete category, we use `bundled` to define its carrier type. -/ universes v u namespace category_theory /-- Category of categories. -/ def Cat := bundled category.{v u} namespace Cat instance : inhabited Cat := ⟨⟨Type u, category_theory.types⟩⟩ instance : has_coe_to_sort Cat := { S := Type u, coe := bundled.α } instance str (C : Cat.{v u}) : category.{v u} C := C.str /-- Construct a bundled `Cat` from the underlying type and the typeclass. -/ def of (C : Type u) [category.{v} C] : Cat.{v u} := bundled.of C /-- Category structure on `Cat` -/ instance category : large_category.{max v u} Cat.{v u} := { hom := λ C D, C ⥤ D, id := λ C, 𝟭 C, comp := λ C D E F G, F ⋙ G, id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- Functor that gets the set of objects of a category. It is not called `forget`, because it is not a faithful functor. -/ def objects : Cat.{v u} ⥤ Type u := { obj := λ C, C, map := λ C D F, F.obj } /-- Any isomorphism in `Cat` induces an equivalence of the underlying categories. -/ def equiv_of_iso {C D : Cat} (γ : C ≅ D) : C ≌ D := { functor := γ.hom, inverse := γ.inv, unit_iso := eq_to_iso $ eq.symm γ.hom_inv_id, counit_iso := eq_to_iso γ.inv_hom_id } end Cat end category_theory
30bd5873d4d727d83aa21b1f8c15bb639168098e
cc5bb0a18c45fa529fc8bf0365b1fbf48464c5a8
/library/init/meta/interactive.lean
56a8484d41cd17bc87c305aef0059a5822d5f3f9
[ "Apache-2.0" ]
permissive
mk12/lean
6bb58b9f3cfe312236b41779478d345399f00918
092fc89333160661c4c5a6295f3054cafff4341e
refs/heads/master
1,609,531,450,083
1,501,275,267,000
1,501,278,025,000
98,760,144
0
0
null
1,501,364,485,000
1,501,364,485,000
null
UTF-8
Lean
false
false
41,057
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.category.combinators import init.meta.interactive_base open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /- allows metavars -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- allow metavars and no subgoals -/ meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr := to_expr q tt ff /- doesn't allows metavars -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ meta def i_to_expr_for_apply (q : pexpr) : tactic expr := let aux (n : name) : tactic expr := do p ← resolve_name n, match p with | (expr.const c []) := do r ← mk_const c, save_type_info r q, return r | _ := i_to_expr p end in match q with | (expr.const c []) := aux c | (expr.local_const c _ _ _) := aux c | _ := i_to_expr q end namespace interactive open interactive interactive.types expr /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit /-- This tactic applies to a goal that is either a Pi/forall or starts with a let binder. If the current goal is a Pi/forall `∀ x:T, U` (resp `let x:=t in U`) then intro puts `x:T` (resp `x:=t`) in the local context. The new subgoal target is `U`. If the goal is an arrow `T → U`, then it puts in the local context either `h:T`, and the new goal target is `U`. If the goal is neither a Pi/forall nor starting with a let definition, the tactic `intro` applies the tactic `whnf` until the tactic `intro` can be applied or the goal is not `head-reducible`. -/ meta def intro : parse ident_? → tactic unit | none := intro1 >> skip | (some h) := tactic.intro h >> skip /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h_1 ... h_n` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := tactic.intros >> skip | hs := intro_lst hs >> skip /-- The tactic introv allows to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ meta def introv (ns : parse ident_*) : tactic unit := tactic.introv ns >> return () /-- The tactic `rename h₁ h₂` renames hypothesis `h₁` into `h₂` in the current local context. -/ meta def rename : parse ident → parse ident → tactic unit := tactic.rename /-- This tactic applies to any goal. The argument term is a term well-formed in the local context of the main goal. The tactic apply tries to match the current goal against the conclusion of the type of term. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non dependent premises are added before dependent ones. The tactic `apply` uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := i_to_expr_for_apply q >>= tactic.apply /-- Similar to the `apply` tactic, but it also creates subgoals for dependent premises that have not been fixed by type inference or type class resolution. -/ meta def fapply (q : parse texpr) : tactic unit := i_to_expr_for_apply q >>= tactic.fapply /-- Similar to the `apply` tactic, but it only creates subgoals for non dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply (q : parse texpr) : tactic unit := i_to_expr_for_apply q >>= tactic.eapply /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := do e ← i_to_expr_for_apply q, tactic.apply e cfg /-- This tactic tries to close the main goal `... |- U` using type class resolution. It succeeds if it generates a term of type `U` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic applies to any goal. It behaves like `exact` with a big difference: the user can leave some holes `_` in the term. `refine` will generate as many subgoals as there are holes in the term. Note that some holes may be implicit. The type of holes must be either synthesized by the system or declared by an explicit type ascription like (e.g., `(_ : nat → Prop)`). -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for an hypothesis which type is equal to the goal target. If it is the case, the subgoal is proved. Otherwise, it fails. -/ meta def assumption : tactic unit := tactic.assumption private meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- This tactic applies to any goal. `change U` replaces the main goal target `T` with `U` providing that `U` is well-formed with respect to the main goal local context, and `T` and `U` are definitionally equal. `change U at h` will change a local hypothesis with `U`. `change A with B at h1 h2 ...` will replace `A` with `B` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `A` and `B` are definitionally equal. -/ meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do u ← mk_meta_univ, ty ← mk_meta_var (sort u), eq ← i_to_expr ``(%%q : %%ty), ew ← i_to_expr ``(%%w : %%ty), let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none), l.try_apply (λh, do e ← infer_type h, change_core (repl e) (some h)) (do g ← target, change_core (repl g) none) /-- This tactic applies to any goal. It gives directly the exact proof term of the goal. Let `T` be our goal, let `p` be a term of type `U` then `exact p` succeeds iff `T` and `U` are definitionally equal. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse pexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts /-- A synonym for `exact` that allows writing `have/show ..., from ...` in tactic mode. -/ meta def «from» := exact /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and its dependencies to the goal target. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := do hs ← mmap tactic.get_local ids, revert_lst hs, skip private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ meta def to_expr' (p : pexpr) : tactic expr := match p with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | _ := i_to_expr p end meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta instance rw_rule.reflect : has_reflect rw_rule := λ ⟨p, s, r⟩, `(_) meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) := let aux (n : name) : tactic (list name) := do { p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := get_eqn_lemmas_for tt n | _ := return [] end } <|> return [] in match r.rule with | const n _ := aux n | local_const n _ _ _ := aux n | _ := return [] end private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {cfg with symm := r.symm}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {cfg with symm := r.symm}) (eq_lemmas.empty) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_hyp e hyp {cfg with symm := r.symm} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {cfg with symm := r.symm} >>= rw_hyp rs) (eq_lemmas.empty) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) meta instance rw_rules_t.reflect : has_reflect rw_rules_t := λ ⟨rs, p⟩, `(_) -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rw_core q l cfg meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rw_core q l cfg /- rewrite followed by assumption -/ meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rewrite q l cfg >> try assumption meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := rw_core q l cfg meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := rw_core q l cfg private meta def get_type_name (e : expr) : tactic name := do e_type ← infer_type e >>= whnf, (const I ls) ← return $ get_app_fn e_type, return I precedence `generalizing` : 0 meta def induction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do e ← i_to_expr p, -- generalize major premise e ← if e.is_local_constant then pure e else generalize e >> intro1, -- generalize major premise args (e, newvars, locals) ← do { none ← pure rec_name | pure (e, [], []), t ← infer_type e, -- TODO(Kha): `t ← whnf_ginductive t,` const n _ ← pure t.get_app_fn | pure (e, [], []), env ← get_env, tt ← pure $ env.is_inductive n | pure (e, [], []), let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition (λ arg : expr, arg.is_local_constant), _ :: _ ← pure nonlocals | pure (e, [], []), n ← tactic.revert e, newvars ← nonlocals.mmap $ λ arg, do { n ← revert_kdeps arg, tactic.generalize arg, h ← intro1, intron n, -- now try to clear hypotheses that may have been abstracted away let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc), locals.mmap' (try ∘ clear), pure h }, intron (n-1), e ← intro1, pure (e, newvars, locals) }, -- revert `generalizing` params n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst, tactic.induction e ids rec_name, all_goals $ do { intron n, clear_lst (newvars.map local_pp_name), (e::locals).mmap' (try ∘ clear) } meta def cases (p : parse texpr) (ids : parse with_ident_list) : tactic unit := do e ← i_to_expr p, tactic.cases e ids private meta def find_case (goals : list expr) (ty : name) (idx : nat) (num_indices : nat) : option expr → expr → option (expr × expr) | case e := if e.has_meta_var then match e with | (mvar _ _ _) := do case ← case, guard $ e ∈ goals, pure (case, e) | (app _ _) := let idx := match e.get_app_fn with | const (name.mk_string rec ty') _ := guard (ty' = ty) >> match mk_simple_name rec with | `drec := some idx | `rec := some idx -- indices + major premise | `dcases_on := some (idx + num_indices + 1) | `cases_on := some (idx + num_indices + 1) | _ := none end | _ := none end in match idx with | none := list.foldl (<|>) (find_case case e.get_app_fn) $ e.get_app_args.map (find_case case) | some idx := let args := e.get_app_args in do arg ← args.nth idx, args.enum.foldl (λ acc ⟨i, arg⟩, match acc with | some _ := acc | _ := if i ≠ idx then find_case none arg else none end) -- start recursion with likely case (find_case (some arg) arg) end | (lam _ _ _ e) := find_case case e | (macro n args) := list.foldl (<|>) none $ args.map (find_case case) | _ := none end else none private meta def rename_lams : expr → list name → tactic unit | (lam n _ _ e) (n'::ns) := (rename n n' >> rename_lams e ns) <|> rename_lams e (n'::ns) | _ _ := skip /-- Focuses on the `induction`/`cases` subgoal corresponding to the given introduction rule, optionally renaming introduced locals. -/ meta def case (ctor : parse ident) (ids : parse ident_*) (tac : itactic) : tactic unit := do r ← result, env ← get_env, ctor ← resolve_constant ctor <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), ty ← (env.inductive_type_of ctor).to_monad <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), let ctors := env.constructors_of ty, let idx := env.inductive_num_params ty + /- motive -/ 1 + list.index_of ctor ctors, gs ← get_goals, (case, g) ← (find_case gs ty idx (env.inductive_num_indices ty) none r ).to_monad <|> fail "could not find open goal of given case", set_goals $ g :: gs.filter (≠ g), rename_lams case ids, solve1 tac meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct private meta def generalize_arg_p : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ meta def generalize (h : parse ident?) (p : parse $ tk ":" *> with_desc "expr = id" (parser.pexpr 0 >>= generalize_arg_p)) : tactic unit := do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize e x >> intro1 >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h meta def ginduction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) : tactic unit := do x ← mk_fresh_name, let (h, hs) := (match ids with | [] := (`_h, []) | (h :: hs) := (h, hs) end : name × list name), generalize h (p, x), t ← get_local x, induction (to_pexpr t) rec_name hs ([] : list name) meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := tactic.admit /-- This tactic applies to any goal. The contradiction tactic attempts to find in the current local context an hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction meta def repeat : itactic → tactic unit := tactic.repeat meta def try : itactic → tactic unit := tactic.try meta def skip : tactic unit := tactic.skip meta def solve1 : itactic → tactic unit := tactic.solve1 meta def abstract (id : parse ident?) (tac : itactic) : tactic unit := tactic.abstract tac id meta def all_goals : itactic → tactic unit := tactic.all_goals meta def any_goals : itactic → tactic unit := tactic.any_goals meta def focus (tac : itactic) : tactic unit := tactic.focus [tac] private meta def assume_core (n : name) (ty : pexpr) := do t ← target, when (not $ t.is_pi ∨ t.is_let) whnf_target, t ← target, when (not $ t.is_pi ∨ t.is_let) $ fail "assume tactic failed, Pi/let expression expected", ty ← i_to_expr ty, unify ty t.binding_domain, intro_core n >> skip meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders) → tactic unit | (sum.inl ty) := assume_core `this ty | (sum.inr binders) := binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type /-- This tactic applies to any goal. - `have h : T := p` adds the hypothesis `h : T` to the current goal if `p` a term of type `T`. If `T` is omitted, it will be inferred. - `have h : T` adds the hypothesis `h : T` to the current goal and opens a new subgoal with target `T`. The new subgoal becomes the main goal. If `T` is omitted, it will be replaced by a fresh meta variable. If `h` is omitted, it defaults to `this`. -/ meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.assertv h t v | none, some p := do p ← i_to_expr p, tactic.note h none p | some e, none := i_to_expr e >>= tactic.assert h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.assert h e end >> skip /-- This tactic applies to any goal. - `let h : T := p` adds the hypothesis `h : T := p` to the current goal if `p` a term of type `T`. If `T` is omitted, it will be inferred. - `let h : T` adds the hypothesis `h : T := ?M` to the current goal and opens a new subgoal `?M : T`. The new subgoal becomes the main goal. If `T` is omitted, it will be replaced by a fresh meta variable. If `h` is omitted, it defaults to `this`. -/ meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.definev h t v | none, some p := do p ← i_to_expr p, tactic.pose h none p | some e, none := i_to_expr e >>= tactic.define h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.define h e end >> skip /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a meta def existsi : parse pexpr_list_or_texpr → tactic unit | [] := return () | (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := tactic.constructor /-- Similar to `constructor`, but only non dependent premises are added as new goals. -/ meta def econstructor : tactic unit := tactic.econstructor meta def left : tactic unit := tactic.left meta def right : tactic unit := tactic.right meta def split : tactic unit := tactic.split meta def exfalso : tactic unit := tactic.exfalso /-- The injection tactic is based on the fact that constructors of inductive datatypes are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds to new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` an `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs, try assumption meta def injections (hs : parse with_ident_list) : tactic unit := do tactic.injections_with hs, try assumption end interactive meta structure simp_config_ext extends simp_config := (discharger : tactic unit := failed) section mk_simp_set open expr interactive.types meta inductive simp_arg_type : Type | all_hyps : simp_arg_type | except : name → simp_arg_type | expr : pexpr → simp_arg_type meta instance : has_reflect simp_arg_type | simp_arg_type.all_hyps := `(_) | (simp_arg_type.except _) := `(_) | (simp_arg_type.expr _) := `(_) meta def simp_arg : parser simp_arg_type := (tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (simp_arg_type.expr <$> texpr) meta def simp_arg_list : parser (list simp_arg_type) := (tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return [] private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name) | [] gex hex := return (gex.reverse, hex.reverse) | (id::ids) gex hex := do p ← resolve_name id, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := resolve_exception_ids ids (n::gex) hex | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >> resolve_exception_ids ids gex (n::hex) | _ := fail $ sformat! "invalid exception {id}, unknown identifier" end /- Return (hs, gex, hex, all) -/ meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool := do let (hs, ex, all) := hs.foldl (λ r h, match r, h with | (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt) | (es, ex, all), simp_arg_type.except id := (es, id::ex, all) | (es, ex, all), simp_arg_type.expr e := (e::es, ex, all) end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail ("invalid simplification lemma '" ++ to_string n ++ "' (use command 'set_option trace.simp_lemmas true' for more details)") private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) : tactic (simp_lemmas × list name) := do p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n, return (s, u)) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s eqns, return (s, u)) <|> (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u)) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e, return (s, u)) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) : tactic (simp_lemmas × list name) := match p with | (const c []) := simp_lemmas.resolve_and_add s u c p | (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p | _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e, return (s, u) end private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list pexpr → tactic (simp_lemmas × list name) | s u [] := return (s, u) | s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l, simp_lemmas.append_pexprs s u ls meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool) : tactic (bool × simp_lemmas × list name) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported", s ← join_user_simp_lemmas no_dflt attr_names, (s, u) ← simp_lemmas.append_pexprs s [] hs, s ← if not at_star ∧ all_hyps then do ctx ← collect_ctx_simps, let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions s.append ctx else return s, -- add equational lemmas, if any gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return (all_hyps, simp_lemmas.erase s $ gex.join, u) meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) := prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff) end mk_simp_set namespace interactive open interactive interactive.types expr meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff, guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.mmap' (λ h, try (clear h)) meta def simp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic unit := match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then tactic.simp_all s u cfg discharger else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, simp_core_aux cfg discharger s u ns locat.include_goal end >> try tactic.triv >> try (tactic.reflexivity reducible) /-- This tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. - `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. - `simp [h_1, ..., h_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h_i`s. The `h_i`'s are terms. If a `h_i` is a definition `f`, then the equational lemmas associated with `f` are used. This is a convenient way to "unfold" `f`. - `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. Remark: `simp *` is a shorthand for `simp [*]`. - `simp only [h_1, ..., h_n]` is like `simp [h_1, ..., h_n]` but does not use `[simp]` lemmas - `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id_i`s. - `simp at h_1 ... h_n` simplifies the non dependent hypotheses `h_1 : T_1` ... `h_n : T : n`. The tactic fails if the target or another hypothesis depends on one of them. - `simp at *` simplifies all the hypotheses and the target. - `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. - `simp with attr_1 ... attr_n` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr_1]`, ..., `[attr_n]` or `[simp]`. -/ meta def simp (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat /-- Just construct the simp set and trace it -/ meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit := do (s, _) ← mk_simp_set no_dflt attr_names hs, s.pp >>= trace meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_intros_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names hs, when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")), tactic.simp_intros s u ids cfg, try triv >> try (reflexivity reducible) private meta def to_simp_arg_list (es : list pexpr) : list simp_arg_type := es.map simp_arg_type.expr meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) (l : parse location) (cfg : dsimp_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names es, match l with | loc.wildcard := do ls ← local_context, n ← revert_lst ls, dsimp_target s u cfg, intron n | _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg) end /-- This tactic applies to a goal that has the form `t ~ u` where `~` is a reflexive relation. That is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity meta def symmetry : tactic unit := tactic.symmetry meta def transitivity (q : parse texpr?) : tactic unit := tactic.transitivity >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, i_to_expr q >>= unify rhs end meta def ac_reflexivity : tactic unit := tactic.ac_refl meta def ac_refl : tactic unit := tactic.ac_refl meta def cc : tactic unit := tactic.cc meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit := match l with | (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, dunfold_target new_cs cfg, intron n | _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg) end private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs meta def delta : parse ident* → parse location → tactic unit | cs (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, delta_target new_cs, intron n | cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs) private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool := hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff /-- This tactic unfolds all structure projections. -/ meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit := match l with | loc.wildcard := do ls ← local_context, b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name), b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff, when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify") | _ := l.try_apply (λ h, unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify" end end interactive meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) := cs.mmap $ λ c, do n ← resolve_name c, hs ← get_eqn_lemmas_for ff n.const_name, env ← get_env, let p := env.is_projection n.const_name, when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")), return $ simp_arg_type.expr (expr.const c []) structure unfold_config extends simp_config := (zeta := ff) (proj := ff) (eta := ff) (canonize_instances := ff) namespace interactive open interactive interactive.types expr meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit := do es ← ids_to_simp_arg_list "unfold" cs, let no_dflt := tt, simp_core cfg.to_simp_config failed no_dflt es [] locat meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit := unfold cs locat cfg meta def apply_opt_param : tactic unit := tactic.apply_opt_param meta def apply_auto_param : tactic unit := tactic.apply_auto_param meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac meta def success_if_fail (tac : itactic) : tactic unit := tactic.success_if_fail tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv t e) meta def guard_target (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq t p meta def by_cases (q : parse texpr) (n : parse (tk "with" *> ident)?): tactic unit := do p ← tactic.to_expr_strict q, tactic.by_cases p (n.get_or_else `h) meta def by_contradiction (n : parse ident?) : tactic unit := tactic.by_contradiction n >> return () meta def by_contra (n : parse ident?) : tactic unit := tactic.by_contradiction n >> return () /-- Type check the given expression, and trace its type. -/ meta def type_check (p : parse texpr) : tactic unit := do e ← to_expr p, tactic.type_check e, infer_type e >>= trace /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := tactic.done private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit | [] r := fail "show tactic failed" | (g::gs) r := do do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty} <|> show_aux gs (g::r) meta def «show» (q : parse texpr) : tactic unit := do gs ← get_goals, show_aux q gs [] end interactive end tactic section add_interactive open tactic /- See add_interactive -/ private meta def add_interactive_aux (new_namespace : name) : list name → command | [] := return () | (n::ns) := do env ← get_env, d_name ← resolve_constant n, (declaration.defn _ ls ty val hints trusted) ← env.get d_name, (name.mk_string h _) ← return d_name, let new_name := `tactic.interactive <.> h, add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted), add_interactive_aux ns /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command := add_interactive_aux p ns end add_interactive
3037e9024d0aeb434f96771e4541b36885514f71
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/tests/lean/run/matchEqs.lean
23c5c3f6b8482dca3f9689ca3a90602b0a43f2d1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
612
lean
import Lean syntax (name := test) "test%" ident : command open Lean.Elab open Lean.Elab.Command @[commandElab test] def elabTest : CommandElab := fun stx => do let id ← resolveGlobalConstNoOverloadWithInfo stx[1] liftTermElabM do IO.println (repr (← Lean.Meta.Match.getEquationsFor id)) return () def f (x : List Nat) : Nat := match x with | [] => 1 | [a] => 2 | _ => 3 test% f.match_1 #check @f.match_1 #check @f.match_1.splitter theorem ex (x : List Nat) : f x > 0 := by simp [f] split <;> decide test% Lean.RBNode.balance1.match_1 #check @Lean.RBNode.balance1.match_1.splitter
84bdcb256062fd967550ebf61e83ec3983044ccb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/is_locally_homeomorph.lean
75fa4fe4ab8ecfecf3c169755bc5cc96659b5ad5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,955
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import topology.local_homeomorph /-! # Local homeomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines local homeomorphisms. ## Main definitions * `is_locally_homeomorph`: A function `f : X → Y` satisfies `is_locally_homeomorph` if for each point `x : X`, the restriction of `f` to some open neighborhood `U` of `x` gives a homeomorphism between `U` and an open subset of `Y`. Note that `is_locally_homeomorph` is a global condition. This is in contrast to `local_homeomorph`, which is a homeomorphism between specific open subsets. -/ open_locale topology variables {X Y Z : Type*} [topological_space X] [topological_space Y] [topological_space Z] (g : Y → Z) (f : X → Y) (s : set X) (t : set Y) /-- A function `f : X → Y` satisfies `is_locally_homeomorph_on f s` if each `x ∈ s` is contained in the source of some `e : local_homeomorph X Y` with `f = e`. -/ def is_locally_homeomorph_on := ∀ x ∈ s, ∃ e : local_homeomorph X Y, x ∈ e.source ∧ f = e namespace is_locally_homeomorph_on /-- Proves that `f` satisfies `is_locally_homeomorph_on f s`. The condition `h` is weaker than the definition of `is_locally_homeomorph_on f s`, since it only requires `e : local_homeomorph X Y` to agree with `f` on its source `e.source`, as opposed to on the whole space `X`. -/ lemma mk (h : ∀ x ∈ s, ∃ e : local_homeomorph X Y, x ∈ e.source ∧ ∀ y ∈ e.source, f y = e y) : is_locally_homeomorph_on f s := begin intros x hx, obtain ⟨e, hx, he⟩ := h x hx, exact ⟨{ to_fun := f, map_source' := λ x hx, by rw he x hx; exact e.map_source' hx, left_inv' := λ x hx, by rw he x hx; exact e.left_inv' hx, right_inv' := λ y hy, by rw he _ (e.map_target' hy); exact e.right_inv' hy, continuous_to_fun := (continuous_on_congr he).mpr e.continuous_to_fun, .. e }, hx, rfl⟩, end variables {g f s t} lemma map_nhds_eq (hf : is_locally_homeomorph_on f s) {x : X} (hx : x ∈ s) : (𝓝 x).map f = 𝓝 (f x) := let ⟨e, hx, he⟩ := hf x hx in he.symm ▸ e.map_nhds_eq hx protected lemma continuous_at (hf : is_locally_homeomorph_on f s) {x : X} (hx : x ∈ s) : continuous_at f x := (hf.map_nhds_eq hx).le protected lemma continuous_on (hf : is_locally_homeomorph_on f s) : continuous_on f s := continuous_at.continuous_on (λ x, hf.continuous_at) protected lemma comp (hg : is_locally_homeomorph_on g t) (hf : is_locally_homeomorph_on f s) (h : set.maps_to f s t) : is_locally_homeomorph_on (g ∘ f) s := begin intros x hx, obtain ⟨eg, hxg, rfl⟩ := hg (f x) (h hx), obtain ⟨ef, hxf, rfl⟩ := hf x hx, exact ⟨ef.trans eg, ⟨hxf, hxg⟩, rfl⟩, end end is_locally_homeomorph_on /-- A function `f : X → Y` satisfies `is_locally_homeomorph f` if each `x : x` is contained in the source of some `e : local_homeomorph X Y` with `f = e`. -/ def is_locally_homeomorph := ∀ x : X, ∃ e : local_homeomorph X Y, x ∈ e.source ∧ f = e variables {f} lemma is_locally_homeomorph_iff_is_locally_homeomorph_on_univ : is_locally_homeomorph f ↔ is_locally_homeomorph_on f set.univ := by simp only [is_locally_homeomorph, is_locally_homeomorph_on, set.mem_univ, forall_true_left] protected lemma is_locally_homeomorph.is_locally_homeomorph_on (hf : is_locally_homeomorph f) : is_locally_homeomorph_on f set.univ := is_locally_homeomorph_iff_is_locally_homeomorph_on_univ.mp hf variables (f) namespace is_locally_homeomorph /-- Proves that `f` satisfies `is_locally_homeomorph f`. The condition `h` is weaker than the definition of `is_locally_homeomorph f`, since it only requires `e : local_homeomorph X Y` to agree with `f` on its source `e.source`, as opposed to on the whole space `X`. -/ lemma mk (h : ∀ x : X, ∃ e : local_homeomorph X Y, x ∈ e.source ∧ ∀ y ∈ e.source, f y = e y) : is_locally_homeomorph f := is_locally_homeomorph_iff_is_locally_homeomorph_on_univ.mpr (is_locally_homeomorph_on.mk f set.univ (λ x hx, h x)) variables {g f} lemma map_nhds_eq (hf : is_locally_homeomorph f) (x : X) : (𝓝 x).map f = 𝓝 (f x) := hf.is_locally_homeomorph_on.map_nhds_eq (set.mem_univ x) protected lemma continuous (hf : is_locally_homeomorph f) : continuous f := continuous_iff_continuous_on_univ.mpr hf.is_locally_homeomorph_on.continuous_on protected lemma is_open_map (hf : is_locally_homeomorph f) : is_open_map f := is_open_map.of_nhds_le (λ x, ge_of_eq (hf.map_nhds_eq x)) protected lemma comp (hg : is_locally_homeomorph g) (hf : is_locally_homeomorph f) : is_locally_homeomorph (g ∘ f) := is_locally_homeomorph_iff_is_locally_homeomorph_on_univ.mpr (hg.is_locally_homeomorph_on.comp hf.is_locally_homeomorph_on (set.univ.maps_to_univ f)) end is_locally_homeomorph
0cbf49ffa1be07179b5c88fbfc10fec0fbd72e96
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/algebra/ordered_group.lean
18f7cc7d5761d6201078646a176bfbc45eaf0279
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
63,072
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.group.with_one import algebra.group.type_tags import order.bounded_lattice set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-! # Ordered monoids and groups This file develops the basics of ordered monoids and groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ universe u variable {α : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c * a ≤ c * b` (multiplication is monotone) * `a * b < a * c → b < c`. -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c + a ≤ c + b` (addition is monotone) * `a + b < a + c → b < c`. -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) attribute [to_additive ordered_add_comm_monoid] ordered_comm_monoid section ordered_comm_monoid variables [ordered_comm_monoid α] {a b c d : α} @[to_additive add_le_add_left] lemma mul_le_mul_left' (h : a ≤ b) (c) : c * a ≤ c * b := ordered_comm_monoid.mul_le_mul_left a b h c @[to_additive add_le_add_right] lemma mul_le_mul_right' (h : a ≤ b) (c) : a * c ≤ b * c := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left' h c @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' : a * b < a * c → b < c := ordered_comm_monoid.lt_of_mul_lt_mul_left a b c @[to_additive add_le_add] lemma mul_le_mul' (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := le_trans (mul_le_mul_right' h₁ _) (mul_le_mul_left' h₂ _) @[to_additive] lemma mul_le_mul_three {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ @[to_additive] lemma le_mul_of_one_le_right (h : 1 ≤ b) : a ≤ a * b := have a * 1 ≤ a * b, from mul_le_mul_left' h _, by rwa mul_one at this @[to_additive] lemma le_mul_of_one_le_left (h : 1 ≤ b) : a ≤ b * a := have 1 * a ≤ b * a, from mul_le_mul_right' h a, by rwa one_mul at this @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' (h : a * b < c * b) : a < c := lt_of_mul_lt_mul_left' (show b * a < b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) -- here we start using properties of one. @[to_additive] lemma le_mul_of_one_le_of_le (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := one_mul b ▸ mul_le_mul' ha hbc @[to_additive] lemma le_mul_of_le_of_one_le (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := mul_one b ▸ mul_le_mul' hbc ha @[to_additive add_nonneg] lemma one_le_mul (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb @[to_additive add_pos_of_pos_of_nonneg] lemma one_lt_mul_of_lt_of_le' (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_of_lt_of_le ha $ le_mul_of_one_le_right hb @[to_additive add_pos_of_nonneg_of_pos] lemma one_lt_mul_of_le_of_lt' (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_of_lt_of_le hb $ le_mul_of_one_le_left ha @[to_additive add_pos] lemma one_lt_mul' (ha : 1 < a) (hb : 1 < b) : 1 < a * b := one_lt_mul_of_lt_of_le' ha $ le_of_lt hb @[to_additive add_nonpos] lemma mul_le_one' (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1:α) ▸ (mul_le_mul' ha hb) @[to_additive] lemma mul_le_of_le_one_of_le' (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one' (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one' (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := lt_of_le_of_lt (mul_le_of_le_of_le_one' (le_refl _) hb) ha @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one' (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha (le_refl _)) hb @[to_additive] lemma mul_lt_one' (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_one_of_le_one_of_lt_one' (le_of_lt ha) hb @[to_additive] lemma lt_mul_of_one_le_of_lt' (ha : 1 ≤ a) (hbc : b < c) : b < a * c := lt_of_lt_of_le hbc $ le_mul_of_one_le_left ha @[to_additive] lemma lt_mul_of_lt_of_one_le' (hbc : b < c) (ha : 1 ≤ a) : b < c * a := lt_of_lt_of_le hbc $ le_mul_of_one_le_right ha @[to_additive] lemma lt_mul_of_one_lt_of_lt' (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt' (le_of_lt ha) hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt' (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le' hbc (le_of_lt ha) @[to_additive] lemma mul_lt_of_le_one_of_lt' (ha : a ≤ 1) (hbc : b < c) : a * b < c := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha (le_refl _)) hbc @[to_additive] lemma mul_lt_of_lt_of_le_one' (hbc : b < c) (ha : a ≤ 1) : b * a < c := lt_of_le_of_lt (mul_le_of_le_of_le_one' (le_refl _) ha) hbc @[to_additive] lemma mul_lt_of_lt_one_of_lt' (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt' (le_of_lt ha) hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one' hbc (le_of_lt ha) @[to_additive] lemma mul_eq_one_iff' (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le (le_refl _) hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha (le_refl _), have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add] lemma monotone.mul' (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) @[to_additive monotone.add_const] lemma monotone.mul_const' (hf : monotone f) (a : α) : monotone (λ x, f x * a) := hf.mul' monotone_const @[to_additive monotone.const_add] lemma monotone.const_mul' (hf : monotone f) (a : α) : monotone (λ x, a * f x) := monotone_const.mul' hf end mono end ordered_comm_monoid lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid α] [preorder α] : preorder (units α) := preorder.lift (coe : units α → α) @[simp, to_additive, norm_cast] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl @[simp, to_additive, norm_cast] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl @[to_additive] instance [monoid α] [partial_order α] : partial_order (units α) := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order (units α) := linear_order.lift coe units.ext @[to_additive] instance [monoid α] [decidable_linear_order α] : decidable_linear_order (units α) := decidable_linear_order.lift coe units.ext @[simp, to_additive, norm_cast] theorem max_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [max, h] @[simp, to_additive, norm_cast] theorem min_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] end units namespace with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order instance [decidable_linear_order α] : decidable_linear_order (with_zero α) := with_bot.decidable_linear_order /-- If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one α] @[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩ @[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 := by rw [eq_comm, coe_eq_one] attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) . @[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ . end has_one instance [has_add α] : has_add (with_top α) := ⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩ instance [add_semigroup α] : add_semigroup (with_top α) := { add := (+), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ } @[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $ @with_zero.monoid_with_zero (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $ @with_zero.comm_monoid_with_zero (multiplicative α) _ } instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) := begin suffices, refine { add_le_add_left := this, ..with_top.partial_order, ..with_top.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ c h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim le_top }, cases b with b, { exact (not_le_of_lt h).elim le_top }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_top.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases b with b; cases h₂, cases a with a, {cases le_antisymm h le_top }, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end @[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe @[simp] lemma add_top [ordered_add_comm_monoid α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [ordered_add_comm_monoid α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by cases a; cases b; simp [none_eq_top, some_eq_coe, coe_add.symm] lemma add_lt_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] end with_top namespace with_bot instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero instance [has_one α] : has_one (with_bot α) := with_top.has_one instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {α : Type*} [add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := by norm_cast @[simp] lemma bot_add [ordered_add_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_add_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl end with_bot /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α := (le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c) section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] {a b c d : α} lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c := canonically_ordered_add_monoid.le_iff_exists_add a b @[simp] lemma zero_le (a : α) : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩ @[simp] lemma bot_eq_zero : (⊥ : α) = 0 := le_antisymm bot_le (zero_le ⊥) @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff' (zero_le _) (zero_le _) @[simp] lemma le_zero_iff_eq : a ≤ 0 ↔ a = 0 := iff.intro (assume h, le_antisymm h (zero_le a)) (assume h, h ▸ le_refl a) lemma zero_lt_iff_ne_zero : 0 < a ↔ a ≠ 0 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm @[nolint ge_or_gt] lemma exists_pos_add_of_lt (h : a < b) : ∃ c > 0, a + c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_lt h), refine ⟨c, zero_lt_iff_ne_zero.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end lemma le_add_left (h : a ≤ c) : a ≤ b + c := calc a = 0 + a : by simp ... ≤ b + c : add_le_add (zero_le _) h lemma le_add_right (h : a ≤ b) : a ≤ b + c := calc a = a + 0 : by simp ... ≤ b + c : add_le_add h (zero_le _) instance with_zero.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } end canonically_ordered_add_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and strictly monotone. -/ @[protect_proj, ancestor add_comm_monoid add_left_cancel_semigroup add_right_cancel_semigroup partial_order] class ordered_cancel_add_comm_monoid (α : Type u) extends add_comm_monoid α, add_left_cancel_semigroup α, add_right_cancel_semigroup α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and strictly monotone. -/ @[protect_proj, ancestor comm_monoid left_cancel_semigroup right_cancel_semigroup partial_order] class ordered_cancel_comm_monoid (α : Type u) extends comm_monoid α, left_cancel_semigroup α, right_cancel_semigroup α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) attribute [to_additive ordered_cancel_add_comm_monoid] ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c d : α} @[to_additive] instance ordered_cancel_comm_monoid.to_left_cancel_monoid : left_cancel_monoid α := { ..‹ordered_cancel_comm_monoid α› } @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' : ∀ {a b c : α}, a * b ≤ a * c → b ≤ c := ordered_cancel_comm_monoid.le_of_mul_le_mul_left @[to_additive] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le (le_of_mul_le_mul_left' (le_of_lt h)) $ mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h), ..‹ordered_cancel_comm_monoid α› } @[to_additive add_lt_add_left] lemma mul_lt_mul_left' (h : a < b) (c : α) : c * a < c * b := lt_of_le_not_le (mul_le_mul_left' (le_of_lt h) _) $ mt le_of_mul_le_mul_left' (not_le_of_gt h) @[to_additive add_lt_add_right] lemma mul_lt_mul_right' (h : a < b) (c : α) : a * c < b * c := begin rw [mul_comm a c, mul_comm b c], exact (mul_lt_mul_left' h c) end @[to_additive add_lt_add] lemma mul_lt_mul''' (h₁ : a < b) (h₂ : c < d) : a * c < b * d := lt_trans (mul_lt_mul_right' h₁ c) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_le_of_lt (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := lt_of_le_of_lt (mul_le_mul_right' h₁ _) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := lt_of_lt_of_le (mul_lt_mul_right' h₁ c) (mul_le_mul_left' h₂ _) @[to_additive] lemma lt_mul_of_one_lt_right (a : α) {b : α} (h : 1 < b) : a < a * b := have a * 1 < a * b, from mul_lt_mul_left' h a, by rwa [mul_one] at this @[to_additive] lemma lt_mul_of_one_lt_left (a : α) {b : α} (h : 1 < b) : a < b * a := have 1 * a < b * a, from mul_lt_mul_right' h a, by rwa [one_mul] at this @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' (h : a * b ≤ c * b) : a ≤ c := le_of_mul_le_mul_left' (show b * a ≤ b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive] lemma mul_lt_one (ha : a < 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul''' ha hb) @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_lt_of_le ha hb) @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_le_of_lt ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_le (ha : 1 < a) (hbc : b ≤ c) : b < a * c := one_mul b ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma lt_mul_of_le_of_one_lt (hbc : b ≤ c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma mul_le_of_le_one_of_le (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_le (ha : a < 1) (hbc : b ≤ c) : a * b < c := one_mul c ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma mul_lt_of_le_of_lt_one (hbc : b ≤ c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma lt_mul_of_one_le_of_lt (ha : 1 ≤ a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_le (hbc : b < c) (ha : 1 ≤ a) : b < c * a := mul_one b ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma lt_mul_of_one_lt_of_lt (ha : 1 < a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul''' ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt (hbc : b < c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul''' hbc ha @[to_additive] lemma mul_lt_of_le_one_of_lt (ha : a ≤ 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma mul_lt_of_lt_of_le_one (hbc : b < c) (ha : a ≤ 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_lt (ha : a < 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul''' ha hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one (hbc : b < c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul''' hbc ha @[simp, to_additive] lemma mul_le_mul_iff_left (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := ⟨le_of_mul_le_mul_left', λ h, mul_le_mul_left' h _⟩ @[simp, to_additive] lemma mul_le_mul_iff_right (c : α) : a * c ≤ b * c ↔ a ≤ b := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_iff_left c @[simp, to_additive] lemma mul_lt_mul_iff_left (a : α) {b c : α} : a * b < a * c ↔ b < c := ⟨lt_of_mul_lt_mul_left', λ h, mul_lt_mul_left' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_right (c : α) : a * c < b * c ↔ a < b := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_iff_left c @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := have a * 1 ≤ a * b ↔ 1 ≤ b, from mul_le_mul_iff_left a, by rwa mul_one at this @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, le_mul_iff_one_le_right'] @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' (a : α) {b : α} : a < a * b ↔ 1 < b := have a * 1 < a * b ↔ 1 < b, from mul_lt_mul_iff_left a, by rwa mul_one at this @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' (a : α) {b : α} : a < b * a ↔ 1 < b := by rw [mul_comm, lt_mul_iff_one_lt_right'] @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' : a * b ≤ b ↔ a ≤ 1 := by { convert mul_le_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' : a * b ≤ a ↔ b ≤ 1 := by { convert mul_le_mul_iff_left a, rw [mul_one] } @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' : a * b < b ↔ a < 1 := by { convert mul_lt_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' : a * b < a ↔ b < 1 := by { convert mul_lt_mul_iff_left a, rw [mul_one] } @[to_additive] lemma mul_eq_one_iff_eq_one_of_one_le (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := ⟨λ hab : a * b = 1, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', mul_one]⟩ section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add_strict_mono] lemma monotone.mul_strict_mono' (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf $ le_of_lt h) (hg h) @[to_additive strict_mono.add_monotone] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg $ le_of_lt h) @[to_additive strict_mono.add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := hf.mul_monotone' monotone_const @[to_additive strict_mono.const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := monotone_const.mul_strict_mono' hf end mono end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid α] lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive ordered_add_comm_group] ordered_comm_group /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) := { mul_le_mul_left := λ a b h c, mul_le_mul_left' h _, .. units.partial_order, .. (infer_instance : comm_group (units α)) } section ordered_comm_group variables [ordered_comm_group α] {a b c d : α} @[to_additive ordered_add_comm_group.add_lt_add_left] lemma ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := begin rw lt_iff_le_not_le at h ⊢, split, { apply ordered_comm_group.mul_le_mul_left _ _ h.1 }, { intro w, replace w : c⁻¹ * (c * b) ≤ c⁻¹ * (c * a) := ordered_comm_group.mul_le_mul_left _ _ w _, simp only [mul_one, mul_comm, mul_left_inv, mul_left_comm] at w, exact h.2 w }, end @[to_additive ordered_add_comm_group.le_of_add_le_add_left] lemma ordered_comm_group.le_of_mul_le_mul_left (h : a * b ≤ a * c) : b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] lemma ordered_comm_group.lt_of_mul_lt_mul_left (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_comm_group.mul_lt_mul_left' _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, le_of_mul_le_mul_left := @ordered_comm_group.le_of_mul_le_mul_left α _, ..s } @[to_additive neg_le_neg] lemma inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := have 1 ≤ a⁻¹ * b, from mul_left_inv a ▸ mul_le_mul_left' h _, have 1 * b⁻¹ ≤ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _, by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma le_of_inv_le_inv (h : b⁻¹ ≤ a⁻¹) : a ≤ b := suffices (a⁻¹)⁻¹ ≤ (b⁻¹)⁻¹, from begin simp [inv_inv] at this, assumption end, inv_le_inv' h @[to_additive] lemma one_le_of_inv_le_one (h : a⁻¹ ≤ 1) : 1 ≤ a := have a⁻¹ ≤ 1⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive] lemma inv_le_one_of_one_le (h : 1 ≤ a) : a⁻¹ ≤ 1 := have a⁻¹ ≤ 1⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive nonpos_of_neg_nonneg] lemma le_one_of_one_le_inv (h : 1 ≤ a⁻¹) : a ≤ 1 := have 1⁻¹ ≤ a⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one (h : a ≤ 1) : 1 ≤ a⁻¹ := have 1⁻¹ ≤ a⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive neg_lt_neg] lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := have 1 < a⁻¹ * b, from mul_left_inv a ▸ mul_lt_mul_left' h (a⁻¹), have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹), by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b := inv_inv a ▸ inv_inv b ▸ inv_lt_inv' h @[to_additive] lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a := have a⁻¹ < 1⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive] lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 := have a⁻¹ < 1⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive neg_of_neg_pos] lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 := have 1⁻¹ < a⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive neg_pos_of_neg] lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ := have 1⁻¹ < a⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive] lemma le_inv_of_le_inv (h : a ≤ b⁻¹) : b ≤ a⁻¹ := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_le_of_inv_le (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma mul_le_of_le_inv_mul (h : b ≤ a⁻¹ * c) : a * b ≤ c := begin have h := mul_le_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma le_inv_mul_of_mul_le (h : a * b ≤ c) : b ≤ a⁻¹ * c := begin have h := mul_le_mul_left' h a⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≤ c) : a ≤ b * c := begin have h := mul_le_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_le_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := begin have h := mul_le_mul_left' h b⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≤ c) : a ≤ b * c := le_mul_of_inv_mul_le h @[to_additive] lemma inv_mul_le_left_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := inv_mul_le_of_le_mul h @[to_additive] lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≤ b) : a ≤ b * c := by { rw mul_comm, exact le_mul_of_inv_mul_le h } @[to_additive] lemma inv_mul_le_right_of_le_mul (h : a ≤ b * c) : c⁻¹ * a ≤ b := by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h } @[to_additive] lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c := begin have h := mul_lt_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c := begin have h := mul_lt_mul_left' h (a⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c := begin have h := mul_lt_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := begin have h := mul_lt_mul_left' h (b⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c := lt_mul_of_inv_mul_lt h @[to_additive] lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := inv_mul_lt_of_lt_mul h @[to_additive] lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c := by { rw mul_comm, exact lt_mul_of_inv_mul_lt h } @[to_additive] lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b := by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h } @[simp, to_additive] lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a := ⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩ @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := have a * b * a⁻¹ ≤ a * b * b⁻¹ ↔ a⁻¹ ≤ b⁻¹, from mul_le_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := have a⁻¹ ≤ (b⁻¹)⁻¹ ↔ b⁻¹ ≤ a, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := have (a⁻¹)⁻¹ ≤ b⁻¹ ↔ b ≤ a⁻¹, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive neg_nonpos] lemma inv_le_one' : a⁻¹ ≤ 1 ↔ 1 ≤ a := have a⁻¹ ≤ 1⁻¹ ↔ 1 ≤ a, from inv_le_inv_iff, by rwa one_inv at this @[simp, to_additive neg_nonneg] lemma one_le_inv' : 1 ≤ a⁻¹ ↔ a ≤ 1 := have 1⁻¹ ≤ a⁻¹ ↔ a ≤ 1, from inv_le_inv_iff, by rwa one_inv at this @[to_additive] lemma inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (inv_le_one'.2 h) h @[to_additive] lemma self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (one_le_inv'.2 h) @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_lt_zero] lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a := have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_pos] lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 := have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := have b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≤ b ↔ a ≤ b * c := by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive sub_le_sub_iff] lemma div_le_div_iff' (a b c d : α) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin split ; intro h, have := mul_le_mul_right' (mul_le_mul_right' h b) d, rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right] at this, have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹, rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc, mul_inv_cancel_right] at this, end end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group α] {a b c d : α} lemma sub_nonneg_of_le (h : b ≤ a) : 0 ≤ a - b := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg (h : 0 ≤ a - b) : b ≤ a := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le (h : a ≤ b) : a - b ≤ 0 := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos (h : a - b ≤ 0) : a ≤ b := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt (h : b < a) : 0 < a - b := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos (h : 0 < a - b) : b < a := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt (h : a < b) : a - b < 0 := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg (h : a - b < 0) : a < b := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_sub_left (h : b ≤ c - a) : a + b ≤ c := begin have h := add_le_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma le_sub_left_of_add_le (h : a + b ≤ c) : b ≤ c - a := begin have h := add_le_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_le_of_le_sub_right (h : a ≤ c - b) : a + b ≤ c := begin have h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le (h : a + b ≤ c) : a ≤ c - b := begin have h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_sub_left_le (h : a - b ≤ c) : a ≤ b + c := begin have h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add (h : a ≤ b + c) : a - b ≤ c := begin have h := add_le_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma le_add_of_sub_right_le (h : a - c ≤ b) : a ≤ b + c := begin have h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add (h : a ≤ b + c) : a - c ≤ b := begin have h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_le_sub_left (h : -a ≤ b - c) : c ≤ a + b := le_add_of_neg_add_le_left (add_le_of_le_sub_right h) lemma neg_le_sub_left_of_le_add (h : c ≤ a + b) : -a ≤ b - c := begin have h := le_neg_add_of_add_le (sub_left_le_of_le_add h), rwa add_comm at h end lemma le_add_of_neg_le_sub_right (h : -b ≤ a - c) : c ≤ a + b := le_add_of_sub_right_le (add_le_of_le_sub_left h) lemma neg_le_sub_right_of_le_add (h : c ≤ a + b) : -b ≤ a - c := le_sub_left_of_add_le (sub_right_le_of_le_add h) lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := sub_left_le_of_le_add (le_add_of_sub_right_le h) lemma sub_le_sub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_sub_left (h : b < c - a) : a + b < c := begin have h := add_lt_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma lt_sub_left_of_add_lt (h : a + b < c) : b < c - a := begin have h := add_lt_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_lt_of_lt_sub_right (h : a < c - b) : a + b < c := begin have h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt (h : a + b < c) : a < c - b := begin have h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_sub_left_lt (h : a - b < c) : a < b + c := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add (h : a < b + c) : a - b < c := begin have h := add_lt_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma lt_add_of_sub_right_lt (h : a - c < b) : a < b + c := begin have h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add (h : a < b + c) : a - c < b := begin have h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_lt_sub_left (h : -a < b - c) : c < a + b := lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h) lemma neg_lt_sub_left_of_lt_add (h : c < a + b) : -a < b - c := begin have h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h), rwa add_comm at h end lemma lt_add_of_neg_lt_sub_right (h : -b < a - c) : c < a + b := lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h) lemma neg_lt_sub_right_of_lt_add (h : c < a + b) : -b < a - c := lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h) lemma sub_lt_of_sub_lt (h : a - b < c) : a - c < b := sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h) lemma sub_lt_sub_left (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c := add_lt_add hab (neg_lt_neg hcd) lemma sub_lt_sub_of_le_of_lt (hab : a ≤ b) (hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt hab (neg_lt_neg hcd) lemma sub_lt_sub_of_lt_of_le (hab : a < b) (hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le hab (neg_le_neg hcd) lemma sub_le_self (a : α) {b : α} (h : 0 ≤ b) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _ ... = a : by rw add_zero lemma sub_lt_self (a : α) {b : α} (h : 0 < b) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _ ... = a : by rw add_zero @[simp] lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b := (add_le_add_iff_left _).trans neg_le_neg_iff @[simp] lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b := add_le_add_iff_right _ @[simp] lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b := (add_lt_add_iff_left _).trans neg_lt_neg_iff @[simp] lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b := add_lt_add_iff_right _ @[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a := have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b := have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b, by rwa sub_self at this @[simp] lemma sub_pos : 0 < a - b ↔ b < a := have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b, by rwa sub_self at this lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c := by rw [le_sub_iff_add_le', add_comm] lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≤ c ↔ a - c ≤ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≤ b - c ↔ c ≤ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b := sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _) lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b := sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _) end ordered_add_comm_group /- TODO: The `add_lt_add_left` field of `ordered_add_comm_group` is redundant, and it is no longer in core so we can remove it now. This alternative constructor is a workaround until someone fixes this. -/ /-- Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`. -/ @[to_additive "Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`."] def ordered_comm_group.mk' {α : Type u} [comm_group α] [partial_order α] (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) : ordered_comm_group α := { mul_le_mul_left := mul_le_mul_left, ..(by apply_instance : comm_group α), ..(by apply_instance : partial_order α) } /-- A decidable linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_cancel_add_comm_monoid (α : Type u) extends ordered_cancel_add_comm_monoid α, decidable_linear_order α section decidable_linear_ordered_cancel_add_comm_monoid variables [decidable_linear_ordered_cancel_add_comm_monoid α] lemma min_add_add_left (a b c : α) : min (a + b) (a + c) = a + min b c := eq.symm (eq_min (show a + min b c ≤ a + b, from add_le_add_left (min_le_left _ _) _) (show a + min b c ≤ a + c, from add_le_add_left (min_le_right _ _) _) (assume d, assume : d ≤ a + b, assume : d ≤ a + c, decidable.by_cases (assume : b ≤ c, by rwa [min_eq_left this]) (assume : ¬ b ≤ c, by rwa [min_eq_right (le_of_lt (lt_of_not_ge this))]))) lemma min_add_add_right (a b c : α) : min (a + c) (b + c) = min a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply min_add_add_left end lemma max_add_add_left (a b c : α) : max (a + b) (a + c) = a + max b c := eq.symm (eq_max (add_le_add_left (le_max_left _ _) _) (add_le_add_left (le_max_right _ _) _) (assume d, assume : a + b ≤ d, assume : a + c ≤ d, decidable.by_cases (assume : b ≤ c, by rwa [max_eq_right this]) (assume : ¬ b ≤ c, by rwa [max_eq_left (le_of_lt (lt_of_not_ge this))]))) lemma max_add_add_right (a b c : α) : max (a + c) (b + c) = max a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply max_add_add_left end end decidable_linear_ordered_cancel_add_comm_monoid /-- A decidable linearly ordered additive commutative group is an additive commutative group with a decidable linear order in which addition is strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_add_comm_group (α : Type u) extends add_comm_group α, decidable_linear_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) instance decidable_linear_ordered_comm_group.to_ordered_add_comm_group (α : Type u) [s : decidable_linear_ordered_add_comm_group α] : ordered_add_comm_group α := { add := s.add, ..s } section decidable_linear_ordered_add_comm_group variables [decidable_linear_ordered_add_comm_group α] @[priority 100] -- see Note [lower instance priority] instance decidable_linear_ordered_add_comm_group.to_decidable_linear_ordered_cancel_add_comm_monoid : decidable_linear_ordered_cancel_add_comm_monoid α := { le_of_add_le_add_left := λ x y z, le_of_add_le_add_left, add_left_cancel := λ x y z, add_left_cancel, add_right_cancel := λ x y z, add_right_cancel, ..‹decidable_linear_ordered_add_comm_group α› } lemma decidable_linear_ordered_add_comm_group.add_lt_add_left (a b : α) (h : a < b) (c : α) : c + a < c + b := ordered_add_comm_group.add_lt_add_left a b h c lemma max_neg_neg (a b : α) : max (-a) (-b) = - min a b := eq.symm (eq_max (show -a ≤ -(min a b), from neg_le_neg $ min_le_left a b) (show -b ≤ -(min a b), from neg_le_neg $ min_le_right a b) (assume d, assume H₁ : -a ≤ d, assume H₂ : -b ≤ d, have H : -d ≤ min a b, from le_min (neg_le_of_neg_le H₁) (neg_le_of_neg_le H₂), show -(min a b) ≤ d, from neg_le_of_neg_le H)) lemma min_eq_neg_max_neg_neg (a b : α) : min a b = - max (-a) (-b) := by rw [max_neg_neg, neg_neg] lemma min_neg_neg (a b : α) : min (-a) (-b) = - max a b := by rw [min_eq_neg_max_neg_neg, neg_neg, neg_neg] lemma max_eq_neg_min_neg_neg (a b : α) : max a b = - min (-a) (-b) := by rw [min_neg_neg, neg_neg] /-- `abs a` is the absolute value of `a`. -/ def abs (a : α) : α := max a (-a) lemma abs_of_nonneg {a : α} (h : 0 ≤ a) : abs a = a := have h' : -a ≤ a, from le_trans (neg_nonpos_of_nonneg h) h, max_eq_left h' lemma abs_of_pos {a : α} (h : 0 < a) : abs a = a := abs_of_nonneg (le_of_lt h) lemma abs_of_nonpos {a : α} (h : a ≤ 0) : abs a = -a := have h' : a ≤ -a, from le_trans h (neg_nonneg_of_nonpos h), max_eq_right h' lemma abs_of_neg {a : α} (h : a < 0) : abs a = -a := abs_of_nonpos (le_of_lt h) lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg (le_refl _) lemma abs_neg (a : α) : abs (-a) = abs a := begin unfold abs, rw [max_comm, neg_neg] end lemma abs_pos_of_pos {a : α} (h : 0 < a) : 0 < abs a := by rwa (abs_of_pos h) lemma abs_pos_of_neg {a : α} (h : a < 0) : 0 < abs a := abs_neg a ▸ abs_pos_of_pos (neg_pos_of_neg h) lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) := by rw [← neg_sub, abs_neg] lemma ne_zero_of_abs_ne_zero {a : α} (h : abs a ≠ 0) : a ≠ 0 := assume ha, h (eq.symm ha ▸ abs_zero) /- these assume a linear order -/ lemma eq_zero_of_neg_eq {a : α} (h : -a = a) : a = 0 := match lt_trichotomy a 0 with | or.inl h₁ := have 0 < a, from h ▸ neg_pos_of_neg h₁, absurd h₁ (lt_asymm this) | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 0, from h ▸ neg_neg_of_pos h₁, absurd h₁ (lt_asymm this) end lemma abs_nonneg (a : α) : 0 ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, by rwa (abs_of_nonneg h)) (assume h : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos h ... = abs a : eq.symm (abs_of_nonpos h)) lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a lemma le_abs_self (a : α) : a ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, begin rw [abs_of_nonneg h] end) (assume h : a ≤ 0, le_trans h $ abs_nonneg a) lemma neg_le_abs_self (a : α) : -a ≤ abs a := abs_neg a ▸ le_abs_self (-a) lemma eq_zero_of_abs_eq_zero {a : α} (h : abs a = 0) : a = 0 := have h₁ : a ≤ 0, from h ▸ le_abs_self a, have h₂ : -a ≤ 0, from h ▸ abs_neg a ▸ le_abs_self (-a), le_antisymm h₁ (nonneg_of_neg_nonpos h₂) lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := have a - b = 0, from eq_zero_of_abs_eq_zero h, show a = b, from eq_of_sub_eq_zero this lemma abs_pos_of_ne_zero {a : α} (h : a ≠ 0) : 0 < abs a := or.elim (lt_or_gt_of_ne h) abs_pos_of_neg abs_pos_of_pos lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := or.elim (le_total 0 a) (assume h : 0 ≤ a, eq.symm (abs_of_nonneg h) ▸ h1) (assume h : a ≤ 0, eq.symm (abs_of_nonpos h) ▸ h2) lemma abs_le_of_le_of_neg_le {a b : α} (h1 : a ≤ b) (h2 : -a ≤ b) : abs a ≤ b := abs_by_cases (λ x : α, x ≤ b) h1 h2 lemma abs_lt_of_lt_of_neg_lt {a b : α} (h1 : a < b) (h2 : -a < b) : abs a < b := abs_by_cases (λ x : α, x < b) h1 h2 private lemma aux1 {a b : α} (h1 : 0 ≤ a + b) (h2 : 0 ≤ a) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume h3 : 0 ≤ b, calc abs (a + b) ≤ abs (a + b) : by apply le_refl ... = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... = abs a + abs b : by rw (abs_of_nonneg h3)) (assume h3 : ¬ 0 ≤ b, have h4 : b ≤ 0, from le_of_lt (lt_of_not_ge h3), calc abs (a + b) = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... ≤ abs a + 0 : add_le_add_left h4 _ ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos h4) _ ... = abs a + abs b : by rw (abs_of_nonpos h4)) private lemma aux2 {a b : α} (h1 : 0 ≤ a + b) : abs (a + b) ≤ abs a + abs b := or.elim (le_total b 0) (assume h2 : b ≤ 0, have h3 : ¬ a < 0, from assume h4 : a < 0, have h5 : a + b < 0, begin have aux := add_lt_add_of_lt_of_le h4 h2, rwa [add_zero] at aux end, not_lt_of_ge h1 h5, aux1 h1 (le_of_not_gt h3)) (assume h2 : 0 ≤ b, begin have h3 : abs (b + a) ≤ abs b + abs a, begin rw add_comm at h1, exact aux1 h1 h2 end, rw [add_comm, add_comm (abs a)], exact h3 end) lemma abs_add_le_abs_add_abs (a b : α) : abs (a + b) ≤ abs a + abs b := or.elim (le_total 0 (a + b)) (assume h2 : 0 ≤ a + b, aux2 h2) (assume h2 : a + b ≤ 0, have h3 : -a + -b = -(a + b), by rw neg_add, have h4 : 0 ≤ -(a + b), from neg_nonneg_of_nonpos h2, have h5 : 0 ≤ -a + -b, begin rw [← h3] at h4, exact h4 end, calc abs (a + b) = abs (-a + -b) : by rw [← abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 h5 ... = abs a + abs b : by rw [abs_neg, abs_neg]) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := have h1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rw sub_add_cancel ... = abs (a - b + b) : by rw sub_add_cancel ... ≤ abs (a - b) + abs b : by apply abs_add_le_abs_add_abs, le_of_add_le_add_right h1 lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left] ... ≤ abs (a - b) + abs (b - c) : by apply abs_add_le_abs_add_abs lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := begin apply le_trans, apply abs_add_le_abs_add_abs, apply le_trans, apply add_le_add_right, apply abs_add_le_abs_add_abs, apply le_refl end lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := begin cases (decidable.em (b ≤ a)) with hba hba, rw (abs_of_nonneg (sub_nonneg_of_le hba)), apply sub_le_sub, apply hau, apply hbl, rw [abs_of_neg (sub_neg_of_lt (lt_of_not_ge hba)), neg_sub], apply sub_le_sub, apply hbu, apply hal end lemma decidable_linear_ordered_add_comm_group.eq_of_abs_sub_nonpos {a b : α} (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) end decidable_linear_ordered_add_comm_group set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) end prio namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `decidable_linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_decidable_linear_ordered_add_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : decidable_linear_ordered_add_comm_group α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace order_dual instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (order_dual α) := { add_le_add_left := λ a b h c, @add_le_add_left α _ b a h _, lt_of_add_lt_add_left := λ a b c h, @lt_of_add_lt_add_left α _ a c b h, ..order_dual.partial_order α, ..show add_comm_monoid α, by apply_instance } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (order_dual α) := { le_of_add_le_add_left := λ a b c : α, le_of_add_le_add_left, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, ..order_dual.ordered_add_comm_monoid } instance [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) := { add_left_neg := λ a : α, add_left_neg a, ..order_dual.ordered_add_comm_monoid, ..show add_comm_group α, by apply_instance } end order_dual
54116372e1379e9c3238c7cffd08aeeecbb30556
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/number_theory/primes_congruent_one.lean
1712603e18984e6ba5af5a2597de599af6157d24
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,680
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.polynomial.cyclotomic import topology.algebra.polynomial import field_theory.finite.basic /-! # Primes congruent to one We prove that, for any positive `k : ℕ`, there are infinitely many primes `p` such that `p ≡ 1 [MOD k]`. -/ namespace nat open polynomial nat filter /-- For any positive `k : ℕ` there are infinitely many primes `p` such that `p ≡ 1 [MOD k]`. -/ lemma exists_prime_ge_modeq_one (k n : ℕ) (hpos : 0 < k) : ∃ (p : ℕ), nat.prime p ∧ n ≤ p ∧ p ≡ 1 [MOD k] := begin have hli : tendsto (abs ∘ (λ (a : ℕ), abs(a : ℚ))) at_top at_top, { simp only [(∘), abs_cast], exact nat.strict_mono_cast.monotone.tendsto_at_top_at_top exists_nat_ge }, have hcff : int.cast_ring_hom ℚ (cyclotomic k ℤ).leading_coeff ≠ 0, { simp only [cyclotomic.monic, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] }, obtain ⟨a, ha⟩ := tendsto_at_top_at_top.1 (tendsto_abv_eval₂_at_top (int.cast_ring_hom ℚ) abs (cyclotomic k ℤ) (degree_cyclotomic_pos k ℤ hpos) hcff hli) 2, let b := a * (k * n.factorial), have hgt : 1 < (eval ↑(a * (k * n.factorial)) (cyclotomic k ℤ)).nat_abs, { suffices hgtabs : 1 < abs (eval ↑b (cyclotomic k ℤ)), { rw [int.abs_eq_nat_abs] at hgtabs, exact_mod_cast hgtabs }, suffices hgtrat : 1 < abs (eval ↑b (cyclotomic k ℚ)), { rw [← map_cyclotomic_int k ℚ, ← int.cast_coe_nat, ← int.coe_cast_ring_hom, eval_map, eval₂_hom, int.coe_cast_ring_hom] at hgtrat, assumption_mod_cast }, suffices hleab : a ≤ b, { replace ha := lt_of_lt_of_le one_lt_two (ha b hleab), rwa [← eval_map, map_cyclotomic_int k ℚ, abs_cast] at ha }, exact le_mul_of_pos_right (mul_pos hpos (factorial_pos n)) }, let p := min_fac (eval ↑b (cyclotomic k ℤ)).nat_abs, haveI hprime : fact p.prime := ⟨min_fac_prime (ne_of_lt hgt).symm⟩, have hroot : is_root (cyclotomic k (zmod p)) (cast_ring_hom (zmod p) b), { rw [is_root.def, ← map_cyclotomic_int k (zmod p), eval_map, coe_cast_ring_hom, ← int.cast_coe_nat, ← int.coe_cast_ring_hom, eval₂_hom, int.coe_cast_ring_hom, zmod.int_coe_zmod_eq_zero_iff_dvd _ _], apply int.dvd_nat_abs.1, exact_mod_cast min_fac_dvd (eval ↑b (cyclotomic k ℤ)).nat_abs }, refine ⟨p, hprime.1, _, _⟩, { by_contra habs, exact (prime.dvd_iff_not_coprime hprime.1).1 (dvd_factorial (min_fac_pos _) (le_of_not_ge habs)) (coprime_of_root_cyclotomic hpos hroot).symm.coprime_mul_left_right.coprime_mul_left_right }, { have hdiv := order_of_dvd_of_pow_eq_one (zmod.units_pow_card_sub_one_eq_one p (zmod.unit_of_coprime b (coprime_of_root_cyclotomic hpos hroot))), have : ¬p ∣ k := hprime.1.coprime_iff_not_dvd.1 (coprime_of_root_cyclotomic hpos hroot).symm.coprime_mul_left_right.coprime_mul_right_right, rw [order_of_root_cyclotomic hpos this hroot] at hdiv, exact ((modeq.modeq_iff_dvd' hprime.1.pos).2 hdiv).symm } end lemma frequently_at_top_modeq_one (k : ℕ) (hpos : 0 < k) : ∃ᶠ p in at_top, nat.prime p ∧ p ≡ 1 [MOD k] := begin refine frequently_at_top.2 (λ n, _), obtain ⟨p, hp⟩ := exists_prime_ge_modeq_one k n hpos, exact ⟨p, ⟨hp.2.1, hp.1, hp.2.2⟩⟩ end lemma infinite_set_of_prime_modeq_one (k : ℕ) (hpos : 0 < k) : set.infinite {p : ℕ | nat.prime p ∧ p ≡ 1 [MOD k]} := frequently_at_top_iff_infinite.1 (frequently_at_top_modeq_one k hpos) end nat
423676a1fa548d83cef194fe15a73a2d0402c4aa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/polynomial/opposites.lean
4ecea9805d529e172ebf79fefc3e1d7701b6dba5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,254
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.degree.definitions /-! # Interactions between `R[X]` and `Rᵐᵒᵖ[X]` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the basic API for "pushing through" the isomorphism `op_ring_equiv : R[X]ᵐᵒᵖ ≃+* Rᵐᵒᵖ[X]`. It allows going back and forth between a polynomial ring over a semiring and the polynomial ring over the opposite semiring. -/ open_locale polynomial open polynomial mul_opposite variables {R : Type*} [semiring R] {p q : R[X]} noncomputable theory namespace polynomial /-- Ring isomorphism between `R[X]ᵐᵒᵖ` and `Rᵐᵒᵖ[X]` sending each coefficient of a polynomial to the corresponding element of the opposite ring. -/ def op_ring_equiv (R : Type*) [semiring R] : R[X]ᵐᵒᵖ ≃+* Rᵐᵒᵖ[X] := ((to_finsupp_iso R).op.trans add_monoid_algebra.op_ring_equiv).trans (to_finsupp_iso _).symm -- for maintenance purposes: `by simp [op_ring_equiv]` proves this lemma /-! Lemmas to get started, using `op_ring_equiv R` on the various expressions of `finsupp.single`: `monomial`, `C a`, `X`, `C a * X ^ n`. -/ @[simp] lemma op_ring_equiv_op_monomial (n : ℕ) (r : R) : op_ring_equiv R (op (monomial n r : R[X])) = monomial n (op r) := by simp only [op_ring_equiv, ring_equiv.trans_apply, ring_equiv.op_apply_apply, ring_equiv.to_add_equiv_eq_coe, add_equiv.mul_op_apply, add_equiv.to_fun_eq_coe, add_equiv.coe_trans, op_add_equiv_apply, ring_equiv.coe_to_add_equiv, op_add_equiv_symm_apply, function.comp_app, unop_op, to_finsupp_iso_apply, to_finsupp_monomial, add_monoid_algebra.op_ring_equiv_single, to_finsupp_iso_symm_apply, of_finsupp_single] @[simp] lemma op_ring_equiv_op_C (a : R) : op_ring_equiv R (op (C a)) = C (op a) := op_ring_equiv_op_monomial 0 a @[simp] lemma op_ring_equiv_op_X : op_ring_equiv R (op (X : R[X])) = X := op_ring_equiv_op_monomial 1 1 lemma op_ring_equiv_op_C_mul_X_pow (r : R) (n : ℕ) : op_ring_equiv R (op (C r * X ^ n : R[X])) = C (op r) * X ^ n := by simp only [X_pow_mul, op_mul, op_pow, map_mul, map_pow, op_ring_equiv_op_X, op_ring_equiv_op_C] /-! Lemmas to get started, using `(op_ring_equiv R).symm` on the various expressions of `finsupp.single`: `monomial`, `C a`, `X`, `C a * X ^ n`. -/ @[simp] lemma op_ring_equiv_symm_monomial (n : ℕ) (r : Rᵐᵒᵖ) : (op_ring_equiv R).symm (monomial n r) = op (monomial n (unop r)) := (op_ring_equiv R).injective (by simp) @[simp] lemma op_ring_equiv_symm_C (a : Rᵐᵒᵖ) : (op_ring_equiv R).symm (C a) = op (C (unop a)) := op_ring_equiv_symm_monomial 0 a @[simp] lemma op_ring_equiv_symm_X : (op_ring_equiv R).symm (X : Rᵐᵒᵖ[X]) = op X := op_ring_equiv_symm_monomial 1 1 lemma op_ring_equiv_symm_C_mul_X_pow (r : Rᵐᵒᵖ) (n : ℕ) : (op_ring_equiv R).symm (C r * X ^ n : Rᵐᵒᵖ[X]) = op (C (unop r) * X ^ n) := by rw [C_mul_X_pow_eq_monomial, op_ring_equiv_symm_monomial, ← C_mul_X_pow_eq_monomial] /-! Lemmas about more global properties of polynomials and opposites. -/ @[simp] lemma coeff_op_ring_equiv (p : R[X]ᵐᵒᵖ) (n : ℕ) : (op_ring_equiv R p).coeff n = op ((unop p).coeff n) := begin induction p using mul_opposite.rec, cases p, refl end @[simp] lemma support_op_ring_equiv (p : R[X]ᵐᵒᵖ) : (op_ring_equiv R p).support = (unop p).support := begin induction p using mul_opposite.rec, cases p, exact finsupp.support_map_range_of_injective _ _ op_injective end @[simp] lemma nat_degree_op_ring_equiv (p : R[X]ᵐᵒᵖ) : (op_ring_equiv R p).nat_degree = (unop p).nat_degree := begin by_cases p0 : p = 0, { simp only [p0, _root_.map_zero, nat_degree_zero, unop_zero] }, { simp only [p0, nat_degree_eq_support_max', ne.def, add_equiv_class.map_eq_zero_iff, not_false_iff, support_op_ring_equiv, unop_eq_zero_iff] } end @[simp] lemma leading_coeff_op_ring_equiv (p : R[X]ᵐᵒᵖ) : (op_ring_equiv R p).leading_coeff = op (unop p).leading_coeff := by rw [leading_coeff, coeff_op_ring_equiv, nat_degree_op_ring_equiv, leading_coeff] end polynomial
223e5e1ee82df3f1635336da17599f5f1393784d
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/rc_tests.lean
32474d3a1ea52fdf9f8369f1b61b88cc91775a0d
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
1,129
lean
universes u v -- set_option pp.binder_types false set_option pp.explicit true set_option trace.compiler.llnf true -- set_option trace.compiler.boxed true namespace x1 def f (x : Bool) (y z : Nat) : Nat := match x with | true => y | false => z + y + y end x1 namespace x2 def f (x : Nat) : Nat := x end x2 namespace x3 def f (x y : Nat) : Nat := x end x3 namespace x4 @[noinline] def h (x y : Nat) : Nat := x + y def f1 (x y : Nat) : Nat := h x y def f2 (x y : Nat) : Nat := h (h x y) (h y x) def f3 (x y : Nat) : Nat := h (h x x) x def f4 (x y : Nat) : Nat := h (h 1 0) x def f5 (x y : Nat) : Nat := h (h 1 1) x end x4 namespace x5 partial def myMap {α : Type u} {β : Type v} (f : α → β) : List α → List β | [] => [] | x::xs => f x :: myMap f xs end x5 namespace x6 @[noinline] def act : StateM Nat Unit := modify (fun a => a + 1) def f : StateM Nat Unit := act *> act end x6 namespace x7 inductive S | v1 | v2 | v3 def foo : S → S × S | S.v1 => (S.v2, S.v1) | S.v2 => (S.v3, S.v2) | S.v3 => (S.v1, S.v2) end x7 namespace x8 def f (x : Nat) : List Nat := x :: x :: [] end x8
94d2ec5af8854a2feefb2b0a7e5d03ea91c52252
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/phashmap_inst_coherence.lean
9985cf2695d6a5ff00f0e04ce0cb62d575fde0e1
[ "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
370
lean
import Std.Data.PersistentHashMap open Std def m : PersistentHashMap Nat Nat := let m : PersistentHashMap Nat Nat := {}; m.insert 1 1 def natDiffHash : Hashable Nat := ⟨fun n => UInt64.ofNat $ n+10⟩ -- The following example should fail since the `Hashable` instance used to create `m` is not `natDiffHash` #eval @PersistentHashMap.find? Nat Nat _ natDiffHash m 1
bd4680ac85288a8429e9ff5fe117b0dccd44bf19
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/continuous_function/compact.lean
a9e1834733f461325599f564a2cf8616a822dca4
[ "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
17,883
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 topology.continuous_function.bounded import topology.uniform_space.compact import topology.compact_open import topology.sets.compacts /-! # Continuous functions on a compact space Continuous functions `C(α, β)` from a compact space `α` to a metric space `β` are automatically bounded, and so acquire various structures inherited from `α →ᵇ β`. This file transfers these structures, and restates some lemmas characterising these structures. If you need a lemma which is proved about `α →ᵇ β` but not for `C(α, β)` when `α` is compact, you should restate it here. You can also use `bounded_continuous_function.equiv_continuous_map_of_compact` to move functions back and forth. -/ noncomputable theory open_locale topological_space classical nnreal bounded_continuous_function big_operators open set filter metric open bounded_continuous_function namespace continuous_map variables {α β E : Type*} [topological_space α] [compact_space α] [metric_space β] [normed_add_comm_group E] section variables (α β) /-- When `α` is compact, the bounded continuous maps `α →ᵇ β` are equivalent to `C(α, β)`. -/ @[simps { fully_applied := ff }] def equiv_bounded_of_compact : C(α, β) ≃ (α →ᵇ β) := ⟨mk_of_compact, bounded_continuous_function.to_continuous_map, λ f, by { ext, refl, }, λ f, by { ext, refl, }⟩ lemma uniform_inducing_equiv_bounded_of_compact : uniform_inducing (equiv_bounded_of_compact α β) := uniform_inducing.mk' begin simp only [has_basis_compact_convergence_uniformity.mem_iff, uniformity_basis_dist_le.mem_iff], exact λ s, ⟨λ ⟨⟨a, b⟩, ⟨ha, ⟨ε, hε, hb⟩⟩, hs⟩, ⟨{p | ∀ x, (p.1 x, p.2 x) ∈ b}, ⟨ε, hε, λ _ h x, hb (by exact (dist_le hε.le).mp h x)⟩, λ f g h, hs (by exact λ x hx, h x)⟩, λ ⟨t, ⟨ε, hε, ht⟩, hs⟩, ⟨⟨set.univ, {p | dist p.1 p.2 ≤ ε}⟩, ⟨is_compact_univ, ⟨ε, hε, λ _ h, h⟩⟩, λ ⟨f, g⟩ h, hs _ _ (ht (by exact (dist_le hε.le).mpr (λ x, h x (mem_univ x))))⟩⟩, end lemma uniform_embedding_equiv_bounded_of_compact : uniform_embedding (equiv_bounded_of_compact α β) := { inj := (equiv_bounded_of_compact α β).injective, .. uniform_inducing_equiv_bounded_of_compact α β } /-- When `α` is compact, the bounded continuous maps `α →ᵇ 𝕜` are additively equivalent to `C(α, 𝕜)`. -/ @[simps apply symm_apply { fully_applied := ff }] def add_equiv_bounded_of_compact [add_monoid β] [has_lipschitz_add β] : C(α, β) ≃+ (α →ᵇ β) := ({ .. to_continuous_map_add_hom α β, .. (equiv_bounded_of_compact α β).symm, } : (α →ᵇ β) ≃+ C(α, β)).symm instance : metric_space C(α, β) := (uniform_embedding_equiv_bounded_of_compact α β).comap_metric_space _ /-- When `α` is compact, and `β` is a metric space, the bounded continuous maps `α →ᵇ β` are isometric to `C(α, β)`. -/ @[simps to_equiv apply symm_apply { fully_applied := ff }] def isometric_bounded_of_compact : C(α, β) ≃ᵢ (α →ᵇ β) := { isometry_to_fun := λ x y, rfl, to_equiv := equiv_bounded_of_compact α β } end @[simp] lemma _root_.bounded_continuous_function.dist_mk_of_compact (f g : C(α, β)) : dist (mk_of_compact f) (mk_of_compact g) = dist f g := rfl @[simp] lemma _root_.bounded_continuous_function.dist_to_continuous_map (f g : α →ᵇ β) : dist (f.to_continuous_map) (g.to_continuous_map) = dist f g := rfl open bounded_continuous_function section variables {α β} {f g : C(α, β)} {C : ℝ} /-- The pointwise distance is controlled by the distance between functions, by definition. -/ lemma dist_apply_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := by simp only [← dist_mk_of_compact, dist_coe_le_dist, ← mk_of_compact_apply] /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C := by simp only [← dist_mk_of_compact, dist_le C0, mk_of_compact_apply] lemma dist_le_iff_of_nonempty [nonempty α] : dist f g ≤ C ↔ ∀ x, dist (f x) (g x) ≤ C := by simp only [← dist_mk_of_compact, dist_le_iff_of_nonempty, mk_of_compact_apply] lemma dist_lt_iff_of_nonempty [nonempty α] : dist f g < C ↔ ∀x:α, dist (f x) (g x) < C := by simp only [← dist_mk_of_compact, dist_lt_iff_of_nonempty_compact, mk_of_compact_apply] lemma dist_lt_of_nonempty [nonempty α] (w : ∀x:α, dist (f x) (g x) < C) : dist f g < C := (dist_lt_iff_of_nonempty).2 w lemma dist_lt_iff (C0 : (0 : ℝ) < C) : dist f g < C ↔ ∀x:α, dist (f x) (g x) < C := by simp only [← dist_mk_of_compact, dist_lt_iff_of_compact C0, mk_of_compact_apply] end instance [complete_space β] : complete_space (C(α, β)) := (isometric_bounded_of_compact α β).complete_space /-- See also `continuous_map.continuous_eval'` -/ @[continuity] lemma continuous_eval : continuous (λ p : C(α, β) × α, p.1 p.2) := continuous_eval.comp ((isometric_bounded_of_compact α β).continuous.prod_map continuous_id) /-- See also `continuous_map.continuous_eval_const` -/ @[continuity] lemma continuous_eval_const (x : α) : continuous (λ f : C(α, β), f x) := continuous_eval.comp (continuous_id.prod_mk continuous_const) /-- See also `continuous_map.continuous_coe'` -/ lemma continuous_coe : @continuous (C(α, β)) (α → β) _ _ coe_fn := continuous_pi continuous_eval_const -- TODO at some point we will need lemmas characterising this norm! -- At the moment the only way to reason about it is to transfer `f : C(α,E)` back to `α →ᵇ E`. instance : has_norm C(α, E) := { norm := λ x, dist x 0 } @[simp] lemma _root_.bounded_continuous_function.norm_mk_of_compact (f : C(α, E)) : ‖mk_of_compact f‖ = ‖f‖ := rfl @[simp] lemma _root_.bounded_continuous_function.norm_to_continuous_map_eq (f : α →ᵇ E) : ‖f.to_continuous_map‖ = ‖f‖ := rfl open bounded_continuous_function instance : normed_add_comm_group C(α, E) := { dist_eq := λ x y, by rw [← norm_mk_of_compact, ← dist_mk_of_compact, dist_eq_norm, mk_of_compact_sub], dist := dist, norm := norm, .. continuous_map.metric_space _ _, .. continuous_map.add_comm_group } instance [nonempty α] [has_one E] [norm_one_class E] : norm_one_class C(α, E) := { norm_one := by simp only [←norm_mk_of_compact, mk_of_compact_one, norm_one] } section variables (f : C(α, E)) -- The corresponding lemmas for `bounded_continuous_function` are stated with `{f}`, -- and so can not be used in dot notation. lemma norm_coe_le_norm (x : α) : ‖f x‖ ≤ ‖f‖ := (mk_of_compact f).norm_coe_le_norm x /-- Distance between the images of any two points is at most twice the norm of the function. -/ lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ‖f‖ := (mk_of_compact f).dist_le_two_norm x y /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le {C : ℝ} (C0 : (0 : ℝ) ≤ C) : ‖f‖ ≤ C ↔ ∀x:α, ‖f x‖ ≤ C := @bounded_continuous_function.norm_le _ _ _ _ (mk_of_compact f) _ C0 lemma norm_le_of_nonempty [nonempty α] {M : ℝ} : ‖f‖ ≤ M ↔ ∀ x, ‖f x‖ ≤ M := @bounded_continuous_function.norm_le_of_nonempty _ _ _ _ _ (mk_of_compact f) _ lemma norm_lt_iff {M : ℝ} (M0 : 0 < M) : ‖f‖ < M ↔ ∀ x, ‖f x‖ < M := @bounded_continuous_function.norm_lt_iff_of_compact _ _ _ _ _ (mk_of_compact f) _ M0 theorem nnnorm_lt_iff {M : ℝ≥0} (M0 : 0 < M) : ‖f‖₊ < M ↔ ∀ (x : α), ‖f x‖₊ < M := f.norm_lt_iff M0 lemma norm_lt_iff_of_nonempty [nonempty α] {M : ℝ} : ‖f‖ < M ↔ ∀ x, ‖f x‖ < M := @bounded_continuous_function.norm_lt_iff_of_nonempty_compact _ _ _ _ _ _ (mk_of_compact f) _ lemma nnnorm_lt_iff_of_nonempty [nonempty α] {M : ℝ≥0} : ‖f‖₊ < M ↔ ∀ x, ‖f x‖₊ < M := f.norm_lt_iff_of_nonempty lemma apply_le_norm (f : C(α, ℝ)) (x : α) : f x ≤ ‖f‖ := le_trans (le_abs.mpr (or.inl (le_refl (f x)))) (f.norm_coe_le_norm x) lemma neg_norm_le_apply (f : C(α, ℝ)) (x : α) : -‖f‖ ≤ f x := le_trans (neg_le_neg (f.norm_coe_le_norm x)) (neg_le.mp (neg_le_abs_self (f x))) lemma norm_eq_supr_norm : ‖f‖ = ⨆ x : α, ‖f x‖ := (mk_of_compact f).norm_eq_supr_norm end section variables {R : Type*} [normed_ring R] instance : normed_ring C(α,R) := { norm_mul := λ f g, norm_mul_le (mk_of_compact f) (mk_of_compact g), ..(infer_instance : normed_add_comm_group C(α,R)), .. continuous_map.ring } end section variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] instance : normed_space 𝕜 C(α,E) := { norm_smul_le := λ c f, le_of_eq (norm_smul c (mk_of_compact f)) } section variables (α 𝕜 E) /-- When `α` is compact and `𝕜` is a normed field, the `𝕜`-algebra of bounded continuous maps `α →ᵇ β` is `𝕜`-linearly isometric to `C(α, β)`. -/ def linear_isometry_bounded_of_compact : C(α, E) ≃ₗᵢ[𝕜] (α →ᵇ E) := { map_smul' := λ c f, by { ext, simp, }, norm_map' := λ f, rfl, .. add_equiv_bounded_of_compact α E } end -- this lemma and the next are the analogues of those autogenerated by `@[simps]` for -- `equiv_bounded_of_compact`, `add_equiv_bounded_of_compact` @[simp] lemma linear_isometry_bounded_of_compact_symm_apply (f : α →ᵇ E) : (linear_isometry_bounded_of_compact α E 𝕜).symm f = f.to_continuous_map := rfl @[simp] lemma linear_isometry_bounded_of_compact_apply_apply (f : C(α, E)) (a : α) : (linear_isometry_bounded_of_compact α E 𝕜 f) a = f a := rfl @[simp] lemma linear_isometry_bounded_of_compact_to_isometric : (linear_isometry_bounded_of_compact α E 𝕜).to_isometric = (isometric_bounded_of_compact α E) := rfl @[simp] lemma linear_isometry_bounded_of_compact_to_add_equiv : (linear_isometry_bounded_of_compact α E 𝕜).to_linear_equiv.to_add_equiv = (add_equiv_bounded_of_compact α E) := rfl @[simp] lemma linear_isometry_bounded_of_compact_of_compact_to_equiv : (linear_isometry_bounded_of_compact α E 𝕜).to_linear_equiv.to_equiv = (equiv_bounded_of_compact α E) := rfl end section variables {𝕜 : Type*} {γ : Type*} [normed_field 𝕜] [normed_ring γ] [normed_algebra 𝕜 γ] instance : normed_algebra 𝕜 C(α, γ) := { ..continuous_map.normed_space } end end continuous_map namespace continuous_map section uniform_continuity variables {α β : Type*} variables [metric_space α] [compact_space α] [metric_space β] /-! We now set up some declarations making it convenient to use uniform continuity. -/ lemma uniform_continuity (f : C(α, β)) (ε : ℝ) (h : 0 < ε) : ∃ δ > 0, ∀ {x y}, dist x y < δ → dist (f x) (f y) < ε := metric.uniform_continuous_iff.mp (compact_space.uniform_continuous_of_continuous f.continuous) ε h /-- An arbitrarily chosen modulus of uniform continuity for a given function `f` and `ε > 0`. -/ -- This definition allows us to separate the choice of some `δ`, -- and the corresponding use of `dist a b < δ → dist (f a) (f b) < ε`, -- even across different declarations. def modulus (f : C(α, β)) (ε : ℝ) (h : 0 < ε) : ℝ := classical.some (uniform_continuity f ε h) lemma modulus_pos (f : C(α, β)) {ε : ℝ} {h : 0 < ε} : 0 < f.modulus ε h := (classical.some_spec (uniform_continuity f ε h)).fst lemma dist_lt_of_dist_lt_modulus (f : C(α, β)) (ε : ℝ) (h : 0 < ε) {a b : α} (w : dist a b < f.modulus ε h) : dist (f a) (f b) < ε := (classical.some_spec (uniform_continuity f ε h)).snd w end uniform_continuity end continuous_map section comp_left variables (X : Type*) {𝕜 β γ : Type*} [topological_space X] [compact_space X] [nontrivially_normed_field 𝕜] variables [normed_add_comm_group β] [normed_space 𝕜 β] [normed_add_comm_group γ] [normed_space 𝕜 γ] open continuous_map /-- Postcomposition of continuous functions into a normed module by a continuous linear map is a continuous linear map. Transferred version of `continuous_linear_map.comp_left_continuous_bounded`, upgraded version of `continuous_linear_map.comp_left_continuous`, similar to `linear_map.comp_left`. -/ protected def continuous_linear_map.comp_left_continuous_compact (g : β →L[𝕜] γ) : C(X, β) →L[𝕜] C(X, γ) := (linear_isometry_bounded_of_compact X γ 𝕜).symm.to_linear_isometry.to_continuous_linear_map.comp $ (g.comp_left_continuous_bounded X).comp $ (linear_isometry_bounded_of_compact X β 𝕜).to_linear_isometry.to_continuous_linear_map @[simp] lemma continuous_linear_map.to_linear_comp_left_continuous_compact (g : β →L[𝕜] γ) : (g.comp_left_continuous_compact X : C(X, β) →ₗ[𝕜] C(X, γ)) = g.comp_left_continuous 𝕜 X := by { ext f, refl } @[simp] lemma continuous_linear_map.comp_left_continuous_compact_apply (g : β →L[𝕜] γ) (f : C(X, β)) (x : X) : g.comp_left_continuous_compact X f x = g (f x) := rfl end comp_left namespace continuous_map /-! We now setup variations on `comp_right_* f`, where `f : C(X, Y)` (that is, precomposition by a continuous map), as a morphism `C(Y, T) → C(X, T)`, respecting various types of structure. In particular: * `comp_right_continuous_map`, the bundled continuous map (for this we need `X Y` compact). * `comp_right_homeomorph`, when we precompose by a homeomorphism. * `comp_right_alg_hom`, when `T = R` is a topological ring. -/ section comp_right /-- Precomposition by a continuous map is itself a continuous map between spaces of continuous maps. -/ def comp_right_continuous_map {X Y : Type*} (T : Type*) [topological_space X] [compact_space X] [topological_space Y] [compact_space Y] [metric_space T] (f : C(X, Y)) : C(C(Y, T), C(X, T)) := { to_fun := λ g, g.comp f, continuous_to_fun := begin refine metric.continuous_iff.mpr _, intros g ε ε_pos, refine ⟨ε, ε_pos, λ g' h, _⟩, rw continuous_map.dist_lt_iff ε_pos at h ⊢, { exact λ x, h (f x), }, end } @[simp] lemma comp_right_continuous_map_apply {X Y : Type*} (T : Type*) [topological_space X] [compact_space X] [topological_space Y] [compact_space Y] [metric_space T] (f : C(X, Y)) (g : C(Y, T)) : (comp_right_continuous_map T f) g = g.comp f := rfl /-- Precomposition by a homeomorphism is itself a homeomorphism between spaces of continuous maps. -/ def comp_right_homeomorph {X Y : Type*} (T : Type*) [topological_space X] [compact_space X] [topological_space Y] [compact_space Y] [metric_space T] (f : X ≃ₜ Y) : C(Y, T) ≃ₜ C(X, T) := { to_fun := comp_right_continuous_map T f.to_continuous_map, inv_fun := comp_right_continuous_map T f.symm.to_continuous_map, left_inv := λ g, ext $ λ _, congr_arg g (f.apply_symm_apply _), right_inv := λ g, ext $ λ _, congr_arg g (f.symm_apply_apply _) } lemma comp_right_alg_hom_continuous {X Y : Type*} (R A : Type*) [topological_space X] [compact_space X] [topological_space Y] [compact_space Y] [comm_semiring R] [semiring A] [metric_space A] [topological_semiring A] [algebra R A] (f : C(X, Y)) : continuous (comp_right_alg_hom R A f) := map_continuous (comp_right_continuous_map A f) end comp_right section weierstrass open topological_space variables {X : Type*} [topological_space X] [t2_space X] [locally_compact_space X] variables {E : Type*} [normed_add_comm_group E] [complete_space E] lemma summable_of_locally_summable_norm {ι : Type*} {F : ι → C(X, E)} (hF : ∀ K : compacts X, summable (λ i, ‖(F i).restrict K‖)) : summable F := begin refine (continuous_map.exists_tendsto_compact_open_iff_forall _).2 (λ K hK, _), lift K to compacts X using hK, have A : ∀ s : finset ι, restrict ↑K (∑ i in s, F i) = ∑ i in s, restrict K (F i), { intro s, ext1 x, simp }, simpa only [has_sum, A] using summable_of_summable_norm (hF K) end end weierstrass /-! ### Star structures In this section, if `β` is a normed ⋆-group, then so is the space of continuous functions from `α` to `β`, by using the star operation pointwise. Furthermore, if `α` is compact and `β` is a C⋆-ring, then `C(α, β)` is a C⋆-ring. -/ section normed_space variables {α : Type*} {β : Type*} variables [topological_space α] [normed_add_comm_group β] [star_add_monoid β] [normed_star_group β] lemma _root_.bounded_continuous_function.mk_of_compact_star [compact_space α] (f : C(α, β)) : mk_of_compact (star f) = star (mk_of_compact f) := rfl instance [compact_space α] : normed_star_group C(α, β) := { norm_star := λ f, by rw [←bounded_continuous_function.norm_mk_of_compact, bounded_continuous_function.mk_of_compact_star, norm_star, bounded_continuous_function.norm_mk_of_compact] } end normed_space section cstar_ring variables {α : Type*} {β : Type*} variables [topological_space α] [normed_ring β] [star_ring β] instance [compact_space α] [cstar_ring β] : cstar_ring C(α, β) := { norm_star_mul_self := begin intros f, refine le_antisymm _ _, { rw [←sq, continuous_map.norm_le _ (sq_nonneg _)], intro x, simp only [continuous_map.coe_mul, coe_star, pi.mul_apply, pi.star_apply, cstar_ring.norm_star_mul_self, ←sq], refine sq_le_sq' _ _, { linarith [norm_nonneg (f x), norm_nonneg f] }, { exact continuous_map.norm_coe_le_norm f x }, }, { rw [←sq, ←real.le_sqrt (norm_nonneg _) (norm_nonneg _), continuous_map.norm_le _ (real.sqrt_nonneg _)], intro x, rw [real.le_sqrt (norm_nonneg _) (norm_nonneg _), sq, ←cstar_ring.norm_star_mul_self], exact continuous_map.norm_coe_le_norm (star f * f) x }, end } end cstar_ring end continuous_map
3f3e8f0a3a6c8c04ad3c5b06d5b2b8864f19d5df
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/group/basic.lean
9abda0620f2dba3348cd81988ad900cecc68827f
[ "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
66,930
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import group_theory.group_action.conj_act import group_theory.group_action.quotient import group_theory.quotient_group import order.filter.pointwise import topology.algebra.monoid import topology.algebra.constructions /-! # Topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space function open_locale classical topological_space filter pointwise universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[simp, to_additive] lemma homeomorph.coe_mul_left (a : G) : ⇑(homeomorph.mul_left a) = (*) a := rfl @[to_additive] lemma homeomorph.mul_left_symm (a : G) : (homeomorph.mul_left a).symm = homeomorph.mul_left a⁻¹ := by { ext, refl } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive is_open.left_add_coset] lemma is_open.left_coset {U : set G} (h : is_open U) (x : G) : is_open (left_coset x U) := is_open_map_mul_left x _ h @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map @[to_additive is_closed.left_add_coset] lemma is_closed.left_coset {U : set G} (h : is_closed U) (x : G) : is_closed (left_coset x U) := is_closed_map_mul_left x _ h /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[simp, to_additive] lemma homeomorph.coe_mul_right (a : G) : ⇑(homeomorph.mul_right a) = λ g, g * a := rfl @[to_additive] lemma homeomorph.mul_right_symm (a : G) : (homeomorph.mul_right a).symm = homeomorph.mul_right a⁻¹ := by { ext, refl } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive is_open.right_add_coset] lemma is_open.right_coset {U : set G} (h : is_open U) (x : G) : is_open (right_coset U x) := is_open_map_mul_right x _ h @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive is_closed.right_add_coset] lemma is_closed.right_coset {U : set G} (h : is_closed U) (x : G) : is_closed (right_coset U x) := is_closed_map_mul_right x _ h @[to_additive] lemma discrete_topology_of_open_singleton_one (h : is_open ({1} : set G)) : discrete_topology G := begin rw ← singletons_open_iff_discrete, intro g, suffices : {g} = (λ (x : G), g⁻¹ * x) ⁻¹' {1}, { rw this, exact (continuous_mul_left (g⁻¹)).is_open_preimage _ h, }, simp only [mul_one, set.preimage_mul_left_singleton, eq_self_iff_true, inv_inv, set.singleton_eq_singleton_iff], end @[to_additive] lemma discrete_topology_iff_open_singleton_one : discrete_topology G ↔ is_open ({1} : set G) := ⟨λ h, forall_open_iff_discrete.mpr h {1}, discrete_topology_of_open_singleton_one⟩ end continuous_mul_group /-! ### `has_continuous_inv` and `has_continuous_neg` -/ /-- Basic hypothesis to talk about a topological additive group. A topological additive group over `M`, for example, is obtained by requiring the instances `add_group M` and `has_continuous_add M` and `has_continuous_neg M`. -/ class has_continuous_neg (G : Type u) [topological_space G] [has_neg G] : Prop := (continuous_neg : continuous (λ a : G, -a)) /-- Basic hypothesis to talk about a topological group. A topological group over `M`, for example, is obtained by requiring the instances `group M` and `has_continuous_mul M` and `has_continuous_inv M`. -/ @[to_additive] class has_continuous_inv (G : Type u) [topological_space G] [has_inv G] : Prop := (continuous_inv : continuous (λ a : G, a⁻¹)) export has_continuous_inv (continuous_inv) export has_continuous_neg (continuous_neg) section continuous_inv variables [topological_space G] [has_inv G] [has_continuous_inv G] @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive "If a function converges to a value in an additive topological group, then its negation converges to the negation of this value."] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf @[to_additive] lemma continuous_at.inv (hf : continuous_at f x) : continuous_at (λ x, (f x)⁻¹) x := continuous_at_inv.comp hf @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[to_additive] instance [topological_space H] [has_inv H] [has_continuous_inv H] : has_continuous_inv (G × H) := ⟨continuous_inv.fst'.prod_mk continuous_inv.snd'⟩ variable {ι : Type*} @[to_additive] instance pi.has_continuous_inv {C : ι → Type*} [∀ i, topological_space (C i)] [∀ i, has_inv (C i)] [∀ i, has_continuous_inv (C i)] : has_continuous_inv (Π i, C i) := { continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) } /-- A version of `pi.has_continuous_inv` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_inv` for non-dependent functions. -/ @[to_additive "A version of `pi.has_continuous_neg` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_neg` for non-dependent functions."] instance pi.has_continuous_inv' : has_continuous_inv (ι → G) := pi.has_continuous_inv @[priority 100, to_additive] instance has_continuous_inv_of_discrete_topology [topological_space H] [has_inv H] [discrete_topology H] : has_continuous_inv H := ⟨continuous_of_discrete_topology⟩ section pointwise_limits variables (G₁ G₂ : Type*) [topological_space G₂] [t2_space G₂] @[to_additive] lemma is_closed_set_of_map_inv [has_inv G₁] [has_inv G₂] [has_continuous_inv G₂] : is_closed {f : G₁ → G₂ | ∀ x, f x⁻¹ = (f x)⁻¹ } := begin simp only [set_of_forall], refine is_closed_Inter (λ i, is_closed_eq (continuous_apply _) (continuous_apply _).inv), end end pointwise_limits instance [topological_space H] [has_inv H] [has_continuous_inv H] : has_continuous_neg (additive H) := { continuous_neg := @continuous_inv H _ _ _ } instance [topological_space H] [has_neg H] [has_continuous_neg H] : has_continuous_inv (multiplicative H) := { continuous_inv := @continuous_neg H _ _ _ } end continuous_inv section continuous_involutive_inv variables [topological_space G] [has_involutive_inv G] [has_continuous_inv G] {s : set G} @[to_additive] lemma is_compact.inv (hs : is_compact s) : is_compact s⁻¹ := by { rw [← image_inv], exact hs.image continuous_inv } variables (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv (G : Type*) [topological_space G] [has_involutive_inv G] [has_continuous_inv G] : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma is_open_map_inv : is_open_map (has_inv.inv : G → G) := (homeomorph.inv _).is_open_map @[to_additive] lemma is_closed_map_inv : is_closed_map (has_inv.inv : G → G) := (homeomorph.inv _).is_closed_map variables {G} @[to_additive] lemma is_open.inv (hs : is_open s) : is_open s⁻¹ := hs.preimage continuous_inv @[to_additive] lemma is_closed.inv (hs : is_closed s) : is_closed s⁻¹ := hs.preimage continuous_inv @[to_additive] lemma inv_closure : ∀ s : set G, (closure s)⁻¹ = closure s⁻¹ := (homeomorph.inv G).preimage_closure end continuous_involutive_inv section lattice_ops variables {ι' : Sort*} [has_inv G] @[to_additive] lemma has_continuous_inv_Inf {ts : set (topological_space G)} (h : Π t ∈ ts, @has_continuous_inv G t _) : @has_continuous_inv G (Inf ts) _ := { continuous_inv := continuous_Inf_rng.2 (λ t ht, continuous_Inf_dom ht (@has_continuous_inv.continuous_inv G t _ (h t ht))) } @[to_additive] lemma has_continuous_inv_infi {ts' : ι' → topological_space G} (h' : Π i, @has_continuous_inv G (ts' i) _) : @has_continuous_inv G (⨅ i, ts' i) _ := by {rw ← Inf_range, exact has_continuous_inv_Inf (set.forall_range_iff.mpr h')} @[to_additive] lemma has_continuous_inv_inf {t₁ t₂ : topological_space G} (h₁ : @has_continuous_inv G t₁ _) (h₂ : @has_continuous_inv G t₂ _) : @has_continuous_inv G (t₁ ⊓ t₂) _ := by { rw inf_eq_infi, refine has_continuous_inv_infi (λ b, _), cases b; assumption } end lattice_ops @[to_additive] lemma inducing.has_continuous_inv {G H : Type*} [has_inv G] [has_inv H] [topological_space G] [topological_space H] [has_continuous_inv H] {f : G → H} (hf : inducing f) (hf_inv : ∀ x, f x⁻¹ = (f x)⁻¹) : has_continuous_inv G := ⟨hf.continuous_iff.2 $ by simpa only [(∘), hf_inv] using hf.continuous.inv⟩ section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G, has_continuous_neg G : Prop /-- A topological group is a group in which the multiplication and inversion operations are continuous. When you declare an instance that does not already have a `uniform_space` instance, you should also provide an instance of `uniform_space` and `uniform_group` using `topological_group.to_uniform_space` and `topological_comm_group_is_uniform`. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G, has_continuous_inv G : Prop section conj instance conj_act.units_has_continuous_const_smul {M} [monoid M] [topological_space M] [has_continuous_mul M] : has_continuous_const_smul (conj_act Mˣ) M := ⟨λ m, (continuous_const.mul continuous_id).mul continuous_const⟩ /-- we slightly weaken the type class assumptions here so that it will also apply to `ennreal`, but we nevertheless leave it in the `topological_group` namespace. -/ variables [topological_space G] [has_inv G] [has_mul G] [has_continuous_mul G] /-- Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are continuous. -/ @[to_additive "Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are continuous."] lemma topological_group.continuous_conj_prod [has_continuous_inv G] : continuous (λ g : G × G, g.fst * g.snd * g.fst⁻¹) := continuous_mul.mul (continuous_inv.comp continuous_fst) /-- Conjugation by a fixed element is continuous when `mul` is continuous. -/ @[to_additive "Conjugation by a fixed element is continuous when `add` is continuous."] lemma topological_group.continuous_conj (g : G) : continuous (λ (h : G), g * h * g⁻¹) := (continuous_mul_right g⁻¹).comp (continuous_mul_left g) /-- Conjugation acting on fixed element of the group is continuous when both `mul` and `inv` are continuous. -/ @[to_additive "Conjugation acting on fixed element of the additive group is continuous when both `add` and `neg` are continuous."] lemma topological_group.continuous_conj' [has_continuous_inv G] (h : G) : continuous (λ (g : G), g * h * g⁻¹) := (continuous_mul_right h).mul continuous_inv end conj variables [topological_space G] [group G] [topological_group G] [topological_space α] {f : α → G} {s : set α} {x : α} section zpow @[continuity, to_additive] lemma continuous_zpow : ∀ z : ℤ, continuous (λ a : G, a ^ z) | (int.of_nat n) := by simpa using continuous_pow n | -[1+n] := by simpa using (continuous_pow (n + 1)).inv instance add_group.has_continuous_const_smul_int {A} [add_group A] [topological_space A] [topological_add_group A] : has_continuous_const_smul ℤ A := ⟨continuous_zsmul⟩ instance add_group.has_continuous_smul_int {A} [add_group A] [topological_space A] [topological_add_group A] : has_continuous_smul ℤ A := ⟨continuous_uncurry_of_discrete_topology continuous_zsmul⟩ @[continuity, to_additive] lemma continuous.zpow {f : α → G} (h : continuous f) (z : ℤ) : continuous (λ b, (f b) ^ z) := (continuous_zpow z).comp h @[to_additive] lemma continuous_on_zpow {s : set G} (z : ℤ) : continuous_on (λ x, x ^ z) s := (continuous_zpow z).continuous_on @[to_additive] lemma continuous_at_zpow (x : G) (z : ℤ) : continuous_at (λ x, x ^ z) x := (continuous_zpow z).continuous_at @[to_additive] lemma filter.tendsto.zpow {α} {l : filter α} {f : α → G} {x : G} (hf : tendsto f l (𝓝 x)) (z : ℤ) : tendsto (λ x, f x ^ z) l (𝓝 (x ^ z)) := (continuous_at_zpow _ _).tendsto.comp hf @[to_additive] lemma continuous_within_at.zpow {f : α → G} {x : α} {s : set α} (hf : continuous_within_at f s x) (z : ℤ) : continuous_within_at (λ x, f x ^ z) s x := hf.zpow z @[to_additive] lemma continuous_at.zpow {f : α → G} {x : α} (hf : continuous_at f x) (z : ℤ) : continuous_at (λ x, f x ^ z) x := hf.zpow z @[to_additive continuous_on.zsmul] lemma continuous_on.zpow {f : α → G} {s : set α} (hf : continuous_on f s) (z : ℤ) : continuous_on (λ x, f x ^ z) s := λ x hx, (hf x hx).zpow z end zpow section ordered_comm_group variables [topological_space H] [ordered_comm_group H] [topological_group H] @[to_additive] lemma tendsto_inv_nhds_within_Ioi {a : H} : tendsto has_inv.inv (𝓝[>] a) (𝓝[<] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iio {a : H} : tendsto has_inv.inv (𝓝[<] a) (𝓝[>] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv {a : H} : tendsto has_inv.inv (𝓝[>] (a⁻¹)) (𝓝[<] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iio_inv {a : H} : tendsto has_inv.inv (𝓝[<] (a⁻¹)) (𝓝[>] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Ici {a : H} : tendsto has_inv.inv (𝓝[≥] a) (𝓝[≤] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iic {a : H} : tendsto has_inv.inv (𝓝[≤] a) (𝓝[≥] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ici_inv {a : H} : tendsto has_inv.inv (𝓝[≥] (a⁻¹)) (𝓝[≤] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iic_inv {a : H} : tendsto has_inv.inv (𝓝[≤] (a⁻¹)) (𝓝[≥] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹) end ordered_comm_group @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } @[to_additive] instance pi.topological_group {C : β → Type*} [∀ b, topological_space (C b)] [∀ b, group (C b)] [∀ b, topological_group (C b)] : topological_group (Π b, C b) := { continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) } open mul_opposite @[to_additive] instance [group α] [has_continuous_inv α] : has_continuous_inv αᵐᵒᵖ := op_homeomorph.symm.inducing.has_continuous_inv unop_inv /-- If multiplication is continuous in `α`, then it also is in `αᵐᵒᵖ`. -/ @[to_additive "If addition is continuous in `α`, then it also is in `αᵃᵒᵖ`."] instance [group α] [topological_group α] : topological_group αᵐᵒᵖ := { } variable (G) @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := ((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds inv_one) /-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a homeomorphism. This is a shear mapping."] protected def homeomorph.shear_mul_right : G × G ≃ₜ G × G := { continuous_to_fun := continuous_fst.prod_mk continuous_mul, continuous_inv_fun := continuous_fst.prod_mk $ continuous_fst.inv.mul continuous_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } @[simp, to_additive] lemma homeomorph.shear_mul_right_coe : ⇑(homeomorph.shear_mul_right G) = λ z : G × G, (z.1, z.1 * z.2) := rfl @[simp, to_additive] lemma homeomorph.shear_mul_right_symm_coe : ⇑(homeomorph.shear_mul_right G).symm = λ z : G × G, (z.1, z.1⁻¹ * z.2) := rfl variables {G} @[to_additive] protected lemma inducing.topological_group {F : Type*} [group H] [topological_space H] [monoid_hom_class F H G] (f : F) (hf : inducing f) : topological_group H := { to_has_continuous_mul := hf.has_continuous_mul _, to_has_continuous_inv := hf.has_continuous_inv (map_inv f) } @[to_additive] protected lemma topological_group_induced {F : Type*} [group H] [monoid_hom_class F H G] (f : F) : @topological_group H (induced f ‹_›) _ := by { letI := induced f ‹_›, exact inducing.topological_group f ⟨rfl⟩ } namespace subgroup @[to_additive] instance (S : subgroup G) : topological_group S := inducing.topological_group S.subtype inducing_coe end subgroup /-- The (topological-space) closure of a subgroup of a space `M` with `has_continuous_mul` is itself a subgroup. -/ @[to_additive "The (topological-space) closure of an additive subgroup of a space `M` with `has_continuous_add` is itself an additive subgroup."] def subgroup.topological_closure (s : subgroup G) : subgroup G := { carrier := closure (s : set G), inv_mem' := λ g m, by simpa [←set.mem_inv, inv_closure] using m, ..s.to_submonoid.topological_closure } @[simp, to_additive] lemma subgroup.topological_closure_coe {s : subgroup G} : (s.topological_closure : set G) = closure s := rfl @[to_additive] lemma subgroup.subgroup_topological_closure (s : subgroup G) : s ≤ s.topological_closure := subset_closure @[to_additive] lemma subgroup.is_closed_topological_closure (s : subgroup G) : is_closed (s.topological_closure : set G) := by convert is_closed_closure @[to_additive] lemma subgroup.topological_closure_minimal (s : subgroup G) {t : subgroup G} (h : s ≤ t) (ht : is_closed (t : set G)) : s.topological_closure ≤ t := closure_minimal h ht @[to_additive] lemma dense_range.topological_closure_map_subgroup [group H] [topological_space H] [topological_group H] {f : G →* H} (hf : continuous f) (hf' : dense_range f) {s : subgroup G} (hs : s.topological_closure = ⊤) : (s.map f).topological_closure = ⊤ := begin rw set_like.ext'_iff at hs ⊢, simp only [subgroup.topological_closure_coe, subgroup.coe_top, ← dense_iff_closure_eq] at hs ⊢, exact hf'.dense_image hf hs end /-- The topological closure of a normal subgroup is normal.-/ @[to_additive "The topological closure of a normal additive subgroup is normal."] lemma subgroup.is_normal_topological_closure {G : Type*} [topological_space G] [group G] [topological_group G] (N : subgroup G) [N.normal] : (subgroup.topological_closure N).normal := { conj_mem := λ n hn g, begin apply map_mem_closure (topological_group.continuous_conj g) hn, exact λ m hm, subgroup.normal.conj_mem infer_instance m hm g end } @[to_additive] lemma mul_mem_connected_component_one {G : Type*} [topological_space G] [mul_one_class G] [has_continuous_mul G] {g h : G} (hg : g ∈ connected_component (1 : G)) (hh : h ∈ connected_component (1 : G)) : g * h ∈ connected_component (1 : G) := begin rw connected_component_eq hg, have hmul: g ∈ connected_component (g*h), { apply continuous.image_connected_component_subset (continuous_mul_left g), rw ← connected_component_eq hh, exact ⟨(1 : G), mem_connected_component, by simp only [mul_one]⟩ }, simpa [← connected_component_eq hmul] using (mem_connected_component) end @[to_additive] lemma inv_mem_connected_component_one {G : Type*} [topological_space G] [group G] [topological_group G] {g : G} (hg : g ∈ connected_component (1 : G)) : g⁻¹ ∈ connected_component (1 : G) := begin rw ← inv_one, exact continuous.image_connected_component_subset continuous_inv _ ((set.mem_image _ _ _).mp ⟨g, hg, rfl⟩) end /-- The connected component of 1 is a subgroup of `G`. -/ @[to_additive "The connected component of 0 is a subgroup of `G`."] def subgroup.connected_component_of_one (G : Type*) [topological_space G] [group G] [topological_group G] : subgroup G := { carrier := connected_component (1 : G), one_mem' := mem_connected_component, mul_mem' := λ g h hg hh, mul_mem_connected_component_one hg hh, inv_mem' := λ g hg, inv_mem_connected_component_one hg } /-- If a subgroup of a topological group is commutative, then so is its topological closure. -/ @[to_additive "If a subgroup of an additive topological group is commutative, then so is its topological closure."] def subgroup.comm_group_topological_closure [t2_space G] (s : subgroup G) (hs : ∀ (x y : s), x * y = y * x) : comm_group s.topological_closure := { ..s.topological_closure.to_group, ..s.to_submonoid.comm_monoid_topological_closure hs } @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := ((homeomorph.mul_right x⁻¹).comap_nhds_eq 1).trans $ show 𝓝 (1 * x⁻¹⁻¹) = 𝓝 x, by simp @[simp, to_additive] lemma map_mul_left_nhds (x y : G) : map ((*) x) (𝓝 y) = 𝓝 (x * y) := (homeomorph.mul_left x).map_nhds_eq y @[to_additive] lemma map_mul_left_nhds_one (x : G) : map ((*) x) (𝓝 1) = 𝓝 x := by simp /-- A monoid homomorphism (a bundled morphism of a type that implements `monoid_hom_class`) from a topological group to a topological monoid is continuous provided that it is continuous at one. See also `uniform_continuous_of_continuous_at_one`. -/ @[to_additive "An additive monoid homomorphism (a bundled morphism of a type that implements `add_monoid_hom_class`) from an additive topological group to an additive topological monoid is continuous provided that it is continuous at zero. See also `uniform_continuous_of_continuous_at_zero`."] lemma continuous_of_continuous_at_one {M hom : Type*} [mul_one_class M] [topological_space M] [has_continuous_mul M] [monoid_hom_class hom G M] (f : hom) (hf : continuous_at f 1) : continuous f := continuous_iff_continuous_at.2 $ λ x, by simpa only [continuous_at, ← map_mul_left_nhds_one x, tendsto_map'_iff, (∘), map_mul, map_one, mul_one] using hf.tendsto.const_mul (f x) @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] @[to_additive] lemma topological_group.ext_iff {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) : t = t' ↔ @nhds G t 1 = @nhds G t' 1 := ⟨λ h, h ▸ rfl, tg.ext tg'⟩ @[to_additive] lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G] (hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1)) (hconj : ∀ (x₀ : G), map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) ≤ 𝓝 1) : continuous (λ x : G, x⁻¹) := begin rw continuous_iff_continuous_at, rintros x₀, have key : (λ x, (x₀*x)⁻¹) = (λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹) ∘ (λ x, x⁻¹), by {ext ; simp[mul_assoc] }, calc map (λ x, x⁻¹) (𝓝 x₀) = map (λ x, x⁻¹) (map (λ x, x₀*x) $ 𝓝 1) : by rw hleft ... = map (λ x, (x₀*x)⁻¹) (𝓝 1) : by rw filter.map_map ... = map (((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) ∘ (λ x, x⁻¹)) (𝓝 1) : by rw key ... = map ((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) _ : by rw ← filter.map_map ... ≤ map ((λ x, x₀⁻¹ * x) ∘ λ x, x₀ * x * x₀⁻¹) (𝓝 1) : map_mono hinv ... = map (λ x, x₀⁻¹ * x) (map (λ x, x₀ * x * x₀⁻¹) (𝓝 1)) : filter.map_map ... ≤ map (λ x, x₀⁻¹ * x) (𝓝 1) : map_mono (hconj x₀) ... = 𝓝 x₀⁻¹ : (hleft _).symm end @[to_additive] lemma topological_group.of_nhds_one' {G : Type u} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G := begin refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul, continuous_inv := topological_group.of_nhds_aux hinv hleft _ }, intros x₀, suffices : map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, by simp [this, le_refl], rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x₀ * x) ∘ λ x, x*x₀⁻¹, by {ext, simp [mul_assoc] }, ← filter.map_map, ← hright, hleft x₀⁻¹, filter.map_map], convert map_id, ext, simp end @[to_additive] lemma topological_group.of_nhds_one {G : Type u} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G := { continuous_mul := begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) = ((λ x, x₀*y₀*x) ∘ (uncurry (*)) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id)), by { ext, simp [uncurry, prod.map, mul_assoc] }, specialize hconj y₀⁻¹, rw inv_inv at hconj, calc map (λ (p : G × G), p.1 * p.2) (𝓝 (x₀, y₀)) = map (λ (p : G × G), p.1 * p.2) ((𝓝 x₀) ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [hleft x₀, hleft y₀, prod_map_map_eq, filter.map_map] ... = map (((λ x, x₀*y₀*x) ∘ (uncurry (*))) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id))((𝓝 1) ×ᶠ (𝓝 1)) : by rw key ... = map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((map (λ x, y₀⁻¹*x*y₀) $ 𝓝 1) ×ᶠ (𝓝 1)) : by rw [← filter.map_map, ← prod_map_map_eq', map_id] ... ≤ map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((𝓝 1) ×ᶠ (𝓝 1)) : map_mono (filter.prod_mono hconj $ le_rfl) ... = map (λ x, x₀*y₀*x) (map (uncurry (*)) ((𝓝 1) ×ᶠ (𝓝 1))) : by rw filter.map_map ... ≤ map (λ x, x₀*y₀*x) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : (hleft _).symm end, continuous_inv := topological_group.of_nhds_aux hinv hleft hconj} @[to_additive] lemma topological_group.of_comm_of_nhds_one {G : Type u} [comm_group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G := topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id) end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance quotient_group.quotient.topological_space {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (G ⧸ N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → G ⧸ N) := begin intros s s_op, change is_open ((coe : G → G ⧸ N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, (continuous_mul_right _).is_open_preimage s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (G ⧸ N) := { continuous_mul := begin have cont : continuous ((coe : G → G ⧸ N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1 : G ⧸ N), (p.2 : G ⧸ N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := by convert (@continuous_inv G _ _ _).quotient_map' _ } /-- Neighborhoods in the quotient are precisely the map of neighborhoods in the prequotient. -/ @[to_additive "Neighborhoods in the quotient are precisely the map of neighborhoods in the prequotient."] lemma quotient_group.nhds_eq (x : G) : 𝓝 (x : G ⧸ N) = map coe (𝓝 x) := le_antisymm ((quotient_group.is_open_map_coe N).nhds_le x) continuous_quot_mk.continuous_at variables (G) [first_countable_topology G] /-- Any first countable topological group has an antitone neighborhood basis `u : ℕ → set G` for which `(u (n + 1)) ^ 2 ⊆ u n`. The existence of such a neighborhood basis is a key tool for `quotient_group.complete_space` -/ @[to_additive "Any first countable topological additive group has an antitone neighborhood basis `u : ℕ → set G` for which `u (n + 1) + u (n + 1) ⊆ u n`. The existence of such a neighborhood basis is a key tool for `quotient_add_group.complete_space`"] lemma topological_group.exists_antitone_basis_nhds_one : ∃ (u : ℕ → set G), (𝓝 1).has_antitone_basis u ∧ (∀ n, u (n + 1) * u (n + 1) ⊆ u n) := begin rcases (𝓝 (1 : G)).exists_antitone_basis with ⟨u, hu, u_anti⟩, have := ((hu.prod_nhds hu).tendsto_iff hu).mp (by simpa only [mul_one] using continuous_mul.tendsto ((1, 1) : G × G)), simp only [and_self, mem_prod, and_imp, prod.forall, exists_true_left, prod.exists, forall_true_left] at this, have event_mul : ∀ n : ℕ, ∀ᶠ m in at_top, u m * u m ⊆ u n, { intros n, rcases this n with ⟨j, k, h⟩, refine at_top_basis.eventually_iff.mpr ⟨max j k, true.intro, λ m hm, _⟩, rintro - ⟨a, b, ha, hb, rfl⟩, exact h a b (u_anti ((le_max_left _ _).trans hm) ha) (u_anti ((le_max_right _ _).trans hm) hb)}, obtain ⟨φ, -, hφ, φ_anti_basis⟩ := has_antitone_basis.subbasis_with_rel ⟨hu, u_anti⟩ event_mul, exact ⟨u ∘ φ, φ_anti_basis, λ n, hφ n.lt_succ_self⟩, end include n /-- In a first countable topological group `G` with normal subgroup `N`, `1 : G ⧸ N` has a countable neighborhood basis. -/ @[to_additive "In a first countable topological additive group `G` with normal additive subgroup `N`, `0 : G ⧸ N` has a countable neighborhood basis."] instance quotient_group.nhds_one_is_countably_generated : (𝓝 (1 : G ⧸ N)).is_countably_generated := (quotient_group.nhds_eq N 1).symm ▸ map.is_countably_generated _ _ end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) /-- A typeclass saying that `λ p : G × G, p.1 / p.2` is a continuous function. This property automatically holds for topological groups. Lemmas using this class have primes. The unprimed version is for `group_with_zero`. -/ @[to_additive] class has_continuous_div (G : Type*) [topological_space G] [has_div G] : Prop := (continuous_div' : continuous (λ p : G × G, p.1 / p.2)) @[priority 100, to_additive] -- see Note [lower instance priority] instance topological_group.to_has_continuous_div [topological_space G] [group G] [topological_group G] : has_continuous_div G := ⟨by { simp only [div_eq_mul_inv], exact continuous_fst.mul continuous_snd.inv }⟩ export has_continuous_sub (continuous_sub) export has_continuous_div (continuous_div') section has_continuous_div variables [topological_space G] [has_div G] [has_continuous_div G] @[to_additive sub] lemma filter.tendsto.div' {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λ x, f x / g x) l (𝓝 (a / b)) := (continuous_div'.tendsto (a, b)).comp (hf.prod_mk_nhds hg) @[to_additive const_sub] lemma filter.tendsto.const_div' (b : G) {c : G} {f : α → G} {l : filter α} (h : tendsto f l (𝓝 c)) : tendsto (λ k : α, b / f k) l (𝓝 (b / c)) := tendsto_const_nhds.div' h @[to_additive sub_const] lemma filter.tendsto.div_const' (b : G) {c : G} {f : α → G} {l : filter α} (h : tendsto f l (𝓝 c)) : tendsto (λ k : α, f k / b) l (𝓝 (c / b)) := h.div' tendsto_const_nhds variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity, to_additive sub] lemma continuous.div' (hf : continuous f) (hg : continuous g) : continuous (λ x, f x / g x) := continuous_div'.comp (hf.prod_mk hg : _) @[to_additive continuous_sub_left] lemma continuous_div_left' (a : G) : continuous (λ b : G, a / b) := continuous_const.div' continuous_id @[to_additive continuous_sub_right] lemma continuous_div_right' (a : G) : continuous (λ b : G, b / a) := continuous_id.div' continuous_const @[to_additive sub] lemma continuous_at.div' {f g : α → G} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x / g x) x := hf.div' hg @[to_additive sub] lemma continuous_within_at.div' (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ x, f x / g x) s x := hf.div' hg @[to_additive sub] lemma continuous_on.div' (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x / g x) s := λ x hx, (hf x hx).div' (hg x hx) end has_continuous_div section div_in_topological_group variables [group G] [topological_space G] [topological_group G] /-- A version of `homeomorph.mul_left a b⁻¹` that is defeq to `a / b`. -/ @[to_additive /-" A version of `homeomorph.add_left a (-b)` that is defeq to `a - b`. "-/, simps {simp_rhs := tt}] def homeomorph.div_left (x : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.div' continuous_id, continuous_inv_fun := continuous_inv.mul continuous_const, .. equiv.div_left x } @[to_additive] lemma is_open_map_div_left (a : G) : is_open_map ((/) a) := (homeomorph.div_left _).is_open_map @[to_additive] lemma is_closed_map_div_left (a : G) : is_closed_map ((/) a) := (homeomorph.div_left _).is_closed_map /-- A version of `homeomorph.mul_right a⁻¹ b` that is defeq to `b / a`. -/ @[to_additive /-" A version of `homeomorph.add_right (-a) b` that is defeq to `b - a`. "-/, simps {simp_rhs := tt}] def homeomorph.div_right (x : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.div' continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.div_right x } @[to_additive] lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) := (homeomorph.div_right a).is_open_map @[to_additive] lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) := (homeomorph.div_right a).is_closed_map @[to_additive] lemma tendsto_div_nhds_one_iff {α : Type*} {l : filter α} {x : G} {u : α → G} : tendsto (λ n, u n / x) l (𝓝 1) ↔ tendsto u l (𝓝 x) := begin have A : tendsto (λ (n : α), x) l (𝓝 x) := tendsto_const_nhds, exact ⟨λ h, by simpa using h.mul A, λ h, by simpa using h.div' A⟩ end @[to_additive] lemma nhds_translation_div (x : G) : comap (/ x) (𝓝 1) = 𝓝 x := by simpa only [div_eq_mul_inv] using nhds_translation_mul_inv x end div_in_topological_group /-! ### Topological operations on pointwise sums and products A few results about interior and closure of the pointwise addition/multiplication of sets in groups with continuous addition/multiplication. See also `submonoid.top_closure_mul_self_eq` in `topology.algebra.monoid`. -/ section has_continuous_const_smul variables [topological_space β] [group α] [mul_action α β] [has_continuous_const_smul α β] {s : set α} {t : set β} @[to_additive] lemma is_open.smul_left (ht : is_open t) : is_open (s • t) := by { rw ←bUnion_smul_set, exact is_open_bUnion (λ a _, ht.smul _) } @[to_additive] lemma subset_interior_smul_right : s • interior t ⊆ interior (s • t) := interior_maximal (set.smul_subset_smul_left interior_subset) is_open_interior.smul_left variables [topological_space α] @[to_additive] lemma subset_interior_smul : interior s • interior t ⊆ interior (s • t) := (set.smul_subset_smul_right interior_subset).trans subset_interior_smul_right end has_continuous_const_smul section has_continuous_const_smul variables [topological_space α] [group α] [has_continuous_const_smul α α] {s t : set α} @[to_additive] lemma is_open.mul_left : is_open t → is_open (s * t) := is_open.smul_left @[to_additive] lemma subset_interior_mul_right : s * interior t ⊆ interior (s * t) := subset_interior_smul_right @[to_additive] lemma subset_interior_mul : interior s * interior t ⊆ interior (s * t) := subset_interior_smul end has_continuous_const_smul section has_continuous_const_smul_op variables [topological_space α] [group α] [has_continuous_const_smul αᵐᵒᵖ α] {s t : set α} @[to_additive] lemma is_open.mul_right (hs : is_open s) : is_open (s * t) := by { rw ←bUnion_op_smul_set, exact is_open_bUnion (λ a _, hs.smul _) } @[to_additive] lemma subset_interior_mul_left : interior s * t ⊆ interior (s * t) := interior_maximal (set.mul_subset_mul_right interior_subset) is_open_interior.mul_right @[to_additive] lemma subset_interior_mul' : interior s * interior t ⊆ interior (s * t) := (set.mul_subset_mul_left interior_subset).trans subset_interior_mul_left end has_continuous_const_smul_op section topological_group variables [topological_space α] [group α] [topological_group α] {s t : set α} @[to_additive] lemma is_open.div_left (ht : is_open t) : is_open (s / t) := by { rw ←Union_div_left_image, exact is_open_bUnion (λ a ha, is_open_map_div_left a t ht) } @[to_additive] lemma is_open.div_right (hs : is_open s) : is_open (s / t) := by { rw ←Union_div_right_image, exact is_open_bUnion (λ a ha, is_open_map_div_right a s hs) } @[to_additive] lemma subset_interior_div_left : interior s / t ⊆ interior (s / t) := interior_maximal (div_subset_div_right interior_subset) is_open_interior.div_right @[to_additive] lemma subset_interior_div_right : s / interior t ⊆ interior (s / t) := interior_maximal (div_subset_div_left interior_subset) is_open_interior.div_left @[to_additive] lemma subset_interior_div : interior s / interior t ⊆ interior (s / t) := (div_subset_div_left interior_subset).trans subset_interior_div_left @[to_additive] lemma is_open.mul_closure (hs : is_open s) (t : set α) : s * closure t = s * t := begin refine (mul_subset_iff.2 $ λ a ha b hb, _).antisymm (mul_subset_mul_left subset_closure), rw mem_closure_iff at hb, have hbU : b ∈ s⁻¹ * {a * b} := ⟨a⁻¹, a * b, set.inv_mem_inv.2 ha, rfl, inv_mul_cancel_left _ _⟩, obtain ⟨_, ⟨c, d, hc, (rfl : d = _), rfl⟩, hcs⟩ := hb _ hs.inv.mul_right hbU, exact ⟨c⁻¹, _, hc, hcs, inv_mul_cancel_left _ _⟩, end @[to_additive] lemma is_open.closure_mul (ht : is_open t) (s : set α) : closure s * t = s * t := by rw [←inv_inv (closure s * t), mul_inv_rev, inv_closure, ht.inv.mul_closure, mul_inv_rev, inv_inv, inv_inv] @[to_additive] lemma is_open.div_closure (hs : is_open s) (t : set α) : s / closure t = s / t := by simp_rw [div_eq_mul_inv, inv_closure, hs.mul_closure] @[to_additive] lemma is_open.closure_div (ht : is_open t) (s : set α) : closure s / t = s / t := by simp_rw [div_eq_mul_inv, ht.inv.closure_mul] end topological_group /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) section filter_mul section variables (G) [topological_space G] [group G] [topological_group G] @[to_additive] lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ @[priority 100, to_additive] instance topological_group.regular_space : regular_space G := begin refine regular_space.of_exists_mem_nhds_is_closed_subset (λ a s hs, _), have : tendsto (λ p : G × G, p.1 * p.2) (𝓝 (a, 1)) (𝓝 a), from continuous_mul.tendsto' _ _ (mul_one a), rcases mem_nhds_prod_iff.mp (this hs) with ⟨U, hU, V, hV, hUV⟩, rw [← image_subset_iff, image_prod] at hUV, refine ⟨closure U, mem_of_superset hU subset_closure, is_closed_closure, _⟩, calc closure U ⊆ closure U * interior V : subset_mul_left _ (mem_interior_iff_mem_nhds.2 hV) ... = U * interior V : is_open_interior.closure_mul U ... ⊆ U * V : mul_subset_mul_left interior_subset ... ⊆ s : hUV end @[to_additive] lemma topological_group.t3_space [t1_space G] : t3_space G := ⟨⟩ @[to_additive] lemma topological_group.t2_space [t1_space G] : t2_space G := by { haveI := topological_group.t3_space G, apply_instance } variables {G} (S : subgroup G) [subgroup.normal S] [is_closed (S : set G)] @[to_additive] instance subgroup.t3_quotient_of_is_closed (S : subgroup G) [subgroup.normal S] [is_closed (S : set G)] : t3_space (G ⧸ S) := begin suffices : t1_space (G ⧸ S), { exact @topological_group.t3_space _ _ _ _ this, }, have hS : is_closed (S : set G) := infer_instance, rw ← quotient_group.ker_mk S at hS, exact topological_group.t1_space (G ⧸ S) ((quotient_map_quotient_mk.is_closed_preimage).mp hS), end /-- A subgroup `S` of a topological group `G` acts on `G` properly discontinuously on the left, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`.) -/ @[to_additive "A subgroup `S` of an additive topological group `G` acts on `G` properly discontinuously on the left, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`."] lemma subgroup.properly_discontinuous_smul_of_tendsto_cofinite (S : subgroup G) (hS : tendsto S.subtype cofinite (cocompact G)) : properly_discontinuous_smul S G := { finite_disjoint_inter_image := begin intros K L hK hL, have H : set.finite _ := hS ((hL.prod hK).image continuous_div').compl_mem_cocompact, rw [preimage_compl, compl_compl] at H, convert H, ext x, simpa only [image_smul, mem_image, prod.exists] using set.smul_inter_ne_empty_iff', end } local attribute [semireducible] mul_opposite /-- A subgroup `S` of a topological group `G` acts on `G` properly discontinuously on the right, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`.) If `G` is Hausdorff, this can be combined with `t2_space_of_properly_discontinuous_smul_of_t2_space` to show that the quotient group `G ⧸ S` is Hausdorff. -/ @[to_additive "A subgroup `S` of an additive topological group `G` acts on `G` properly discontinuously on the right, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`.) If `G` is Hausdorff, this can be combined with `t2_space_of_properly_discontinuous_vadd_of_t2_space` to show that the quotient group `G ⧸ S` is Hausdorff."] lemma subgroup.properly_discontinuous_smul_opposite_of_tendsto_cofinite (S : subgroup G) (hS : tendsto S.subtype cofinite (cocompact G)) : properly_discontinuous_smul S.opposite G := { finite_disjoint_inter_image := begin intros K L hK hL, have : continuous (λ p : G × G, (p.1⁻¹, p.2)) := continuous_inv.prod_map continuous_id, have H : set.finite _ := hS ((hK.prod hL).image (continuous_mul.comp this)).compl_mem_cocompact, rw [preimage_compl, compl_compl] at H, convert H, ext x, simpa only [image_smul, mem_image, prod.exists] using set.op_smul_inter_ne_empty_iff, end } end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [group G] [topological_group G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `K * V ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul_right {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), K * V ⊆ U := begin apply hK.induction_on, { exact ⟨univ, by simp⟩ }, { rintros s t hst ⟨V, hV, hV'⟩, exact ⟨V, hV, (mul_subset_mul_right hst).trans hV'⟩ }, { rintros s t ⟨V, V_in, hV'⟩ ⟨W, W_in, hW'⟩, use [V ∩ W, inter_mem V_in W_in], rw union_mul, exact union_subset ((mul_subset_mul_left (V.inter_subset_left W)).trans hV') ((mul_subset_mul_left (V.inter_subset_right W)).trans hW') }, { intros x hx, have := tendsto_mul (show U ∈ 𝓝 (x * 1), by simpa using hU.mem_nhds (hKU hx)), rw [nhds_prod_eq, mem_map, mem_prod_iff] at this, rcases this with ⟨t, ht, s, hs, h⟩, rw [← image_subset_iff, image_mul_prod] at h, exact ⟨t, mem_nhds_within_of_mem_nhds ht, s, hs, h⟩ } end open mul_opposite /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `V * K ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `V + K ⊆ U`."] lemma compact_open_separated_mul_left {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), V * K ⊆ U := begin rcases compact_open_separated_mul_right (hK.image continuous_op) (op_homeomorph.is_open_map U hU) (image_subset op hKU) with ⟨V, (hV : V ∈ 𝓝 (op (1 : G))), hV' : op '' K * V ⊆ op '' U⟩, refine ⟨op ⁻¹' V, continuous_op.continuous_at hV, _⟩, rwa [← image_preimage_eq V op_surjective, ← image_op_mul, image_subset_iff, preimage_image_eq _ op_injective] at hV' end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin obtain ⟨t, ht⟩ : ∃ t : finset G, K ⊆ ⋃ x ∈ t, interior (((*) x) ⁻¹' V), { refine hK.elim_finite_subcover (λ x, interior $ ((*) x) ⁻¹' V) (λ x, is_open_interior) _, cases hV with g₀ hg₀, refine λ g hg, mem_Union.2 ⟨g₀ * g⁻¹, _⟩, refine preimage_interior_subset_interior_preimage (continuous_const.mul continuous_id) _, rwa [mem_preimage, inv_mul_cancel_right] }, exact ⟨t, subset.trans ht $ Union₂_mono $ λ g hg, interior_subset⟩ end /-- Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis. -/ @[priority 100, to_additive separable_locally_compact_add_group.sigma_compact_space "Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis."] instance separable_locally_compact_group.sigma_compact_space [separable_space G] [locally_compact_space G] : sigma_compact_space G := begin obtain ⟨L, hLc, hL1⟩ := exists_compact_mem_nhds (1 : G), refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩, { intro n, exact (homeomorph.mul_right _).is_compact_preimage.mpr hLc }, { refine Union_eq_univ_iff.2 (λ x, _), obtain ⟨_, ⟨n, rfl⟩, hn⟩ : (range (dense_seq G) ∩ (λ y, x * y) ⁻¹' L).nonempty, { rw [← (homeomorph.mul_left x).apply_symm_apply 1] at hL1, exact (dense_range_dense_seq G).inter_nhds_nonempty ((homeomorph.mul_left x).continuous.continuous_at $ hL1) }, exact ⟨n, hn⟩ } end /-- Given two compact sets in a noncompact topological group, there is a translate of the second one that is disjoint from the first one. -/ @[to_additive "Given two compact sets in a noncompact additive topological group, there is a translate of the second one that is disjoint from the first one."] lemma exists_disjoint_smul_of_is_compact [noncompact_space G] {K L : set G} (hK : is_compact K) (hL : is_compact L) : ∃ (g : G), disjoint K (g • L) := begin have A : ¬ (K * L⁻¹ = univ), from (hK.mul hL.inv).ne_univ, obtain ⟨g, hg⟩ : ∃ g, g ∉ K * L⁻¹, { contrapose! A, exact eq_univ_iff_forall.2 A }, refine ⟨g, _⟩, apply disjoint_left.2 (λ a ha h'a, hg _), rcases h'a with ⟨b, bL, rfl⟩, refine ⟨g * b, b⁻¹, ha, by simpa only [set.mem_inv, inv_inv] using bL, _⟩, simp only [smul_eq_mul, mul_inv_cancel_right] end /-- In a locally compact group, any neighborhood of the identity contains a compact closed neighborhood of the identity, even without separation assumptions on the space. -/ @[to_additive "In a locally compact additive group, any neighborhood of the identity contains a compact closed neighborhood of the identity, even without separation assumptions on the space."] lemma local_is_compact_is_closed_nhds_of_group [locally_compact_space G] {U : set G} (hU : U ∈ 𝓝 (1 : G)) : ∃ (K : set G), is_compact K ∧ is_closed K ∧ K ⊆ U ∧ (1 : G) ∈ interior K := begin obtain ⟨L, Lint, LU, Lcomp⟩ : ∃ (L : set G) (H : L ∈ 𝓝 (1 : G)), L ⊆ U ∧ is_compact L, from local_compact_nhds hU, obtain ⟨V, Vnhds, hV⟩ : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v * w ∈ L, { have : ((λ p : G × G, p.1 * p.2) ⁻¹' L) ∈ 𝓝 ((1, 1) : G × G), { refine continuous_at_fst.mul continuous_at_snd _, simpa only [mul_one] using Lint }, simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] }, have VL : closure V ⊆ L, from calc closure V = {(1 : G)} * closure V : by simp only [singleton_mul, one_mul, image_id'] ... ⊆ interior V * closure V : mul_subset_mul_right (by simpa only [singleton_subset_iff] using mem_interior_iff_mem_nhds.2 Vnhds) ... = interior V * V : is_open_interior.mul_closure _ ... ⊆ V * V : mul_subset_mul_right interior_subset ... ⊆ L : by { rintros x ⟨y, z, yv, zv, rfl⟩, exact hV _ yv _ zv }, exact ⟨closure V, is_compact_of_is_closed_subset Lcomp is_closed_closure VL, is_closed_closure, VL.trans LU, interior_mono subset_closure (mem_interior_iff_mem_nhds.2 Vnhds)⟩, end end section variables [topological_space G] [comm_group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_one_split ht with ⟨V, V1, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_mem_nhds hd }, { simp only [inv_mul_cancel_right] } } end /-- On a topological group, `𝓝 : G → filter G` can be promoted to a `mul_hom`. -/ @[to_additive "On an additive topological group, `𝓝 : G → filter G` can be promoted to an `add_hom`.", simps] def nhds_mul_hom : G →ₙ* (filter G) := { to_fun := 𝓝, map_mul' := λ_ _, nhds_mul _ _ } end end filter_mul instance {G} [topological_space G] [group G] [topological_group G] : topological_add_group (additive G) := { continuous_neg := @continuous_inv G _ _ _ } instance {G} [topological_space G] [add_group G] [topological_add_group G] : topological_group (multiplicative G) := { continuous_inv := @continuous_neg G _ _ _ } section quotient variables [group G] [topological_space G] [topological_group G] {Γ : subgroup G} @[to_additive] instance quotient_group.has_continuous_const_smul : has_continuous_const_smul G (G ⧸ Γ) := { continuous_const_smul := λ g, by convert ((@continuous_const _ _ _ _ g).mul continuous_id).quotient_map' _ } @[to_additive] lemma quotient_group.continuous_smul₁ (x : G ⧸ Γ) : continuous (λ g : G, g • x) := begin induction x using quotient_group.induction_on, exact continuous_quotient_mk.comp (continuous_mul_right x) end /-- The quotient of a second countable topological group by a subgroup is second countable. -/ @[to_additive "The quotient of a second countable additive topological group by a subgroup is second countable."] instance quotient_group.second_countable_topology [second_countable_topology G] : second_countable_topology (G ⧸ Γ) := has_continuous_const_smul.second_countable_topology end quotient namespace units open mul_opposite (continuous_op continuous_unop) variables [monoid α] [topological_space α] [monoid β] [topological_space β] @[to_additive] instance [has_continuous_mul α] : topological_group αˣ := { continuous_inv := units.continuous_iff.2 $ ⟨continuous_coe_inv, continuous_coe⟩ } /-- The topological group isomorphism between the units of a product of two monoids, and the product of the units of each monoid. -/ @[to_additive "The topological group isomorphism between the additive units of a product of two additive monoids, and the product of the additive units of each additive monoid."] def homeomorph.prod_units : (α × β)ˣ ≃ₜ (αˣ × βˣ) := { continuous_to_fun := (continuous_fst.units_map (monoid_hom.fst α β)).prod_mk (continuous_snd.units_map (monoid_hom.snd α β)), continuous_inv_fun := units.continuous_iff.2 ⟨continuous_coe.fst'.prod_mk continuous_coe.snd', continuous_coe_inv.fst'.prod_mk continuous_coe_inv.snd'⟩, to_equiv := mul_equiv.prod_units.to_equiv } end units section lattice_ops variables {ι : Sort*} [group G] @[to_additive] lemma topological_group_Inf {ts : set (topological_space G)} (h : ∀ t ∈ ts, @topological_group G t _) : @topological_group G (Inf ts) _ := { to_has_continuous_inv := @has_continuous_inv_Inf _ _ _ $ λ t ht, @topological_group.to_has_continuous_inv G t _ $ h t ht, to_has_continuous_mul := @has_continuous_mul_Inf _ _ _ $ λ t ht, @topological_group.to_has_continuous_mul G t _ $ h t ht } @[to_additive] lemma topological_group_infi {ts' : ι → topological_space G} (h' : ∀ i, @topological_group G (ts' i) _) : @topological_group G (⨅ i, ts' i) _ := by { rw ← Inf_range, exact topological_group_Inf (set.forall_range_iff.mpr h') } @[to_additive] lemma topological_group_inf {t₁ t₂ : topological_space G} (h₁ : @topological_group G t₁ _) (h₂ : @topological_group G t₂ _) : @topological_group G (t₁ ⊓ t₂) _ := by { rw inf_eq_infi, refine topological_group_infi (λ b, _), cases b; assumption } end lattice_ops /-! ### Lattice of group topologies We define a type class `group_topology α` which endows a group `α` with a topology such that all group operations are continuous. Group topologies on a fixed group `α` are ordered, by reverse inclusion. They form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. Any function `f : α → β` induces `coinduced f : topological_space α → group_topology β`. The additive version `add_group_topology α` and corresponding results are provided as well. -/ /-- A group topology on a group `α` is a topology for which multiplication and inversion are continuous. -/ structure group_topology (α : Type u) [group α] extends topological_space α, topological_group α : Type u /-- An additive group topology on an additive group `α` is a topology for which addition and negation are continuous. -/ structure add_group_topology (α : Type u) [add_group α] extends topological_space α, topological_add_group α : Type u attribute [to_additive] group_topology namespace group_topology variables [group α] /-- A version of the global `continuous_mul` suitable for dot notation. -/ @[to_additive "A version of the global `continuous_add` suitable for dot notation."] lemma continuous_mul' (g : group_topology α) : by haveI := g.to_topological_space; exact continuous (λ p : α × α, p.1 * p.2) := begin letI := g.to_topological_space, haveI := g.to_topological_group, exact continuous_mul, end /-- A version of the global `continuous_inv` suitable for dot notation. -/ @[to_additive "A version of the global `continuous_neg` suitable for dot notation."] lemma continuous_inv' (g : group_topology α) : by haveI := g.to_topological_space; exact continuous (has_inv.inv : α → α) := begin letI := g.to_topological_space, haveI := g.to_topological_group, exact continuous_inv, end @[to_additive] lemma to_topological_space_injective : function.injective (to_topological_space : group_topology α → topological_space α):= λ f g h, by { cases f, cases g, congr' } @[ext, to_additive] lemma ext' {f g : group_topology α} (h : f.is_open = g.is_open) : f = g := to_topological_space_injective $ topological_space_eq h /-- The ordering on group topologies on the group `γ`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ @[to_additive "The ordering on group topologies on the group `γ`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`)."] instance : partial_order (group_topology α) := partial_order.lift to_topological_space to_topological_space_injective @[simp, to_additive] lemma to_topological_space_le {x y : group_topology α} : x.to_topological_space ≤ y.to_topological_space ↔ x ≤ y := iff.rfl @[to_additive] instance : has_top (group_topology α) := ⟨{to_topological_space := ⊤, continuous_mul := continuous_top, continuous_inv := continuous_top}⟩ @[simp, to_additive] lemma to_topological_space_top : (⊤ : group_topology α).to_topological_space = ⊤ := rfl @[to_additive] instance : has_bot (group_topology α) := ⟨{to_topological_space := ⊥, continuous_mul := by continuity, continuous_inv := continuous_bot}⟩ @[simp, to_additive] lemma to_topological_space_bot : (⊥ : group_topology α).to_topological_space = ⊥ := rfl @[to_additive] instance : bounded_order (group_topology α) := { top := ⊤, le_top := λ x, show x.to_topological_space ≤ ⊤, from le_top, bot := ⊥, bot_le := λ x, show ⊥ ≤ x.to_topological_space, from bot_le } @[to_additive] instance : has_inf (group_topology α) := { inf := λ x y, ⟨x.1 ⊓ y.1, topological_group_inf x.2 y.2⟩ } @[simp, to_additive] lemma to_topological_space_inf (x y : group_topology α) : (x ⊓ y).to_topological_space = x.to_topological_space ⊓ y.to_topological_space := rfl @[to_additive] instance : semilattice_inf (group_topology α) := to_topological_space_injective.semilattice_inf _ to_topological_space_inf @[to_additive] instance : inhabited (group_topology α) := ⟨⊤⟩ local notation `cont` := @continuous _ _ /-- Infimum of a collection of group topologies. -/ @[to_additive "Infimum of a collection of additive group topologies"] instance : has_Inf (group_topology α) := { Inf := λ S, ⟨Inf (to_topological_space '' S), topological_group_Inf $ ball_image_iff.2 $ λ t ht, t.2⟩ } @[simp, to_additive] lemma to_topological_space_Inf (s : set (group_topology α)) : (Inf s).to_topological_space = Inf (to_topological_space '' s) := rfl @[simp, to_additive] lemma to_topological_space_infi {ι} (s : ι → group_topology α) : (⨅ i, s i).to_topological_space = ⨅ i, (s i).to_topological_space := congr_arg Inf (range_comp _ _).symm /-- Group topologies on `γ` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of group topologies is the topology generated by all their open sets (which is a group topology). The supremum of two group topologies `s` and `t` is the infimum of the family of all group topologies contained in the intersection of `s` and `t`. -/ @[to_additive "Group topologies on `γ` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of group topologies is the topology generated by all their open sets (which is a group topology). The supremum of two group topologies `s` and `t` is the infimum of the family of all group topologies contained in the intersection of `s` and `t`."] instance : complete_semilattice_Inf (group_topology α) := { Inf_le := λ S a haS, to_topological_space_le.1 $ Inf_le ⟨a, haS, rfl⟩, le_Inf := begin intros S a hab, apply topological_space.complete_lattice.le_Inf, rintros _ ⟨b, hbS, rfl⟩, exact hab b hbS, end, ..group_topology.has_Inf, ..group_topology.partial_order } @[to_additive] instance : complete_lattice (group_topology α) := { inf := (⊓), top := ⊤, bot := ⊥, ..group_topology.bounded_order, ..group_topology.semilattice_inf, ..complete_lattice_of_complete_semilattice_Inf _ } /-- Given `f : α → β` and a topology on `α`, the coinduced group topology on `β` is the finest topology such that `f` is continuous and `β` is a topological group. -/ @[to_additive "Given `f : α → β` and a topology on `α`, the coinduced additive group topology on `β` is the finest topology such that `f` is continuous and `β` is a topological additive group."] def coinduced {α β : Type*} [t : topological_space α] [group β] (f : α → β) : group_topology β := Inf {b : group_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space} @[to_additive] lemma coinduced_continuous {α β : Type*} [t : topological_space α] [group β] (f : α → β) : cont t (coinduced f).to_topological_space f := begin rw [continuous_Inf_rng], rintros _ ⟨t', ht', rfl⟩, exact continuous_iff_coinduced_le.2 ht' end end group_topology
1bdc88a39c4e5a22daa07fbb9650ca0b99012f5b
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/lean2h.lean
6752ce4258e5a99983ba038836be12c3e9e15596
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
2,329
lean
(* -- Auxiliary script for generating .h file that declare mk_* and is_* functions for -- constants defined in Lean local env = get_environment() local num_imports = 0 print('/*') print('Copyright (c) 2013 Microsoft Corporation. All rights reserved.') print('Released under Apache 2.0 license as described in the file LICENSE.') print('*/') print("// Automatically generated file, DO NOT EDIT") print('#include "kernel/expr.h"') print('namespace lean {') for obj in env:objects() do if obj:is_begin_import() or obj:is_begin_builtin_import() then num_imports = num_imports + 1 elseif obj:is_end_import() then num_imports = num_imports - 1 elseif num_imports == 0 and obj:has_name() and obj:has_type() and not is_explicit(env, obj:get_name()) and not obj:is_builtin() then local ty = env:normalize(obj:get_type()) local is_fn = ty:is_pi() local arity = 0 while ty:is_pi() do n, d, ty = ty:fields() arity = arity + 1 end local is_th = obj:is_theorem() or obj:is_axiom() io.write("expr mk_") name_to_cpp_decl(obj:get_name()) if is_fn then io.write("_fn"); end print("();") io.write("bool is_") name_to_cpp_decl(obj:get_name()) if is_fn then io.write("_fn"); end print("(expr const & e);") if is_fn and not is_th then io.write("inline bool is_") name_to_cpp_decl(obj:get_name()) io.write("(expr const & e) { return is_app(e) && is_"); name_to_cpp_decl(obj:get_name()) print("_fn(arg(e, 0)) && num_args(e) == " .. (arity+1) .. "; }") end if is_fn then io.write("inline expr mk_") name_to_cpp_decl(obj:get_name()) if is_th then io.write("_th"); end io.write("("); for i = 1, arity do if i > 1 then io.write(", ") end io.write("expr const & e" .. tostring(i)) end io.write(") { return mk_app({mk_"); name_to_cpp_decl(obj:get_name()) io.write("_fn()") for i = 1, arity do io.write(", e" .. tostring(i)) end print ("}); }") end end end print('}') *)
e0632d60575bcc089f5088d1e93ad99f26d6835c
626e312b5c1cb2d88fca108f5933076012633192
/test/lint.lean
08a8983e5ed80badaef7856134026330c7b1590c
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,806
lean
import tactic.lint import algebra.ring.basic def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances lemma foo.bar (ε > 0) : ε = ε := rfl -- >/≥ is allowed in binders (and in fact, in all hypotheses) /-- Test exception in `def_lemma` linter. -/ @[pattern] def my_exists_intro := @Exists.intro -- section -- local attribute [instance, priority 1001] classical.prop_decidable -- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) -- end open tactic meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d run_cmd do let t := name × list ℕ, e ← get_env, let l := e.filter (λ d, e.in_current_file d.to_name ∧ ¬ d.is_auto_or_internal e), l2 ← fold_over_with_cond l (return ∘ check_unused_arguments), guard $ l2.length = 4, let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ (⟨`foo1, [2]⟩ : t) ∈ l2, guard $ (⟨`foo2, [1]⟩ : t) ∈ l2, guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2, guard $ (⟨`foo.bar, [2]⟩ : t) ∈ l2, l2 ← fold_over_with_cond l linter.def_lemma.test, guard $ l2.length = 2, let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3, l3 ← fold_over_with_cond l linter.dup_namespace.test, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l linter.ge_or_gt.test, guard $ l4.length = 1, guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo, -- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4, (_, s) ← lint ff, guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string, (_, s2) ← lint tt, guard $ s.to_string ≠ s2.to_string, skip /- check customizability and nolint -/ meta def dummy_check (d : declaration) : tactic (option string) := return $ if d.to_name.last = "foo" then some "gotcha!" else none meta def linter.dummy_linter : linter := { test := dummy_check, auto_decls := ff, no_errors_found := "found nothing.", errors_found := "found something:" } @[nolint dummy_linter] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) run_cmd do (_, s) ← lint tt lint_verbosity.medium [`linter.dummy_linter] tt, guard $ "/- found something: -/\n#check @foo.foo /- gotcha! -/\n".is_suffix_of s.to_string def incorrect_type_class_argument_test {α : Type} (x : α) [x = x] [decidable_eq α] [group α] : unit := () run_cmd do d ← get_decl `incorrect_type_class_argument_test, x ← linter.incorrect_type_class_argument.test d, guard $ x = some "These are not classes. argument 3: [_inst_1 : x = x]" section def impossible_instance_test {α β : Type} [add_group α] : has_add α := infer_instance local attribute [instance] impossible_instance_test run_cmd do d ← get_decl `impossible_instance_test, x ← linter.impossible_instance.test d, guard $ x = some "Impossible to infer argument 2: {β : Type}" def dangerous_instance_test {α β γ : Type} [ring α] [add_comm_group β] [has_coe α β] [has_inv γ] : has_add β := infer_instance local attribute [instance] dangerous_instance_test run_cmd do d ← get_decl `dangerous_instance_test, x ← linter.dangerous_instance.test d, guard $ x = some "The following arguments become metavariables. argument 1: {α : Type}, argument 3: {γ : Type}" end section def foo_has_mul {α} [has_mul α] : has_mul α := infer_instance local attribute [instance, priority 1] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 20 d, guard $ s = "type-class inference timed out" local attribute [instance, priority 10000] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end instance beta_redex_test {α} [monoid α] : (λ (X : Type), has_mul X) α := ⟨(*)⟩ run_cmd do d ← get_decl `beta_redex_test, x ← linter.instance_priority.test d, guard $ x = some "set priority below 1000" /- test of `apply_to_fresh_variables` -/ run_cmd do e ← mk_const `id, e2 ← apply_to_fresh_variables e, type_check e2, `(@id %%α %%a) ← instantiate_mvars e2, expr.sort (level.succ $ level.mvar u) ← infer_type α, skip /- Test exception in `def_lemma` linter. -/ run_cmd do d ← get_decl `my_exists_intro, t ← linter.def_lemma.test d, guard $ t = none
77981e7c5a9febbe3f65a39095f082aec30a19f7
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/solutions/wednesday/afternoon/algebraic_hierarchy.lean
43a21ea2391aaa5adda3e804873d523649d6e67d
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
19,967
lean
/- This is a sorry-free file covering the material on Wednesday afternoon at LFTCM2020. It's how to build some algebraic structures in Lean -/ import data.rat.basic -- we'll need the rationals at the end of this file /- As a mathematician I essentially always start my Lean files with the following line: -/ import tactic /- That gives me access to all Lean's tactics (see https://leanprover-community.github.io/mathlib_docs/tactics.html) -/ /- ## The point of this file The idea of this file is to show how to build in Lean what the computer scientists call "an algebraic heirarchy", and what mathematicians call "groups, rings, fields, modules etc". Firstly, we will define groups, and develop a basic interface for groups. Then we will define rings, fields, modules, vector spaces, and just demonstrate that they are usable, rather than making a complete interface for all of them. Let's start with the theory of groups. Unfortunately Lean has groups already, so we will have to do everything in a namespace -/ namespace lftcm /- ... which means that now when we define `group`, it will actually be called `lftcm.group`. ## Notation typeclasses To make a term of type `has_mul G`, you need to give a map G^2 → G (or more precisely, a map `has_mul.mul : G → G → G`. Lean's notation `g * h` is notation for `has_mul.mul g h`. Furthermore, `has_mul` is a class. In short, this means that if you write `[has_mul G]` then `G` will magically have a multiplication called `*` (satisfying no axioms). Similarly `[has_one G]` gives you `has_one.one : G` with notation `1 : G`, and `[has_inv G]` gives you `has_inv.inv : G → G` with notation `g⁻¹ : G` ## Definition of a group If `G` is a type, equipped with `* : G^2 → G`, `1 : G` and `⁻¹ : G → G` then it's a group if it satisfies the group axioms. -/ -- `group G` is the type of group structures on a type `G`. -- first we ask for the structure class group (G : Type) extends has_mul G, has_one G, has_inv G := -- and then we ask for the axioms (mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)) (one_mul : ∀ (a : G), 1 * a = a) (mul_left_inv : ∀ (a : G), a⁻¹ * a = 1) /- Advantages of this approach: axioms look lovely. Disadvantage: what if I want the group law to be `+`?? I have embedded `has_mul` in the definition. Lean's solution: develop a `to_additive` metaprogram which translates all theorems about `group`s (with group law `*`) to theorems about `add_group`s (with group law `+`). We will not go into details here. -/ namespace group -- let G be a group variables {G : Type} [group G] /- Lemmas about groups are proved in this namespace. We already have some! All the group axioms are theorems in this namespace. Indeed we have just defined `group.mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)` `group.one_mul : ∀ (a : G), 1 * a = a` `group.mul_left_inv : ∀ (a : G), a⁻¹ * a = 1` Because we are in the `group` namespace, we don't need to write `group.` everywhere. Let's put some more theorems into the `group` namespace. We definitely need `mul_one` and `mul_right_inv`, and it's a fun exercise to get them. Here is a route: `mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c` `mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y` `mul_one (a : G) : a * 1 = a` `mul_right_inv (a : G) : a * a⁻¹ = 1` -/ lemma mul_left_cancel (a b c : G) (Habac : a * b = a * c) : b = c := calc b = 1 * b : by rw one_mul ... = (a⁻¹ * a) * b : by rw mul_left_inv ... = a⁻¹ * (a * b) : by rw mul_assoc ... = a⁻¹ * (a * c) : by rw Habac ... = (a⁻¹ * a) * c : by rw mul_assoc ... = 1 * c : by rw mul_left_inv ... = c : by rw one_mul -- more mathlib-ish proof: lemma mul_left_cancel' (a b c : G) (Habac : a * b = a * c) : b = c := begin rw [←one_mul b, ←mul_left_inv a, mul_assoc, Habac, ←mul_assoc, mul_left_inv, one_mul], end lemma mul_eq_of_eq_inv_mul {a x y : G} (h : x = a⁻¹ * y) : a * x = y := begin apply mul_left_cancel a⁻¹, -- ⊢ a⁻¹ * (a * x) = a⁻¹ * y rw ←mul_assoc, -- ⊢ a⁻¹ * a * x = a⁻¹ * y (remember this means (a⁻¹ * a) * x = ...) rw mul_left_inv, -- ⊢ 1 * x = a⁻¹ * y rw one_mul, -- ⊢ x = a⁻¹ * y exact h end -- The same proof lemma mul_eq_of_eq_inv_mul' {a x y : G} (h : x = a⁻¹ * y) : a * x = y := mul_left_cancel a⁻¹ _ _ $ by rwa [←mul_assoc, mul_left_inv, one_mul] /- So now we can finally prove `mul_one` and `mul_right_inv`. But before we start, let's learn a little bit about the simplifier. ## The `simp` tactic -- Lean's simplifier We have the theorems (axioms) `one_mul g : 1 * g = g` and `mul_left_inv g : g⁻¹ * g = 1`. Both of these theorems are of the form `A = B`, with `A` more complicated than `B`. This means that they are *perfect* theorems for the simplifier. Let's teach those theorems to the simplifier, by adding the `@[simp]` attribute to them. An "attribute" is just a tag which we attach to a theorem (or definition). -/ attribute [simp] one_mul mul_left_inv /- Now let's prove `mul_one` using the simplifier. This also a perfect `simp` lemma, so let's also add the `simp` tag to it. -/ @[simp] theorem mul_one (a : G) : a * 1 = a := begin apply mul_eq_of_eq_inv_mul, -- ⊢ 1 = a⁻¹ * a simp, end /- The simplifier solved `1 = a⁻¹ * a` because it knew `mul_left_inv`. Feel free to comment out the `attribute [simp] one_mul mul_left_inv` line above, and observe that the proof breaks. -/ -- term mode proof theorem mul_one' (a : G) : a * 1 = a := mul_eq_of_eq_inv_mul $ by simp -- see if you can get the simplifier to do this one too @[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 := begin apply mul_eq_of_eq_inv_mul, -- ⊢ a⁻¹ = a⁻¹ * 1 simp end -- Now here's a question. Can we train the simplifier to solve the following problem: --example (a b c d : G) : -- ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ := --by simp -- Remove the --'s and see that it fails. Let's see if we can get it to work. -- We start with two very natural `simp` lemmas. @[simp] lemma one_inv : (1 : G)⁻¹ = 1 := begin apply mul_left_cancel (1 : G), simp, end @[simp] lemma inv_inv (a : G) : a⁻¹⁻¹ = a := begin apply mul_left_cancel a⁻¹, simp, end -- Here is a riskier looking `[simp]` lemma. attribute [simp] mul_assoc -- recall this says (a * b) * c = a * (b * c) -- The simplifier will now push all brackets to the right, which means -- that it's worth proving the following two lemmas and tagging -- them `[simp]`, so that we can still cancel a with a⁻¹ in these situations. @[simp] lemma inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := begin rw ←mul_assoc, simp, end @[simp] lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b := begin rw ←mul_assoc, simp end -- Finally, let's make a `simp` lemma which enables us to -- reduce all inverses to inverses of variables @[simp] lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := begin apply mul_left_cancel (a * b), rw mul_right_inv, simp, end /- If you solved them all -- congratulations! You have just turned Lean's simplifier into a normalising confluent rewriting system for groups, following Knuth-Bendix. https://en.wikipedia.org/wiki/Confluence_(abstract_rewriting)#Motivating_examples In other words, the simplifier will now put any element of a free group into a canonical normal form, and can hence solve the word problem for free groups. -/ example (a b c d : G) : ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ := by simp -- Abstract example of the power of classes: we can define products of groups with instances instance (G : Type) [group G] (H : Type) [group H] : group (G × H) := { mul := λ k l, (k.1*l.1, k.2*l.2), one := (1,1), inv := λ k, (k.1⁻¹, k.2⁻¹), mul_assoc := begin intros a b c, cases a, cases b, cases c, ext; simp, end, one_mul := begin intro a, cases a, ext; simp, end, mul_left_inv := begin intro a, cases a, ext; simp end } -- the type class inference system now knows that products of groups are groups example (G H K : Type) [group G] [group H] [group K] : group (G × H × K) := by apply_instance end group -- let's make a group of order two. -- First the elements {+1, -1} inductive mu2 | p1 : mu2 | m1 : mu2 namespace mu2 -- Now let's do some CS stuff: -- 1) prove it has decidable equality attribute [derive decidable_eq] mu2 -- 2) prove it is finite instance : fintype mu2 := ⟨⟨[mu2.p1, mu2.m1], by simp⟩, λ x, by cases x; simp⟩ -- now back to the maths. -- Define multiplication by doing all cases def mul : mu2 → mu2 → mu2 | p1 p1 := p1 | p1 m1 := m1 | m1 p1 := m1 | m1 m1 := p1 instance : has_mul mu2 := ⟨mul⟩ -- identity def one : mu2 := p1 -- notation instance : has_one mu2 := ⟨one⟩ -- inverse def inv : mu2 → mu2 := id -- notation instance : has_inv mu2 := ⟨inv⟩ -- currently we have notation but no axioms example : p1 * m1 * m1 = p1⁻¹ * p1 := rfl -- all true by definition -- now let's make it a group instance : group mu2 := begin -- first define the structure refine_struct { mul := mul, one := one, inv := inv }, -- now we have three goals (the axioms) all_goals {exact dec_trivial} end end mu2 -- Now let's build rings and modules and stuff (via monoids and add_comm_groups) -- a monoid is a group without inverses class monoid (M : Type) extends has_mul M, has_one M := (mul_assoc : ∀ (a b c : M), a * b * c = a * (b * c)) (one_mul : ∀ (a : M), 1 * a = a) (mul_one : ∀ (a : M), a * 1 = a) -- additive commutative groups from first principles class add_comm_group (A : Type) extends has_add A, has_zero A, has_neg A := (add_assoc : ∀ (a b c : A), a + b + c = a + (b + c)) (zero_add : ∀ (a : A), 0 + a = a) (add_left_neg : ∀ (a : A), -a + a = 0) (add_comm : ∀ a b : A, a + b = b + a) -- Notation for subtraction is handy to have; define a - b to be a + (-b) instance (A : Type) [add_comm_group A] : has_sub A := ⟨λ a b, a + -b⟩ -- rings are additive abelian groups and multiplicative monoids, -- with distributivity class ring (R : Type) extends monoid R, add_comm_group R := (mul_add : ∀ (a b c : R), a * (b + c) = a * b + a * c) (add_mul : ∀ (a b c : R), (a + b) * c = a * c + b * c) -- for commutative rings, add commutativity of multiplication class comm_ring (R : Type) extends ring R := (mul_comm : ∀ a b : R, a * b = b * a) /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (R : Type) (M : Type) := (smul : R → M → M) infixr ` • `:73 := has_scalar.smul -- modules for a ring class module (R : Type) [ring R] (M : Type) [add_comm_group M] extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀ (r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀ x : M, (1 : R) • x = x) -- for fields we let ⁻¹ be defined on the entire field, and demand 0⁻¹ = 0 -- and that a⁻¹ * a = 1 for non-zero a. This is merely for convenience; -- one can easily check that it's mathematically equivalent to the usual -- definition of a field. class field (K : Type) extends comm_ring K, has_inv K := (zero_ne_one : (0 : K) ≠ 1) (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) -- the type of vector spaces def vector_space (K : Type) [field K] (V : Type) [add_comm_group V] := module K V /- Exercise for the reader: define manifolds, schemes, perfectoid spaces in Lean. All have been done! As you can see, it is clearly *feasible*, although it does sometimes take time to get it right. It is all very much work in progress. The extraordinary thing is that although these computer theorem provers have been around for about 50 years, there has never been a serious effort to make the standard definitions used all over modern mathematics in one of them, and this is why these systems are rarely used in mathematics departments. Changing this is one of the goals of the Leanprover community. -/ /- Let's check that we can make the rational numbers into a field. Of course they are already a field in Lean, but remember that when we say `field` below, we mean our just-defined structure `lftcm.field`. -/ -- the rationals are a field (easy because all the work is done in the import) instance : field ℚ := { mul := (*), one := 1, mul_assoc := rat.mul_assoc, one_mul := rat.one_mul, mul_one := rat.mul_one, add := (+), zero := 0, neg := has_neg.neg, -- no () trickery for unary operators add_assoc := rat.add_assoc, zero_add := rat.zero_add, add_left_neg := rat.add_left_neg, add_comm := rat.add_comm, mul_add := rat.mul_add, add_mul := rat.add_mul, mul_comm := rat.mul_comm, inv := has_inv.inv, -- see neg zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := inv_zero -- I don't know why rat.inv_zero was never explicitly defined } /- Below is evidence that we can prove basic theorems about these structures. Note however that it is a *complete pain* because we are *re-implementing* everything; `add_comm` defaults to Lean's version for Lean's `add_comm_group`s, so we have to explicitly write `add_comm_group.add_comm` to use our own version. The mathlib versions of these proofs are less ugly. -/ variables {A : Type} [add_comm_group A] lemma add_comm_group.add_left_cancel (a b c : A) (Habac : a + b = a + c) : b = c := begin rw ←add_comm_group.zero_add b, rw ←add_comm_group.add_left_neg a, rw add_comm_group.add_assoc, rw Habac, rw ←add_comm_group.add_assoc, rw add_comm_group.add_left_neg, rw add_comm_group.zero_add, end lemma add_comm_group.add_right_neg (a : A) : a + -a = 0 := begin rw add_comm_group.add_comm, rw add_comm_group.add_left_neg, end lemma add_comm_group.sub_eq_add_neg (a b : A) : a - b = a + -b := begin -- this is just our definition of subtraction refl end lemma add_comm_group.sub_self (a : A) : a - a = 0 := begin rw add_comm_group.sub_eq_add_neg, rw add_comm_group.add_comm, rw add_comm_group.add_left_neg, end lemma add_comm_group.neg_eq_of_add_eq_zero (a b : A) (h : a + b = 0) : -a = b := begin apply add_comm_group.add_left_cancel a, rw h, rw add_comm_group.add_right_neg, end lemma add_comm_group.add_zero (a : A) : a + 0 = a := begin rw add_comm_group.add_comm, rw add_comm_group.zero_add, end variables {R : Type} [ring R] lemma ring.mul_zero (r : R) : r * 0 = 0 := begin apply add_comm_group.add_left_cancel (r * 0), rw ←ring.mul_add, rw add_comm_group.add_zero, rw add_comm_group.add_zero, end lemma ring.mul_neg (a b : R) : a * -b = -(a * b) := begin symmetry, apply add_comm_group.neg_eq_of_add_eq_zero, rw ←ring.mul_add, rw add_comm_group.add_right_neg, rw ring.mul_zero end lemma ring.mul_sub (R : Type) [comm_ring R] (r a b : R) : r * (a - b) = r * a - r * b := begin rw add_comm_group.sub_eq_add_neg, rw ring.mul_add, rw ring.mul_neg, refl, end lemma comm_ring.sub_mul (R : Type) [comm_ring R] (r a b : R) : (a - b) * r = a * r - b * r := begin rw comm_ring.mul_comm (a - b), rw comm_ring.mul_comm a, rw comm_ring.mul_comm b, apply ring.mul_sub end -- etc etc, for thousands of lines of mathlib, which develop the interface -- abelian groups, rings, commutative rings, modules, fields, vector spaces etc. end lftcm /- ## Advertisement Finished the natural number game? Have Lean installed? Want more games/exercises? Take a look at the following projects, many of which are ongoing but the first three of which are pretty much ready: *) The complex number game (complete, needs to be played within VS Code) https://github.com/ImperialCollegeLondon/complex-number-game To install, type `leanproject get ImperialCollegeLondon/complex-number-game` and then just open the levels in `src/complex`. *) Undergraduate level mathematics Lean puzzles (plenty of stuff here, and more appearing over the summer): https://github.com/ImperialCollegeLondon/Example-Lean-Projects `leanproject get ImperialCollegeLondon/Example-Lean-Projects` *) The max mini-game (a simple browser game like the natural number game) http://wwwf.imperial.ac.uk/~buzzard/xena/max_minigame/ (this is part of what will become the real number game, a game to teach series, sequences and limits etc like the natural number game): `leanproject get ImperialCollegeLondon/real-number-game` *) Some commutative algebra experiments (ongoing work to prove the Nullstellensatz, going slowly because I'm busy): https://github.com/ImperialCollegeLondon/M4P33/blob/1a179372db71ad6802d11eacbc1f02f327d55f8f/src/for_mathlib/commutative_algebra/Zariski_lemma.lean#L80-L81 `leanproject get ImperialCollegeLondon/M4P33` *) The group theory game (work in progress, expect more progress over the summer, as a couple of undergraduates are working on it) https://github.com/ImperialCollegeLondon/group-theory-game `leanproject get ImperialCollegeLondon/group-theory-game` *) Galois theory experiments https://github.com/ImperialCollegeLondon/P11-Galois-Theory `leanproject get ImperialCollegeLondon/P11-Galois-Theory` *) Beginnings of the theory of condensed sets (currently on hold because we need a good interface for abelian categories in mathlib) https://github.com/ImperialCollegeLondon/condensed-sets `leanproject get ImperialCollegeLondon/condensed-sets` ## The Xena Project Why do these projects exist? I (Kevin Buzzard) am interested in teaching undergraduates how to use Lean. I have been running a club at Imperial College London called the Xena Project for the last three years, I am proud that many Imperial mathematics undegraduates have contributed to Lean's maths library, and three of them (Chris Hughes, Kenny Lau, Amelia Livingston) have each contributed over 5,000 lines of code. It is non-trivial to get your work into such a polished state that it is acceptable to the mathlib maintainers. It is also very good practice. I am running Lean summer projects this summer, on a Discord server. If you know of any undergraduates who you think might be interested in Lean, please direct them to the Xena Project Discord! https://discord.gg/BgyVYgJ Undergraduates use Discord for lots of things, and seem to be more likely to use a Discord server than the Zulip chat. The Discord server is chaotic and full of off-topic material -- quite unlike the Lean Zulip server, which is professional and focussed. If you have a serious question about Lean, ask it on the Zulip chat! But if you know an undergraduate who is interested in Lean, they might be interested in the Discord server. We have meetings every Thursday evening (UK time), with live Lean coding and streaming, speedruns, there is music, people posting pictures of cats, Haikus, and so on. To a large extent it is run by undergraduates and PhD students. Over the summer (July and August 2020) there are also live Twitch talks at https://www.twitch.tv/kbuzzard , on Tuesdays 10am and Thursdays 4pm UK time (UTC+1), aimed at mathematics undergraduates. It is an informal place for undergraduates to hang out and meet other undergraduates who are interested in Lean. I believe that it is crucial to make undergraduates aware of computer proof verification systems, because one day (possibly a long time in the future, but one day) these things will cause a paradigm shift in the way mathematics is done, and the sooner young mathematicians learn about them, the sooner it will happen. Prove a theorem. Write a function. @XenaProject https://twitter.com/XenaProject -/
3d28740dbf362740f8190c3bb171a0dd962b9ae3
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/equiv_rw.lean
dbe3ce5fe1efa028640bc24ff97ad769c7484c8d
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
12,084
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 tactic.simp_result import tactic.clear import control.equiv_functor.instances /-! # The `equiv_rw` tactic transports goals or hypotheses along equivalences. The basic syntax is `equiv_rw e`, where `e : α ≃ β` is an equivalence. This will try to replace occurrences of `α` in the goal with `β`, for example transforming * `⊢ α` to `⊢ β`, * `⊢ option α` to `⊢ option β` * `⊢ {a // P}` to `{b // P (⇑(equiv.symm e) b)}` The tactic can also be used to rewrite hypotheses, using the syntax `equiv_rw e at h`. ## Implementation details The main internal function is `equiv_rw_type e t`, which attempts to turn an expression `e : α ≃ β` into a new equivalence with left hand side `t`. As an example, with `t = option α`, it will generate `functor.map_equiv option e`. This is achieved by generating a new synthetic goal `%%t ≃ _`, and calling `solve_by_elim` with an appropriate set of congruence lemmas. To avoid having to specify the relevant congruence lemmas by hand, we mostly rely on `equiv_functor.map_equiv` and `bifunctor.map_equiv` along with some structural congruence lemmas such as * `equiv.arrow_congr'`, * `equiv.subtype_equiv_of_subtype'`, * `equiv.sigma_congr_left'`, and * `equiv.Pi_congr_left'`. The main `equiv_rw` function, when operating on the goal, simply generates a new equivalence `e'` with left hand side matching the target, and calls `apply e'.inv_fun`. When operating on a hypothesis `x : α`, we introduce a new fact `h : x = e.symm (e x)`, revert this, and then attempt to `generalize`, replacing all occurrences of `e x` with a new constant `y`, before `intro`ing and `subst`ing `h`, and renaming `y` back to `x`. ## Future improvements In a future PR I anticipate that `derive equiv_functor` should work on many examples, (internally using `transport`, which is in turn based on `equiv_rw`) and we can incrementally bootstrap the strength of `equiv_rw`. An ambitious project might be to add `equiv_rw!`, a tactic which, when failing to find appropriate `equiv_functor` instances, attempts to `derive` them on the spot. For now `equiv_rw` is entirely based on `equiv`, but the framework can readily be generalised to also work with other types of equivalences, for example specific notations such as ring equivalence (`≃+*`), or general categorical isomorphisms (`≅`). This will allow us to transport across more general types of equivalences, but this will wait for another subsequent PR. -/ namespace tactic /-- A list of lemmas used for constructing congruence equivalences. -/ -- Although this looks 'hard-coded', in fact the lemma `equiv_functor.map_equiv` -- allows us to extend `equiv_rw` simply by constructing new instance so `equiv_functor`. -- TODO: We should also use `category_theory.functorial` and `category_theory.hygienic` instances. -- (example goal: we could rewrite along an isomorphism of rings (either as `R ≅ S` or `R ≃+* S`) -- and turn an `x : mv_polynomial σ R` into an `x : mv_polynomial σ S`.). meta def equiv_congr_lemmas : list (tactic expr) := [ `equiv.of_iff, -- TODO decide what to do with this; it's an equiv_bifunctor? `equiv.equiv_congr, -- The function arrow is technically a bifunctor `Typeᵒᵖ → Type → Type`, -- but the pattern matcher will never see this. `equiv.arrow_congr', -- Allow rewriting in subtypes: `equiv.subtype_equiv_of_subtype', -- Allow rewriting in the first component of a sigma-type: `equiv.sigma_congr_left', -- Allow rewriting ∀s: -- (You might think that repeated application of `equiv.forall_congr' -- would handle the higher arity cases, but unfortunately unification is not clever enough.) `equiv.forall₃_congr', `equiv.forall₂_congr', `equiv.forall_congr', -- Allow rewriting in argument of Pi types: `equiv.Pi_congr_left', -- Handles `sum` and `prod`, and many others: `bifunctor.map_equiv, -- Handles `list`, `option`, `unique`, and many others: `equiv_functor.map_equiv, -- We have to filter results to ensure we don't cheat and use exclusively `equiv.refl` and `iff.refl`! `equiv.refl, `iff.refl ].map (λ n, mk_const n) declare_trace equiv_rw_type /-- Configuration structure for `equiv_rw`. * `max_depth` bounds the search depth for equivalences to rewrite along. The default value is 10. (e.g., if you're rewriting along `e : α ≃ β`, and `max_depth := 2`, you can rewrite `option (option α))` but not `option (option (option α))`. -/ meta structure equiv_rw_cfg := (max_depth : ℕ := 10) /-- Implementation of `equiv_rw_type`, using `solve_by_elim`. Expects a goal of the form `t ≃ _`, and tries to solve it using `eq : α ≃ β` and congruence lemmas. -/ meta def equiv_rw_type_core (eq : expr) (cfg : equiv_rw_cfg) : tactic unit := do /- We now call `solve_by_elim` to try to generate the requested equivalence. There are a few subtleties! * We make sure that `eq` is the first lemma, so it is applied whenever possible. * In `equiv_congr_lemmas`, we put `equiv.refl` last so it is only used when it is not possible to descend further. * Since some congruence lemmas generate subgoals with `∀` statements, we use the `pre_apply` subtactic of `solve_by_elim` to preprocess each new goal with `intros`. -/ solve_by_elim { use_symmetry := false, use_exfalso := false, lemma_thunks := some (pure eq :: equiv_congr_lemmas), ctx_thunk := pure [], max_depth := cfg.max_depth, -- Subgoals may contain function types, -- and we want to continue trying to construct equivalences after the binders. pre_apply := tactic.intros >> skip, backtrack_all_goals := tt, -- If solve_by_elim gets stuck, make sure it isn't because there's a later `≃` or `↔` goal -- that we should still attempt. discharger := `[success_if_fail { match_target _ ≃ _ }] >> `[success_if_fail { match_target _ ↔ _ }] >> (`[show _ ≃ _] <|> `[show _ ↔ _]) <|> trace_if_enabled `equiv_rw_type "Failed, no congruence lemma applied!" >> failed, -- We use the `accept` tactic in `solve_by_elim` to provide tracing. accept := λ goals, lock_tactic_state (do when_tracing `equiv_rw_type (do goals.mmap pp >>= λ goals, trace format!"So far, we've built: {goals}"), done <|> when_tracing `equiv_rw_type (do gs ← get_goals, gs ← gs.mmap (λ g, infer_type g >>= pp), trace format!"Attempting to adapt to {gs}")) } /-- `equiv_rw_type e t` rewrites the type `t` using the equivalence `e : α ≃ β`, returning a new equivalence `t ≃ t'`. -/ meta def equiv_rw_type (eqv : expr) (ty : expr) (cfg : equiv_rw_cfg) : tactic expr := do when_tracing `equiv_rw_type (do ty_pp ← pp ty, eqv_pp ← pp eqv, eqv_ty_pp ← infer_type eqv >>= pp, trace format!"Attempting to rewrite the type `{ty_pp}` using `{eqv_pp} : {eqv_ty_pp}`."), `(_ ≃ _) ← infer_type eqv | fail format!"{eqv} must be an `equiv`", -- We prepare a synthetic goal of type `(%%ty ≃ _)`, for some placeholder right hand side. equiv_ty ← to_expr ``(%%ty ≃ _), -- Now call `equiv_rw_type_core`. new_eqv ← prod.snd <$> (solve_aux equiv_ty $ equiv_rw_type_core eqv cfg), -- Check that we actually used the equivalence `eq` -- (`equiv_rw_type_core` will always find `equiv.refl`, but hopefully only after all other possibilities) new_eqv ← instantiate_mvars new_eqv, -- We previously had `guard (eqv.occurs new_eqv)` here, but `kdepends_on` is more reliable. kdepends_on new_eqv eqv >>= guardb <|> (do eqv_pp ← pp eqv, ty_pp ← pp ty, fail format!"Could not construct an equivalence from {eqv_pp} of the form: {ty_pp} ≃ _"), -- Finally we simplify the resulting equivalence, -- to compress away some `map_equiv equiv.refl` subexpressions. prod.fst <$> new_eqv.simp {fail_if_unchanged := ff} mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to simplify applications of equivalences and their inverses." attribute [equiv_rw_simp] equiv.symm_symm equiv.apply_symm_apply equiv.symm_apply_apply /-- Attempt to replace the hypothesis with name `x` by transporting it along the equivalence in `e : α ≃ β`. -/ meta def equiv_rw_hyp (x : name) (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := -- We call `dsimp_result` to perform the beta redex introduced by `revert` dsimp_result (do x' ← get_local x, x_ty ← infer_type x', -- Adapt `e` to an equivalence with left-hand-side `x_ty`. e ← equiv_rw_type e x_ty cfg, eq ← to_expr ``(%%x' = equiv.symm %%e (equiv.to_fun %%e %%x')), prf ← to_expr ``((equiv.symm_apply_apply %%e %%x').symm), h ← note_anon eq prf, -- Revert the new hypothesis, so it is also part of the goal. revert h, ex ← to_expr ``(equiv.to_fun %%e %%x'), -- Now call `generalize`, -- attempting to replace all occurrences of `e x`, -- calling it for now `j : β`, with `k : x = e.symm j`. generalize ex (by apply_opt_param) transparency.none, -- Reintroduce `x` (now of type `b`), and the hypothesis `h`. intro x, h ← intro1, -- Finally, if we're working on properties, substitute along `h`, then do some cleanup, -- and if we're working on data, just throw out the old `x`. b ← target >>= is_prop, if b then do subst h, `[try { simp only with equiv_rw_simp }] else -- We may need to unfreeze `x` before we can `clear` it. unfreezing_hyp x' (clear' tt [x']) <|> fail format!"equiv_rw expected to be able to clear the original hypothesis {x}, but couldn't.", skip) {fail_if_unchanged := ff} tt -- call `dsimp_result` with `no_defaults := tt`. /-- Rewrite the goal using an equiv `e`. -/ meta def equiv_rw_target (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := do t ← target, e ← equiv_rw_type e t cfg, s ← to_expr ``(equiv.inv_fun %%e), tactic.eapply s, skip end tactic namespace tactic.interactive open lean.parser open interactive interactive.types open tactic local postfix `?`:9001 := optional /-- `equiv_rw e at h`, where `h : α` is a hypothesis, and `e : α ≃ β`, will attempt to transport `h` along `e`, producing a new hypothesis `h : β`, with all occurrences of `h` in other hypotheses and the goal replaced with `e.symm h`. `equiv_rw e` will attempt to transport the goal along an equivalence `e : α ≃ β`. In its minimal form it replaces the goal `⊢ α` with `⊢ β` by calling `apply e.inv_fun`. `equiv_rw` will also try rewriting under (equiv_)functors, so can turn a hypothesis `h : list α` into `h : list β` or a goal `⊢ unique α` into `⊢ unique β`. The maximum search depth for rewriting in subexpressions is controlled by `equiv_rw e {max_depth := n}`. -/ meta def equiv_rw (e : parse texpr) (loc : parse $ (tk "at" *> ident)?) (cfg : equiv_rw_cfg := {}) : itactic := do e ← to_expr e, match loc with | (some hyp) := equiv_rw_hyp hyp e cfg | none := equiv_rw_target e cfg end add_tactic_doc { name := "equiv_rw", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw], tags := ["rewriting", "equiv", "transport"] } /-- Solve a goal of the form `t ≃ _`, by constructing an equivalence from `e : α ≃ β`. This is the same equivalence that `equiv_rw` would use to rewrite a term of type `t`. A typical usage might be: ``` have e' : option α ≃ option β := by equiv_rw_type e ``` -/ meta def equiv_rw_type (e : parse texpr) (cfg : equiv_rw_cfg := {}) : itactic := do `(%%t ≃ _) ← target | fail "`equiv_rw_type` solves goals of the form `t ≃ _`.", e ← to_expr e, tactic.equiv_rw_type e t cfg >>= tactic.exact add_tactic_doc { name := "equiv_rw_type", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw_type], tags := ["rewriting", "equiv", "transport"] } end tactic.interactive
164e6ffb2829787d97627fa0616eec1559d044bf
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/group/pi.lean
538f9445a578248b6ce0410e192438f52c22616b
[ "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
5,927
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import data.pi import algebra.ordered_group import algebra.group_with_zero import tactic.pi_instances /-! # Pi instances for groups and monoids This file defines instances for group, monoid, semigroup and related structures on Pi Types -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) namespace pi @[to_additive] instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ _, 1⟩ @[simp, to_additive] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl @[to_additive] instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ f g i, f i * g i⟩ @[simp, to_additive] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl @[to_additive] instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ f i, (f i)⁻¹⟩ @[simp, to_additive] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_div [Π i, has_div $ f i] : has_div (Π i : I, f i) := ⟨λ f g i, f i / g i⟩ @[simp] lemma div_apply [Π i, has_div $ f i] : (x / y) i = x i / y i := rfl @[to_additive] instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance group [∀ i, group $ f i] : group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. }; tactic.pi_instance_derive_field @[simp] lemma sub_apply [∀ i, add_group $ f i] : (x - y) i = x i - y i := rfl @[to_additive] instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. }; tactic.pi_instance_derive_field @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive] instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by refine_struct { mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<), .. pi.partial_order }; tactic.pi_instance_derive_field @[to_additive] instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) := { mul_le_mul_left := λ x y hxy c i, mul_le_mul_left' (hxy i) _, ..pi.comm_group, ..pi.partial_order } instance mul_zero_class [∀ i, mul_zero_class $ f i] : mul_zero_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance comm_monoid_with_zero [∀ i, comm_monoid_with_zero $ f i] : comm_monoid_with_zero (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field section instance_lemmas open function variables {α β γ : Type*} @[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl @[simp, to_additive] lemma comp_one [has_one β] {f : β → γ} : f ∘ 1 = const α (f 1) := rfl @[simp, to_additive] lemma one_comp [has_one γ] {f : α → β} : (1 : β → γ) ∘ f = 1 := rfl end instance_lemmas end pi section monoid_hom variables (f) [Π i, monoid (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ @[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point is an additive monoid homomorphism."] def monoid_hom.apply (i : I) : (Π i, f i) →* f i := { to_fun := λ g, g i, map_one' := rfl, map_mul' := λ x y, rfl, } @[simp, to_additive] lemma monoid_hom.apply_apply (i : I) (g : Π i, f i) : (monoid_hom.apply f i) g = g i := rfl end monoid_hom section add_monoid_single variables [decidable_eq I] (f) [Π i, add_monoid (f i)] open pi /-- The additive monoid homomorphism including a single additive monoid into a dependent family of additive monoids, as functions supported at a point. -/ def add_monoid_hom.single (i : I) : f i →+ Π i, f i := { to_fun := λ x, single i x, map_zero' := begin ext i', by_cases h : i' = i, { subst h, simp only [single_eq_same], refl, }, { simp only [h, single_eq_of_ne, ne.def, not_false_iff], refl, }, end, map_add' := λ x y, begin ext i', by_cases h : i' = i, -- FIXME in the next two `simp only`s, -- it would be really nice to not have to provide the arguments to `add_apply`. { subst h, simp only [single_eq_same, add_apply (single i' x) (single i' y) i'], }, { simp only [h, add_zero, single_eq_of_ne, add_apply (single i x) (single i y) i', ne.def, not_false_iff], }, end, } @[simp] lemma add_monoid_hom.single_apply {i : I} (x : f i) : (add_monoid_hom.single f i) x = single i x := rfl end add_monoid_single
cba2a8120c48f730c98b81b0026d9ed1a94b5fe6
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/arity.hlean
88ed2b08e217db03b2ac642e62f6de7b0e6b163c
[ "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
11,083
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about functions with multiple arguments -/ variables {A U V W X Y Z : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {E : Πa b c, D a b c → Type} {F : Πa b c d, E a b c d → Type} {G : Πa b c d e, F a b c d e → Type} {H : Πa b c d e f, G a b c d e f → Type} variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {z z' : Z} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} {d : D a b c} {d' : D a' b' c'} {e : E a b c d} {e' : E a' b' c' d'} {ff : F a b c d e} {f' : F a' b' c' d' e'} {g : G a b c d e ff} {g' : G a' b' c' d' e' f'} {h : H a b c d e ff g} {h' : H a' b' c' d' e' f' g'} namespace eq /- Naming convention: The theorem which states how to construct an path between two function applications is api₀i₁...iₙ. Here i₀, ... iₙ are digits, n is the arity of the function(s), and iⱼ specifies the dimension of the path between the jᵗʰ argument (i₀ specifies the dimension of the path between the functions). A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionally equal The functions are non-dependent, except when the theorem name contains trailing zeroes (where the function is dependent only in the arguments where it doesn't result in any transports in the theorem statement). For the fully-dependent versions (except that the conclusion doesn't contain a transport) we write apdi₀i₁...iₙ. For versions where only some arguments depend on some other arguments, or for versions with transport in the conclusion (like apdt), we don't have a consistent naming scheme (yet). We don't prove each theorem systematically, but prove only the ones which we actually need. -/ definition homotopy2 [reducible] (f g : Πa b, C a b) : Type := Πa b, f a b = g a b definition homotopy3 [reducible] (f g : Πa b c, D a b c) : Type := Πa b c, f a b c = g a b c definition homotopy4 [reducible] (f g : Πa b c d, E a b c d) : Type := Πa b c d, f a b c d = g a b c d infix ` ~2 `:50 := homotopy2 infix ` ~3 `:50 := homotopy3 definition ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w') : f u v w = f u' v' w' := by cases Hu; congruence; repeat assumption definition ap01111 (f : U → V → W → X → Y) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') : f u v w x = f u' v' w' x' := by cases Hu; congruence; repeat assumption definition ap011111 (f : U → V → W → X → Y → Z) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') : f u v w x y = f u' v' w' x' y' := by cases Hu; congruence; repeat assumption definition ap0111111 (f : U → V → W → X → Y → Z → A) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') (Hz : z = z') : f u v w x y z = f u' v' w' x' y' z' := by cases Hu; congruence; repeat assumption definition ap010 (f : X → Πa, B a) (Hx : x = x') : f x ~ f x' := by intros; cases Hx; reflexivity definition ap0100 (f : X → Πa b, C a b) (Hx : x = x') : f x ~2 f x' := by intros; cases Hx; reflexivity definition ap01000 (f : X → Πa b c, D a b c) (Hx : x = x') : f x ~3 f x' := by intros; cases Hx; reflexivity definition apdt011 (f : Πa, B a → Z) (Ha : a = a') (Hb : transport B Ha b = b') : f a b = f a' b' := by cases Ha; cases Hb; reflexivity definition apdt0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') : f a b c = f a' b' c' := by cases Ha; cases Hb; cases Hc; reflexivity definition apdt01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := by cases Ha; cases Hb; cases Hc; cases Hd; reflexivity definition apdt011111 (f : Πa b c d, E a b c d → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d') (He : cast (apdt01111 E Ha Hb Hc Hd) e = e') : f a b c d e = f a' b' c' d' e' := by cases Ha; cases Hb; cases Hc; cases Hd; cases He; reflexivity definition apdt0111111 (f : Πa b c d e, F a b c d e → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d') (He : cast (apdt01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apdt011111 F Ha Hb Hc Hd He) ff = f') : f a b c d e ff = f a' b' c' d' e' f' := begin cases Ha, cases Hb, cases Hc, cases Hd, cases He, cases Hf, reflexivity end -- definition apd0111111 (f : Πa b c d e ff, G a b c d e ff → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') -- : f a b c d e ff g = f a' b' c' d' e' f' g' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; reflexivity -- definition apd01111111 (f : Πa b c d e ff g, G a b c d e ff g → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') (Hh : cast (apd01111111 H Ha Hb Hc Hd He Hf Hg) h = h') -- : f a b c d e ff g h = f a' b' c' d' e' f' g' h' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; cases Hh; reflexivity definition apd100 [unfold 6] {f g : Πa b, C a b} (p : f = g) : f ~2 g := λa b, apd10 (apd10 p a) b definition apd1000 [unfold 7] {f g : Πa b c, D a b c} (p : f = g) : f ~3 g := λa b c, apd100 (apd10 p a) b c /- some properties of these variants of ap -/ -- we only prove what we currently need definition ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') : ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a := eq.rec_on q (eq.rec_on p idp) definition ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') : ap010 f (ap g p) a = ap010 (λy, f (g y)) p a := eq.rec_on p idp /- the following theorems are function extentionality for functions with multiple arguments -/ definition eq_of_homotopy2 {f g : Πa b, C a b} (H : f ~2 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy (H a)) definition eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ~3 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy2 (H a)) definition eq_of_homotopy2_id (f : Πa b, C a b) : eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f := begin transitivity eq_of_homotopy (λ a, idpath (f a)), {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy_idp}, apply eq_of_homotopy_idp end definition eq_of_homotopy3_id (f : Πa b c, D a b c) : eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f := begin transitivity _, {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy2_id}, apply eq_of_homotopy_idp end definition eq_of_homotopy2_inv {f g : Πa b, C a b} (H : f ~2 g) : eq_of_homotopy2 (λa b, (H a b)⁻¹) = (eq_of_homotopy2 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy3_inv {f g : Πa b c, D a b c} (H : f ~3 g) : eq_of_homotopy3 (λa b c, (H a b c)⁻¹) = (eq_of_homotopy3 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy2_con {f g h : Πa b, C a b} (H1 : f ~2 g) (H2 : g ~2 h) : eq_of_homotopy2 (λa b, H1 a b ⬝ H2 a b) = eq_of_homotopy2 H1 ⬝ eq_of_homotopy2 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_con)) ⬝ !eq_of_homotopy_con definition eq_of_homotopy3_con {f g h : Πa b c, D a b c} (H1 : f ~3 g) (H2 : g ~3 h) : eq_of_homotopy3 (λa b c, H1 a b c ⬝ H2 a b c) = eq_of_homotopy3 H1 ⬝ eq_of_homotopy3 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_con)) ⬝ !eq_of_homotopy_con end eq open eq equiv is_equiv namespace funext definition is_equiv_apd100 [instance] (f g : Πa b, C a b) : is_equiv (@apd100 A B C f g) := adjointify _ eq_of_homotopy2 begin intro H, esimp [apd100, eq_of_homotopy2], apply eq_of_homotopy, intro a, apply concat, apply (ap (λx, apd10 (x a))), apply (right_inv apd10), apply (right_inv apd10) end begin intro p, cases p, apply eq_of_homotopy2_id end definition is_equiv_apd1000 [instance] (f g : Πa b c, D a b c) : is_equiv (@apd1000 A B C D f g) := adjointify _ eq_of_homotopy3 begin intro H, esimp, apply eq_of_homotopy, intro a, transitivity apd100 (eq_of_homotopy2 (H a)), {apply ap (λx, apd100 (x a)), apply right_inv apd10}, apply right_inv apd100 end begin intro p, cases p, apply eq_of_homotopy3_id end end funext attribute funext.is_equiv_apd100 funext.is_equiv_apd1000 [constructor] namespace eq open funext local attribute funext.is_equiv_apd100 [instance] protected definition homotopy2.rec_on {f g : Πa b, C a b} {P : (f ~2 g) → Type} (p : f ~2 g) (H : Π(q : f = g), P (apd100 q)) : P p := right_inv apd100 p ▸ H (eq_of_homotopy2 p) protected definition homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ~3 g) → Type} (p : f ~3 g) (H : Π(q : f = g), P (apd1000 q)) : P p := right_inv apd1000 p ▸ H (eq_of_homotopy3 p) definition eq_equiv_homotopy2 [constructor] (f g : Πa b, C a b) : (f = g) ≃ (f ~2 g) := equiv.mk apd100 _ definition eq_equiv_homotopy3 [constructor] (f g : Πa b c, D a b c) : (f = g) ≃ (f ~3 g) := equiv.mk apd1000 _ definition apd10_ap (f : X → Πa, B a) (p : x = x') : apd10 (ap f p) = ap010 f p := eq.rec_on p idp definition eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x') : eq_of_homotopy (ap010 f p) = ap f p := inv_eq_of_eq !apd10_ap⁻¹ definition ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ~ ap010 f q) : ap f p = ap f q := calc ap f p = eq_of_homotopy (ap010 f p) : eq_of_homotopy_ap010 ... = eq_of_homotopy (ap010 f q) : eq_of_homotopy H ... = ap f q : eq_of_homotopy_ap010 end eq
1739f230e4e9991ee0f9c0b7a861cd6f341c61ad
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/continuous_function/stone_weierstrass.lean
1c07645da016767e538f2807d3ea6204f64b5003
[ "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
21,099
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Heather Macbeth -/ import topology.continuous_function.weierstrass import data.complex.is_R_or_C /-! # The Stone-Weierstrass theorem If a subalgebra `A` of `C(X, ℝ)`, where `X` is a compact topological space, separates points, then it is dense. We argue as follows. * In any subalgebra `A` of `C(X, ℝ)`, if `f ∈ A`, then `abs f ∈ A.topological_closure`. This follows from the Weierstrass approximation theorem on `[-‖f‖, ‖f‖]` by approximating `abs` uniformly thereon by polynomials. * This ensures that `A.topological_closure` is actually a sublattice: if it contains `f` and `g`, then it contains the pointwise supremum `f ⊔ g` and the pointwise infimum `f ⊓ g`. * Any nonempty sublattice `L` of `C(X, ℝ)` which separates points is dense, by a nice argument approximating a given `f` above and below using separating functions. For each `x y : X`, we pick a function `g x y ∈ L` so `g x y x = f x` and `g x y y = f y`. By continuity these functions remain close to `f` on small patches around `x` and `y`. We use compactness to identify a certain finitely indexed infimum of finitely indexed supremums which is then close to `f` everywhere, obtaining the desired approximation. * Finally we put these pieces together. `L = A.topological_closure` is a nonempty sublattice which separates points since `A` does, and so is dense (in fact equal to `⊤`). We then prove the complex version for self-adjoint subalgebras `A`, by separately approximating the real and imaginary parts using the real subalgebra of real-valued functions in `A` (which still separates points, by taking the norm-square of a separating function). ## Future work Extend to cover the case of subalgebras of the continuous functions vanishing at infinity, on non-compact spaces. -/ noncomputable theory namespace continuous_map variables {X : Type*} [topological_space X] [compact_space X] open_locale polynomial /-- Turn a function `f : C(X, ℝ)` into a continuous map into `set.Icc (-‖f‖) (‖f‖)`, thereby explicitly attaching bounds. -/ def attach_bound (f : C(X, ℝ)) : C(X, set.Icc (-‖f‖) (‖f‖)) := { to_fun := λ x, ⟨f x, ⟨neg_norm_le_apply f x, apply_le_norm f x⟩⟩ } @[simp] lemma attach_bound_apply_coe (f : C(X, ℝ)) (x : X) : ((attach_bound f) x : ℝ) = f x := rfl lemma polynomial_comp_attach_bound (A : subalgebra ℝ C(X, ℝ)) (f : A) (g : ℝ[X]) : (g.to_continuous_map_on (set.Icc (-‖f‖) ‖f‖)).comp (f : C(X, ℝ)).attach_bound = polynomial.aeval f g := begin ext, simp only [continuous_map.coe_comp, function.comp_app, continuous_map.attach_bound_apply_coe, polynomial.to_continuous_map_on_apply, polynomial.aeval_subalgebra_coe, polynomial.aeval_continuous_map_apply, polynomial.to_continuous_map_apply], end /-- Given a continuous function `f` in a subalgebra of `C(X, ℝ)`, postcomposing by a polynomial gives another function in `A`. This lemma proves something slightly more subtle than this: we take `f`, and think of it as a function into the restricted target `set.Icc (-‖f‖) ‖f‖)`, and then postcompose with a polynomial function on that interval. This is in fact the same situation as above, and so also gives a function in `A`. -/ lemma polynomial_comp_attach_bound_mem (A : subalgebra ℝ C(X, ℝ)) (f : A) (g : ℝ[X]) : (g.to_continuous_map_on (set.Icc (-‖f‖) ‖f‖)).comp (f : C(X, ℝ)).attach_bound ∈ A := begin rw polynomial_comp_attach_bound, apply set_like.coe_mem, end theorem comp_attach_bound_mem_closure (A : subalgebra ℝ C(X, ℝ)) (f : A) (p : C(set.Icc (-‖f‖) (‖f‖), ℝ)) : p.comp (attach_bound f) ∈ A.topological_closure := begin -- `p` itself is in the closure of polynomials, by the Weierstrass theorem, have mem_closure : p ∈ (polynomial_functions (set.Icc (-‖f‖) (‖f‖))).topological_closure := continuous_map_mem_polynomial_functions_closure _ _ p, -- and so there are polynomials arbitrarily close. have frequently_mem_polynomials := mem_closure_iff_frequently.mp mem_closure, -- To prove `p.comp (attached_bound f)` is in the closure of `A`, -- we show there are elements of `A` arbitrarily close. apply mem_closure_iff_frequently.mpr, -- To show that, we pull back the polynomials close to `p`, refine ((comp_right_continuous_map ℝ (attach_bound (f : C(X, ℝ)))).continuous_at p).tendsto .frequently_map _ _ frequently_mem_polynomials, -- but need to show that those pullbacks are actually in `A`. rintros _ ⟨g, ⟨-,rfl⟩⟩, simp only [set_like.mem_coe, alg_hom.coe_to_ring_hom, comp_right_continuous_map_apply, polynomial.to_continuous_map_on_alg_hom_apply], apply polynomial_comp_attach_bound_mem, end theorem abs_mem_subalgebra_closure (A : subalgebra ℝ C(X, ℝ)) (f : A) : (f : C(X, ℝ)).abs ∈ A.topological_closure := begin let M := ‖f‖, let f' := attach_bound (f : C(X, ℝ)), let abs : C(set.Icc (-‖f‖) (‖f‖), ℝ) := { to_fun := λ x : set.Icc (-‖f‖) (‖f‖), |(x : ℝ)| }, change (abs.comp f') ∈ A.topological_closure, apply comp_attach_bound_mem_closure, end theorem inf_mem_subalgebra_closure (A : subalgebra ℝ C(X, ℝ)) (f g : A) : (f : C(X, ℝ)) ⊓ (g : C(X, ℝ)) ∈ A.topological_closure := begin rw inf_eq, refine A.topological_closure.smul_mem (A.topological_closure.sub_mem (A.topological_closure.add_mem (A.subalgebra_topological_closure f.property) (A.subalgebra_topological_closure g.property)) _) _, exact_mod_cast abs_mem_subalgebra_closure A _, end theorem inf_mem_closed_subalgebra (A : subalgebra ℝ C(X, ℝ)) (h : is_closed (A : set C(X, ℝ))) (f g : A) : (f : C(X, ℝ)) ⊓ (g : C(X, ℝ)) ∈ A := begin convert inf_mem_subalgebra_closure A f g, apply set_like.ext', symmetry, erw closure_eq_iff_is_closed, exact h, end theorem sup_mem_subalgebra_closure (A : subalgebra ℝ C(X, ℝ)) (f g : A) : (f : C(X, ℝ)) ⊔ (g : C(X, ℝ)) ∈ A.topological_closure := begin rw sup_eq, refine A.topological_closure.smul_mem (A.topological_closure.add_mem (A.topological_closure.add_mem (A.subalgebra_topological_closure f.property) (A.subalgebra_topological_closure g.property)) _) _, exact_mod_cast abs_mem_subalgebra_closure A _, end theorem sup_mem_closed_subalgebra (A : subalgebra ℝ C(X, ℝ)) (h : is_closed (A : set C(X, ℝ))) (f g : A) : (f : C(X, ℝ)) ⊔ (g : C(X, ℝ)) ∈ A := begin convert sup_mem_subalgebra_closure A f g, apply set_like.ext', symmetry, erw closure_eq_iff_is_closed, exact h, end open_locale topological_space -- Here's the fun part of Stone-Weierstrass! theorem sublattice_closure_eq_top (L : set C(X, ℝ)) (nA : L.nonempty) (inf_mem : ∀ f g ∈ L, f ⊓ g ∈ L) (sup_mem : ∀ f g ∈ L, f ⊔ g ∈ L) (sep : L.separates_points_strongly) : closure L = ⊤ := begin -- We start by boiling down to a statement about close approximation. apply eq_top_iff.mpr, rintros f -, refine filter.frequently.mem_closure ((filter.has_basis.frequently_iff metric.nhds_basis_ball).mpr (λ ε pos, _)), simp only [exists_prop, metric.mem_ball], -- It will be helpful to assume `X` is nonempty later, -- so we get that out of the way here. by_cases nX : nonempty X, swap, exact ⟨nA.some, (dist_lt_iff pos).mpr (λ x, false.elim (nX ⟨x⟩)), nA.some_spec⟩, /- The strategy now is to pick a family of continuous functions `g x y` in `A` with the property that `g x y x = f x` and `g x y y = f y` (this is immediate from `h : separates_points_strongly`) then use continuity to see that `g x y` is close to `f` near both `x` and `y`, and finally using compactness to produce the desired function `h` as a maximum over finitely many `x` of a minimum over finitely many `y` of the `g x y`. -/ dsimp [set.separates_points_strongly] at sep, let g : X → X → L := λ x y, (sep f x y).some, have w₁ : ∀ x y, g x y x = f x := λ x y, (sep f x y).some_spec.1, have w₂ : ∀ x y, g x y y = f y := λ x y, (sep f x y).some_spec.2, -- For each `x y`, we define `U x y` to be `{z | f z - ε < g x y z}`, -- and observe this is a neighbourhood of `y`. let U : X → X → set X := λ x y, {z | f z - ε < g x y z}, have U_nhd_y : ∀ x y, U x y ∈ 𝓝 y, { intros x y, refine is_open.mem_nhds _ _, { apply is_open_lt; continuity, }, { rw [set.mem_set_of_eq, w₂], exact sub_lt_self _ pos, }, }, -- Fixing `x` for a moment, we have a family of functions `λ y, g x y` -- which on different patches (the `U x y`) are greater than `f z - ε`. -- Taking the supremum of these functions -- indexed by a finite collection of patches which cover `X` -- will give us an element of `A` that is globally greater than `f z - ε` -- and still equal to `f x` at `x`. -- Since `X` is compact, for every `x` there is some finset `ys t` -- so the union of the `U x y` for `y ∈ ys x` still covers everything. let ys : Π x, finset X := λ x, (compact_space.elim_nhds_subcover (U x) (U_nhd_y x)).some, let ys_w : ∀ x, (⋃ y ∈ ys x, U x y) = ⊤ := λ x, (compact_space.elim_nhds_subcover (U x) (U_nhd_y x)).some_spec, have ys_nonempty : ∀ x, (ys x).nonempty := λ x, set.nonempty_of_union_eq_top_of_nonempty _ _ nX (ys_w x), -- Thus for each `x` we have the desired `h x : A` so `f z - ε < h x z` everywhere -- and `h x x = f x`. let h : Π x, L := λ x, ⟨(ys x).sup' (ys_nonempty x) (λ y, (g x y : C(X, ℝ))), finset.sup'_mem _ sup_mem _ _ _ (λ y _, (g x y).2)⟩, have lt_h : ∀ x z, f z - ε < h x z, { intros x z, obtain ⟨y, ym, zm⟩ := set.exists_set_mem_of_union_eq_top _ _ (ys_w x) z, dsimp [h], simp only [coe_fn_coe_base', subtype.coe_mk, sup'_coe, finset.sup'_apply, finset.lt_sup'_iff], exact ⟨y, ym, zm⟩ }, have h_eq : ∀ x, h x x = f x, { intro x, simp only [coe_fn_coe_base'] at w₁, simp [coe_fn_coe_base', w₁], }, -- For each `x`, we define `W x` to be `{z | h x z < f z + ε}`, let W : Π x, set X := λ x, {z | h x z < f z + ε}, -- This is still a neighbourhood of `x`. have W_nhd : ∀ x, W x ∈ 𝓝 x, { intros x, refine is_open.mem_nhds _ _, { apply is_open_lt; continuity, }, { dsimp only [W, set.mem_set_of_eq], rw h_eq, exact lt_add_of_pos_right _ pos}, }, -- Since `X` is compact, there is some finset `ys t` -- so the union of the `W x` for `x ∈ xs` still covers everything. let xs : finset X := (compact_space.elim_nhds_subcover W W_nhd).some, let xs_w : (⋃ x ∈ xs, W x) = ⊤ := (compact_space.elim_nhds_subcover W W_nhd).some_spec, have xs_nonempty : xs.nonempty := set.nonempty_of_union_eq_top_of_nonempty _ _ nX xs_w, -- Finally our candidate function is the infimum over `x ∈ xs` of the `h x`. -- This function is then globally less than `f z + ε`. let k : (L : Type*) := ⟨xs.inf' xs_nonempty (λ x, (h x : C(X, ℝ))), finset.inf'_mem _ inf_mem _ _ _ (λ x _, (h x).2)⟩, refine ⟨k.1, _, k.2⟩, -- We just need to verify the bound, which we do pointwise. rw dist_lt_iff pos, intro z, -- We rewrite into this particular form, -- so that simp lemmas about inequalities involving `finset.inf'` can fire. rw [(show ∀ a b ε : ℝ, dist a b < ε ↔ a < b + ε ∧ b - ε < a, by { intros, simp only [← metric.mem_ball, real.ball_eq_Ioo, set.mem_Ioo, and_comm], })], fsplit, { dsimp [k], simp only [finset.inf'_lt_iff, continuous_map.inf'_apply], exact set.exists_set_mem_of_union_eq_top _ _ xs_w z, }, { dsimp [k], simp only [finset.lt_inf'_iff, continuous_map.inf'_apply], intros x xm, apply lt_h, }, end /-- The **Stone-Weierstrass Approximation Theorem**, that a subalgebra `A` of `C(X, ℝ)`, where `X` is a compact topological space, is dense if it separates points. -/ theorem subalgebra_topological_closure_eq_top_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) : A.topological_closure = ⊤ := begin -- The closure of `A` is closed under taking `sup` and `inf`, -- and separates points strongly (since `A` does), -- so we can apply `sublattice_closure_eq_top`. apply set_like.ext', let L := A.topological_closure, have n : set.nonempty (L : set C(X, ℝ)) := ⟨(1 : C(X, ℝ)), A.subalgebra_topological_closure A.one_mem⟩, convert sublattice_closure_eq_top (L : set C(X, ℝ)) n (λ f fm g gm, inf_mem_closed_subalgebra L A.is_closed_topological_closure ⟨f, fm⟩ ⟨g, gm⟩) (λ f fm g gm, sup_mem_closed_subalgebra L A.is_closed_topological_closure ⟨f, fm⟩ ⟨g, gm⟩) (subalgebra.separates_points.strongly (subalgebra.separates_points_monotone (A.subalgebra_topological_closure) w)), { simp, }, end /-- An alternative statement of the Stone-Weierstrass theorem. If `A` is a subalgebra of `C(X, ℝ)` which separates points (and `X` is compact), every real-valued continuous function on `X` is a uniform limit of elements of `A`. -/ theorem continuous_map_mem_subalgebra_closure_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) (f : C(X, ℝ)) : f ∈ A.topological_closure := begin rw subalgebra_topological_closure_eq_top_of_separates_points A w, simp, end /-- An alternative statement of the Stone-Weierstrass theorem, for those who like their epsilons. If `A` is a subalgebra of `C(X, ℝ)` which separates points (and `X` is compact), every real-valued continuous function on `X` is within any `ε > 0` of some element of `A`. -/ theorem exists_mem_subalgebra_near_continuous_map_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) (f : C(X, ℝ)) (ε : ℝ) (pos : 0 < ε) : ∃ (g : A), ‖(g : C(X, ℝ)) - f‖ < ε := begin have w := mem_closure_iff_frequently.mp (continuous_map_mem_subalgebra_closure_of_separates_points A w f), rw metric.nhds_basis_ball.frequently_iff at w, obtain ⟨g, H, m⟩ := w ε pos, rw [metric.mem_ball, dist_eq_norm] at H, exact ⟨⟨g, m⟩, H⟩, end /-- An alternative statement of the Stone-Weierstrass theorem, for those who like their epsilons and don't like bundled continuous functions. If `A` is a subalgebra of `C(X, ℝ)` which separates points (and `X` is compact), every real-valued continuous function on `X` is within any `ε > 0` of some element of `A`. -/ theorem exists_mem_subalgebra_near_continuous_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) (f : X → ℝ) (c : continuous f) (ε : ℝ) (pos : 0 < ε) : ∃ (g : A), ∀ x, ‖g x - f x‖ < ε := begin obtain ⟨g, b⟩ := exists_mem_subalgebra_near_continuous_map_of_separates_points A w ⟨f, c⟩ ε pos, use g, rwa norm_lt_iff _ pos at b, end end continuous_map section is_R_or_C open is_R_or_C -- Redefine `X`, since for the next few lemmas it need not be compact variables {𝕜 : Type*} {X : Type*} [is_R_or_C 𝕜] [topological_space X] namespace continuous_map /-- A real subalgebra of `C(X, 𝕜)` is `conj_invariant`, if it contains all its conjugates. -/ def conj_invariant_subalgebra (A : subalgebra ℝ C(X, 𝕜)) : Prop := A.map (conj_ae.to_alg_hom.comp_left_continuous ℝ conj_cle.continuous) ≤ A lemma mem_conj_invariant_subalgebra {A : subalgebra ℝ C(X, 𝕜)} (hA : conj_invariant_subalgebra A) {f : C(X, 𝕜)} (hf : f ∈ A) : (conj_ae.to_alg_hom.comp_left_continuous ℝ conj_cle.continuous) f ∈ A := hA ⟨f, hf, rfl⟩ /-- If a set `S` is conjugation-invariant, then its `𝕜`-span is conjugation-invariant. -/ lemma subalgebra_conj_invariant {S : set C(X, 𝕜)} (hS : ∀ f, f ∈ S → (conj_ae.to_alg_hom.comp_left_continuous ℝ conj_cle.continuous) f ∈ S) : conj_invariant_subalgebra ((algebra.adjoin 𝕜 S).restrict_scalars ℝ) := begin rintros _ ⟨f, hf, rfl⟩, change _ ∈ ((algebra.adjoin 𝕜 S).restrict_scalars ℝ), change _ ∈ ((algebra.adjoin 𝕜 S).restrict_scalars ℝ) at hf, rw subalgebra.mem_restrict_scalars at hf ⊢, apply algebra.adjoin_induction hf, { exact λ g hg, algebra.subset_adjoin (hS g hg), }, { exact λ c, subalgebra.algebra_map_mem _ (star_ring_end 𝕜 c) }, { intros f g hf hg, convert subalgebra.add_mem _ hf hg, exact alg_hom.map_add _ f g }, { intros f g hf hg, convert subalgebra.mul_mem _ hf hg, exact alg_hom.map_mul _ f g, } end end continuous_map open continuous_map /-- If a conjugation-invariant subalgebra of `C(X, 𝕜)` separates points, then the real subalgebra of its purely real-valued elements also separates points. -/ lemma subalgebra.separates_points.is_R_or_C_to_real {A : subalgebra 𝕜 C(X, 𝕜)} (hA : A.separates_points) (hA' : conj_invariant_subalgebra (A.restrict_scalars ℝ)) : ((A.restrict_scalars ℝ).comap (of_real_am.comp_left_continuous ℝ continuous_of_real)).separates_points := begin intros x₁ x₂ hx, -- Let `f` in the subalgebra `A` separate the points `x₁`, `x₂` obtain ⟨_, ⟨f, hfA, rfl⟩, hf⟩ := hA hx, let F : C(X, 𝕜) := f - const _ (f x₂), -- Subtract the constant `f x₂` from `f`; this is still an element of the subalgebra have hFA : F ∈ A, { refine A.sub_mem hfA (@eq.subst _ (∈ A) _ _ _ $ A.smul_mem A.one_mem $ f x₂), ext1, simp only [coe_smul, coe_one, pi.smul_apply, pi.one_apply, algebra.id.smul_eq_mul, mul_one, const_apply] }, -- Consider now the function `λ x, |f x - f x₂| ^ 2` refine ⟨_, ⟨(⟨is_R_or_C.norm_sq, continuous_norm_sq⟩ : C(𝕜, ℝ)).comp F, _, rfl⟩, _⟩, { -- This is also an element of the subalgebra, and takes only real values rw [set_like.mem_coe, subalgebra.mem_comap], convert (A.restrict_scalars ℝ).mul_mem (mem_conj_invariant_subalgebra hA' hFA) hFA, ext1, rw [mul_comm], exact (is_R_or_C.mul_conj _).symm }, { -- And it also separates the points `x₁`, `x₂` have : f x₁ - f x₂ ≠ 0 := sub_ne_zero.mpr hf, simpa only [comp_apply, coe_sub, coe_const, pi.sub_apply, coe_mk, sub_self, map_zero, ne.def, norm_sq_eq_zero] using this }, end variables [compact_space X] /-- The Stone-Weierstrass approximation theorem, `is_R_or_C` version, that a subalgebra `A` of `C(X, 𝕜)`, where `X` is a compact topological space and `is_R_or_C 𝕜`, is dense if it is conjugation-invariant and separates points. -/ theorem continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points (A : subalgebra 𝕜 C(X, 𝕜)) (hA : A.separates_points) (hA' : conj_invariant_subalgebra (A.restrict_scalars ℝ)) : A.topological_closure = ⊤ := begin rw algebra.eq_top_iff, -- Let `I` be the natural inclusion of `C(X, ℝ)` into `C(X, 𝕜)` let I : C(X, ℝ) →ₗ[ℝ] C(X, 𝕜) := of_real_clm.comp_left_continuous ℝ X, -- The main point of the proof is that its range (i.e., every real-valued function) is contained -- in the closure of `A` have key : I.range ≤ (A.to_submodule.restrict_scalars ℝ).topological_closure, { -- Let `A₀` be the subalgebra of `C(X, ℝ)` consisting of `A`'s purely real elements; it is the -- preimage of `A` under `I`. In this argument we only need its submodule structure. let A₀ : submodule ℝ C(X, ℝ) := (A.to_submodule.restrict_scalars ℝ).comap I, -- By `subalgebra.separates_points.complex_to_real`, this subalgebra also separates points, so -- we may apply the real Stone-Weierstrass result to it. have SW : A₀.topological_closure = ⊤, { have := subalgebra_topological_closure_eq_top_of_separates_points _ (hA.is_R_or_C_to_real hA'), exact congr_arg subalgebra.to_submodule this }, rw [← submodule.map_top, ← SW], -- So it suffices to prove that the image under `I` of the closure of `A₀` is contained in the -- closure of `A`, which follows by abstract nonsense have h₁ := A₀.topological_closure_map ((@of_real_clm 𝕜 _).comp_left_continuous_compact X), have h₂ := (A.to_submodule.restrict_scalars ℝ).map_comap_le I, exact h₁.trans (submodule.topological_closure_mono h₂) }, -- In particular, for a function `f` in `C(X, 𝕜)`, the real and imaginary parts of `f` are in the -- closure of `A` intros f, let f_re : C(X, ℝ) := (⟨is_R_or_C.re, is_R_or_C.re_clm.continuous⟩ : C(𝕜, ℝ)).comp f, let f_im : C(X, ℝ) := (⟨is_R_or_C.im, is_R_or_C.im_clm.continuous⟩ : C(𝕜, ℝ)).comp f, have h_f_re : I f_re ∈ A.topological_closure := key ⟨f_re, rfl⟩, have h_f_im : I f_im ∈ A.topological_closure := key ⟨f_im, rfl⟩, -- So `f_re + I • f_im` is in the closure of `A` convert A.topological_closure.add_mem h_f_re (A.topological_closure.smul_mem h_f_im is_R_or_C.I), -- And this, of course, is just `f` ext, apply eq.symm, simp [I, mul_comm is_R_or_C.I _], end end is_R_or_C
059cc4fae3ef9b375a46ef884796fd41bd050033
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/803.lean
a2b65dc650f94943db2bc9b2b7466c3b86eef32b
[ "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
586
lean
import data.matrix open algebra fin nat namespace matrix definition vector [reducible] (A : Type) (n : nat) := fin n → A definition to_cvec [reducible] [coercion] {A : Type} {n : nat} (v : vector A n) : matrix A n 1 := λ i o, v i definition to_rvec [reducible] [coercion] {A : Type} {n : nat} (v : vector A n) : matrix A 1 n := λ o i, v i variables (A : Type) (n : nat) variable [r : comm_ring A] include r variables (M : matrix A n n) (v : vector A n) print "----------------" check matrix.mul M v check (λ f, f v) (matrix.mul M) check (λ v, matrix.mul M v) v end matrix
0e58af345915a8ee65a1192bb6a3afaef83ef460
7617a8700fc3eebd9200f1e620ee65b3565d2eff
/src/vc0/preservation.lean
b0bb929d7e6fe9c480ced3097116f2ac1f1d5322
[]
no_license
digama0/vc0
9747eee791c5c2f58eb53264ca6263ee53de0f87
b8b192c8c139e0b5a25a7284b93ed53cdf7fd7a5
refs/heads/master
1,626,186,940,436
1,592,385,972,000
1,592,385,972,000
158,556,766
5
0
null
null
null
null
UTF-8
Lean
false
false
33,051
lean
import vc0.basic namespace c0 open ast ast.gdecl theorem start_ok (Γ : ast) (ok : Γ.ok) : ∀ s, start Γ s → state.ok Γ s | _ (@start.mk _ s h) := begin rcases get_body_ok' ok.ind h with ⟨h₁, h₂|⟨⟨⟩⟩⟩, rcases ok.ok_init h with ⟨δ, h₃⟩, exact state.ok.stmt (some type.int) env.ok.empty vtype.of_ty.int h₁ h₃ (or.inl h₂) end namespace value theorem default.ok {Γ : ast} {ts v} (Γok : Γ.ok) (h : default Γ ts v) (E) : ok_type_or_sdef Γ E v ts := begin induction h, { exact ⟨_, vtype.of_ty.int, ok.int⟩ }, { exact ⟨_, vtype.of_ty.bool, ok.bool⟩ }, { exact ⟨_, vtype.of_ty.ref (vtype.of_ty_fn _).2, ok.null⟩ }, { exact ⟨_, vtype.of_ty.arr (vtype.of_ty_fn _).2, ok.null_arr⟩ }, { rcases h_ih with ⟨vs, vm, al'⟩, refine ⟨_, vtype.of_ty.struct, ok.struct (λ sd' τs hd al, value.of_map_ok.2 ⟨_, rfl, _⟩) vm⟩, cases get_sdef_determ Γok.ind h_a hd, refine list.forall₂.mp_trans _ al'.flip al, rintro _ _ _ ⟨i, v, t, τ, tτ, vok⟩ ⟨_, _, τ', tτ'⟩, cases vtype.of_ty_determ tτ tτ', exact ⟨vok⟩ }, { exact ⟨∅, rfl, list.forall₂.nil⟩ }, case c0.value.default.cons : Δ x τ h v vs h₁ h₂ IH₁ IH₂ { rcases IH₁ with ⟨τ', tτ₁, vok⟩, rcases IH₂ with ⟨τs', rfl, al⟩, exact ⟨_, (of_map_cons (mt al.mem_iff.2 h)).symm, alist.forall₂_cons.2 ⟨⟨_, tτ₁, vok⟩, al⟩⟩ }, end theorem default.ok' {Γ : ast} {t τ v} (ok : Γ.ok) (h : default Γ (sum.inl t) v) (E) (tτ : vtype.of_ty (exp.type.reg t) τ) : value.ok Γ E v τ := let ⟨τ', h₁, h₂⟩ := h.ok ok E in vtype.of_ty_determ h₁ tτ ▸ h₂ theorem ok.repeat {Γ E v τ} (h : value.ok Γ E v τ) : ∀ {n}, value.ok Γ E (value.repeat v n) (vtype.arr' τ n) | 0 := value.ok.nil | (n+1) := value.ok.cons h ok.repeat end value namespace addr theorem update.ok {Γ E Δ H σ η} (ok : ast.okind Γ) (σok : vars_ty.ok Δ σ) (Hok : heap.ok Γ H E) (ηok : vars.ok Γ E η σ) {R a H' η' τ} (aok : addr.ok Γ E σ a τ) (h : update H η R a H' η') (Rok : ∀ x, value.ok Γ E x τ → ∀ y, R x y → value.ok Γ E y τ) : heap.ok Γ H' E ∧ vars.ok Γ E η' σ := begin induction h generalizing τ, case c0.addr.update.ref : R n H' { rcases aok with ⟨_, _, m⟩, suffices : ∀ E', list.forall₂ (value.ok Γ E) H E' → τ ∈ list.nth E' n → list.forall₂ (value.ok Γ E) H' E', from ⟨this _ Hok m, ηok⟩, clear Hok m, induction h_a with v v' vs r n v' H H' h IH; intros E' Hok m; cases Hok with _ τ' _ E' v'ok vsok, { cases m, exact list.forall₂.cons (Rok _ v'ok _ r) vsok }, { exact list.forall₂.cons v'ok (IH _ vsok m) } }, case c0.addr.update.var : R i v v' e mη r { refine ⟨Hok, λ j τ' τσ, _⟩, subst e, rcases ηok _ _ τσ with ⟨x, xη, xok⟩, rcases aok with _|⟨_, _, mσ⟩, revert η, refine λ η, finmap.induction_on η (λ η, _), intros, have := alist.replace_forall₂ i v' η, rcases this.rel_of_lookup_right xη with ⟨v', m', h⟩, refine ⟨v', m', _⟩, cases h, { cases option.mem_unique mη xη, cases option.mem_unique mσ τσ, exact Rok _ xok _ r }, { exact xok } }, case c0.addr.update.head : R a H' η' h IH { rcases aok with _|_|⟨_, _, τs, aok⟩, exact IH aok (at_head.ok Rok) }, case c0.addr.update.tail : R a H' η' h IH { rcases aok with _|_|_|⟨_, τ₁, _, aok⟩, exact IH aok (at_tail.ok Rok) }, case c0.addr.update.nth : R a i H' η' h IH { rcases aok with _|_|_|_|⟨_, τ₁, _, aok⟩, exact IH aok_a_2 (at_nth.ok Rok aok_a_1) }, case c0.addr.update.field : R a f H' η' h IH { rcases aok with _|_|_|_|⟨_, τ₁, _, aok⟩, exact IH aok_a_4 (at_field.ok ok Rok aok_a_1 aok_a_2 aok_a_3) }, end end addr theorem assign.ok {Γ E Δ σ η x v t τ} (σok : vars_ty.ok Δ σ) (ηok : vars.ok Γ E η σ) (xok : t ∈ Δ.lookup x) (tτ : vtype.of_ty (exp.type.reg t) τ) (vok : value.ok Γ E v τ) : ∃ σ', vars_ty.ok Δ σ' ∧ σ'.keys = insert x σ.keys ∧ vars.ok Γ E (vars.assign η x v) σ' := begin by_cases xσ : x ∈ σ, { refine ⟨σ, σok, (finset.insert_eq_of_mem (finmap.mem_keys.2 xσ)).symm, _⟩, rw [vars.assign, if_pos (ηok.mem xσ)], intros y τ' hy, by_cases x = y, { subst y, rcases σok _ _ hy with ⟨t', h₁, h₂⟩, cases option.mem_unique xok h₁, cases vtype.of_ty_determ tτ h₂, exact ⟨v, finmap.lookup_replace_self (ηok.mem xσ), vok⟩ }, { rcases ηok _ _ hy with ⟨v', h₁, h₂⟩, refine ⟨v', _, h₂⟩, convert h₁ using 1, exact finmap.lookup_replace_of_ne h } }, { refine ⟨σ.insert x τ, λ y τ' hy, _, finmap.keys_insert _ _ _, λ y τ' hy, _⟩; rw finmap.lookup_insert_of_neg xσ at hy; rcases hy with ⟨⟨⟩⟩ | hy, { exact ⟨_, xok, tτ⟩ }, { exact σok _ _ hy }, { refine ⟨v, _, vok⟩, rw vars.assign, split_ifs, { exact finmap.lookup_replace_self h }, { exact (finmap.lookup_insert_of_neg h).2 (or.inl rfl) } }, { rcases ηok _ _ hy with ⟨v', h₁, h₂⟩, refine ⟨v', _, h₂⟩, rw vars.assign, split_ifs, { rwa finmap.lookup_replace_of_ne, rintro rfl, cases xσ (finmap.exists_mem_lookup_iff.1 ⟨_, hy⟩) }, { exact (finmap.lookup_insert_of_neg h).2 (or.inr h₁) } } } end theorem value.step_binop.ok {Γ E op t₁ t₂ τ₁ τ₂ v₁ v₂ v} (sok : value.step_binop op v₁ v₂ (sum.inl v)) (opok : binop.ok op t₁ t₂) (tτ₁ : vtype.of_ty (exp.type.reg t₁) τ₁) (tτ₂ : vtype.of_ty (exp.type.reg t₂) τ₂) (vok₁ : value.ok Γ E v₁ τ₁) (vok₂ : value.ok Γ E v₂ τ₁) : value.ok Γ E v τ₂ := begin generalize_hyp e : sum.inl v = o at sok, generalize_hyp e' : op = o' at opok, induction sok; cases opok; cases e'; try {injection e, subst v}; cases tτ₁; cases tτ₂; try {constructor}, all_goals { rcases (⟨_, e⟩ : ∃ x, sum.inl v = value.to_err x) with ⟨_|_, ⟨⟩⟩, constructor } end theorem value.step_unop.ok {Γ E op t₁ t₂ τ₁ τ₂ v v'} (sok : value.step_unop op v v') (opok : unop.ok op t₁ t₂) (tτ₁ : vtype.of_ty (exp.type.reg t₁) τ₁) (tτ₂ : vtype.of_ty (exp.type.reg t₂) τ₂) (vok₁ : value.ok Γ E v τ₁) : value.ok Γ E v' τ₂ := by cases sok; cases opok; cases tτ₁; cases tτ₂; constructor theorem stmt_list.ok.mono {Γ Δ δ₁ δ₂ ret K} (ss : δ₁ ⊆ δ₂) (Kok : stmt_list.ok Γ ret Δ δ₁ K) : stmt_list.ok Γ ret Δ δ₂ K := begin induction Kok generalizing δ₂, { exact stmt_list.ok.nil Kok_a }, { rcases Kok_a_2.mono ss with ⟨δ', ss', i⟩, exact stmt_list.ok.one Kok_a Kok_a_1 i }, { rcases Kok_a_1.mono ss with ⟨δ', ss', i⟩, exact stmt_list.ok.cons Kok_a i (Kok_ih ss') }, { exact stmt_list.ok.weak (Kok_ih (finset.erase_subset_erase _ ss)) } end theorem stmt_list.ok.cons_inv {Γ E Δ σ η ret s K} (σok : vars_ty.ok Δ σ) (ηok : vars.ok Γ E η σ) : stmt_list.ok Γ ret Δ σ.keys (s :: K) → ∃ Δ' σ' δ', vars_ty.ok Δ' σ' ∧ vars.ok Γ E η σ' ∧ stmt.ok Γ ret Δ' s ∧ stmt.init' Γ Δ'.keys.to_finset σ'.keys s δ' ∧ (stmt.returns s ∨ stmt_list.ok Γ ret Δ' δ' K) := begin generalize e : (s :: K : list stmt) = K', generalize e' : σ.keys = δ, intro Kok, induction Kok generalizing σ; cases e; subst Kok_δ, { exact ⟨_, _, _, σok, ηok, Kok_a, Kok_a_2, or.inl Kok_a_1⟩ }, { rcases Kok_a_1.subset Kok_a rfl σok.subset with ⟨ss₁', ss₂'⟩, exact ⟨_, _, _, σok, ηok, Kok_a, Kok_a_1, or.inr Kok_a_2⟩ }, { exact Kok_ih rfl σok.erase ηok.erase (finmap.keys_erase _ _) } end theorem step_deref.ok {Γ E σs Δ σ H S η ret a τ K s'} (σok : vars_ty.ok Δ σ) (Eok : heap.ok Γ H E) (ηok : vars.ok Γ E η σ) (Sok : stack.ok Γ E σs S ret) (aok : addr_opt.ok Γ E σ a τ) (Kok : cont.ok' Γ E σ Δ ret K τ) (h : step_deref ⟨H, S, η⟩ a K s') : state.ok Γ s' := begin cases h, { apply state.ok.err }, { exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (h_a_1.ok σok Eok ηok aok) Kok } end theorem step_ret.ok {Γ E σs Δ σ H S η τ v s'} (σok : vars_ty.ok Δ σ) (Eok : heap.ok Γ H E) (ηok : vars.ok Γ E η σ) (Sok : stack.ok Γ E σs S τ) (vok : value.ok Γ E v τ) (h : step_ret ⟨H, S, η⟩ v s') : state.ok Γ s' := begin cases h, { cases Sok with Δ' η K' S' σ σs τ₁ τ' σok' ηok' Kok' Sok', exact state.ok.ret ⟨σok', Eok, ηok', Sok'⟩ vok Kok' }, { apply state.ok.done } end theorem step_call.ok {Γ : ast} {Δ : ctx} {E vs τs η} (τok : vtype.of_ty (exp.type.ls Δ.values) τs) (sc : step_call Δ vs η) (vok : value.ok Γ E vs τs) : ∃ σ, vars_ty.ok Δ σ ∧ vars.ok Γ E η σ ∧ Δ.keys.to_finset ⊆ σ.keys ∧ ∀ x ∈ η, x ∈ σ := begin induction sc with Δ x τ v vs η h a IH generalizing τs; cases τok; cases vok, { exact ⟨∅, by rintro _ _ ⟨⟩, by rintro _ _ ⟨⟩, λ _, id, by rintro _ ⟨_, ⟨⟩⟩⟩ }, { rcases IH τok_a_1 vok_a_1 with ⟨σ, σok, ηok, ss, ησ⟩, have ηok' := ηok.insert (mt (σok.mem ∘ ησ _) h) vok_a, refine ⟨_, (σok.weak _).insert (mt σok.mem h) alist.lookup_cons_self τok_a, ηok', _, λ y h, _⟩, { rw [alist.cons_keys, list.cons_to_finset, finmap.keys_insert], exact finset.insert_subset_insert _ ss }, { rw [← finmap.mem_keys, finmap.keys_insert, finset.mem_insert, finmap.mem_keys] at h ⊢, exact h.imp_right (ησ _) } } end theorem step_alloc.ok {Γ E σs Δ σ H S ret η τ v K s} (σok : vars_ty.ok Δ σ) (Eok : heap.ok Γ H E) (ηok : vars.ok Γ E η σ) (Sok : stack.ok Γ E σs S ret) (vok : value.ok Γ E v τ) (Kok : cont.ok' Γ E σ Δ ret K (vtype.ref τ)) (h : step_alloc ⟨H, S, η⟩ v K s) : state.ok Γ s := begin cases h, have EE : E ≤ E.add τ := E.le_add τ, refine state.ok.ret ⟨σok, Eok.add (vok.mono EE), ηok.mono EE, Sok.mono EE⟩ (value.ok.ref _) (Kok.mono EE), rintro _ ⟨⟩, rw list.forall₂_length_eq Eok, apply list.nth_concat_length end theorem step_alloc_arr.ok {Γ E σs Δ σ H S ret η τ n v K s} (σok : vars_ty.ok Δ σ) (Eok : heap.ok Γ H E) (ηok : vars.ok Γ E η σ) (Sok : stack.ok Γ E σs S ret) (vok : value.ok Γ E v (vtype.arr τ n)) (Kok : cont.ok' Γ E σ Δ ret K (vtype.refarr τ)) (h : step_alloc ⟨H, S, η⟩ v K s) : state.ok Γ s := begin cases h, have EE : E ≤ E.add (vtype.arr τ n) := E.le_add (vtype.arr τ n), refine state.ok.ret ⟨σok, Eok.add (vok.mono EE), ηok.mono EE, Sok.mono EE⟩ (value.ok.refarr _) (Kok.mono EE), rintro _ ⟨⟩, existsi n, rw list.forall₂_length_eq Eok, apply list.nth_concat_length end theorem preservation {Γ : ast} (ok : Γ.ok) {s} (sok : state.ok Γ s) {o} (iok : io.ok Γ o) {s'} (H : step Γ s o s') : state.ok Γ s' := begin cases H, case c0.step.decl : H S η v τ τ' s K H₁ { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, ⟨_, _, _, τ', _, hn, ττ', τsm, sok⟩, si, Kok⟩, cases si, refine state.ok.stmt t ⟨σok.weak _, Eok, ηok, Sok⟩ tτ sok (by simpa using si_a) _, rcases Kok with ⟨⟨_, _, _, r⟩⟩|Kok, { exact or.inl r }, { exact or.inr Kok.weak } }, case c0.step.decl_asgn : H S η v τ τ' e s K H₁ { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, Kok⟩, cases si, cases sok, refine state.ok.stmt t ⟨σok.weak sok_h, Eok, ηok, Sok⟩ tτ (stmt.ok.asgn (exp.ok.var alist.lookup_cons_self) sok_a_2.weak' sok_a_1) (ast.stmt.init.asgn ⟨⟩ si_a) (or.inr _), change stmt.init' Γ (insert v sok_Δ.keys.to_finset) (insert v sok_σ.keys) s si_δ' at si_a_1, rw [← list.cons_to_finset, ← alist.cons_keys] at si_a_1, rcases Kok with ⟨⟨⟩⟩|Kok, { exact stmt_list.ok.one sok_a_3 Kok_a si_a_1 }, { exact Kok.weak.cons sok_a_3 si_a_1 } }, case c0.step.If₁ : C c s₁ s₂ K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, Kok⟩, cases si, cases sok, refine state.ok.exp ⟨σok, Eok, ηok, Sok⟩ si_a ⟨⟩ ⟨_, sok_a_1, vtype.of_ty.bool⟩ (cont.ok.If tτ sok_a_2 si_a_1 sok_a_3 si_a_2 _), rcases Kok with ⟨⟨⟩⟩|Kok, { exact or.inl ⟨Kok_a, Kok_a_1⟩ }, { exact or.inr Kok } }, case c0.step.If₂ : C b s₁ s₂ K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, _, _, _, _, δ₁, δ₂, _, t, tτ, s₁ok, i₁, s₂ok, i₂, Kok⟩, cases b, exact state.ok.stmt t ⟨σok, Eok, ηok, Sok⟩ tτ s₂ok i₂ (Kok.imp and.right $ stmt_list.ok.mono (finset.inter_subset_right _ _)), exact state.ok.stmt t ⟨σok, Eok, ηok, Sok⟩ tτ s₁ok i₁ (Kok.imp and.left $ stmt_list.ok.mono (finset.inter_subset_left _ _)) }, case c0.step.while : C c s K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, ⟨⟨⟩⟩|Kok⟩, cases si, cases id sok, have := si_a_1.subset a_1 rfl σok.subset, rcases si.mono this.1 with ⟨δ'', ss', i'⟩, exact (state.ok.exp ⟨σok, Eok, ηok, Sok⟩ si_a ⟨⟩ ⟨_, a, vtype.of_ty.bool⟩ $ cont.ok.If tτ (a_1.seq sok) (si_a_1.seq i') stmt.ok.nop stmt.init.nop $ or.inr $ Kok.mono $ finset.subset_inter ss' (finset.subset.refl _)) }, case c0.step.asgn₁ : C lv e K eq { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, ⟨⟨⟩⟩|Kok⟩, cases si, cases sok, rcases vtype.of_ty_fn sok_τ with ⟨vτ, hv⟩, rw [lval.uses, eq] at si_a, rw eq at Kok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ si_a lv.ok ⟨_, sok_a_1, hv⟩ (cont.ok.asgn₁ ⟨_, sok_a_2, hv⟩ si_a_1 ⟨t, tτ, Kok⟩) }, case c0.step.asgn₂ : C a e K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, aok, _|⟨_, _, _, _, ⟨t, eok, tτ⟩, eu, t', tτ', Kok⟩⟩, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu ⟨⟩ ⟨_, eok, tτ⟩ (cont.ok.asgn₂ aok ⟨_, tτ', Kok⟩) }, case c0.step.asgn₃ : H H' S η η' a v K h { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, _|_|⟨_, _, _, _, aok, t, tτ, Kok⟩⟩, rcases h.ok ok.ind σok Eok ηok aok (addr.eq.ok vok) with ⟨Eok', ηok'⟩, exact state.ok.stmt t ⟨σok, Eok', ηok', Sok⟩ tτ stmt.ok.nop stmt.init.nop (or.inr Kok) }, case c0.step.asgn_var₁ : C lv x e K eq { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, ⟨⟨⟩⟩|Kok⟩, cases si, cases sok, cases lv; cases eq, rcases vtype.of_ty_fn sok_τ with ⟨vτ, hv⟩, rcases sok_a_1 with _|_|_|⟨_, t', tΔ⟩, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ si_a_1 ⟨⟩ ⟨_, sok_a_2, hv⟩ (cont.ok.asgn_var tΔ hv ⟨_, tτ, Kok⟩) }, case c0.step.asgn_var₂ : H S η x v K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, rcases Kok_a_2 with ⟨t, tτ, Kok⟩, rcases assign.ok σok ηok Kok_a Kok_a_1 vok with ⟨σ', σok', e, ηok'⟩, exact state.ok.stmt _ ⟨σok', Eok, ηok', Sok⟩ tτ stmt.ok.nop stmt.init.nop (or.inr (by rwa e)) }, case c0.step.asgn_err : H S η v K { apply state.ok.err }, case c0.step.asnop₁ : C lv op e K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, ⟨⟨⟩⟩|Kok⟩, cases si, cases id sok, rcases vtype.of_ty_fn (exp.type.reg τ_1) with ⟨vτ, hv⟩, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ si_a lv.ok ⟨_, a, hv⟩ (cont.ok.asnop a_2 hv a_1 si_a_1 ⟨_, tτ, Kok⟩) }, case c0.step.asnop₂ : _ C a op e K h { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, aok, Kok⟩, cases Kok, cases Kok_a with _ opok, exact step_deref.ok σok Eok ηok Sok aok (cont.ok.binop₁ opok Kok_a_1 Kok_a_1 Kok_a_2 Kok_a_3 $ cont.ok.asgn₂ aok Kok_a_4) h }, case c0.step.eval₁ : C e K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, ⟨⟨⟩⟩|Kok⟩, cases si, cases id sok, rcases vtype.of_ty_fn τ_1 with ⟨vτ, hv⟩, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ si_a ⟨⟩ ⟨_, a, hv⟩ (cont.ok.eval ⟨t, tτ, Kok⟩) }, case c0.step.eval₂ : C e K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, aok, Kok⟩, cases Kok, rcases Kok_a with ⟨t, tτ, Kok⟩, exact state.ok.stmt t ⟨σok, Eok, ηok, Sok⟩ tτ stmt.ok.nop stmt.init.nop (or.inr Kok) }, case c0.step.assert₁ : C e K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, ⟨⟨⟩⟩|Kok⟩, cases si, cases id sok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ si_a ⟨⟩ ⟨_, a, vtype.of_ty.bool⟩ (cont.ok.assert ⟨t, tτ, Kok⟩) }, case c0.step.assert₂ : C b K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, aok, Kok⟩, cases b, {apply state.ok.err}, cases Kok, rcases Kok_a with ⟨t, tτ, Kok⟩, exact state.ok.stmt t ⟨σok, Eok, ηok, Sok⟩ tτ stmt.ok.nop stmt.init.nop (or.inr Kok) }, case c0.step.ret₁ : C e K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, Kok⟩, cases si, cases id sok, cases a, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ (si_a _ rfl) ⟨⟩ ⟨_, a_a_1, tτ⟩ cont.ok.ret }, case c0.step.ret₂ : _ C v h { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, ⟨⟩⟩, exact h.ok σok Eok ηok Sok vok }, case c0.step.ret_none : _ C v h { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, Kok⟩, cases id sok, cases a, cases tτ, exact h.ok σok Eok ηok Sok value.ok.nil }, case c0.step.nop₁ : _ C h { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, _, si, ⟨⟨⟩⟩|Kok⟩, cases si, cases Kok.eq_none, cases tτ, exact h.ok σok Eok ηok Sok value.ok.nil }, case c0.step.nop₂ : C s K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, _, si, ⟨⟨⟩⟩|Kok⟩, cases si, rcases Kok.cons_inv σok ηok with ⟨Δ', σ', δ', σok', ηok', sok, si', Kok⟩, exact state.ok.stmt t ⟨σok', Eok, ηok', Sok⟩ tτ sok si' Kok }, case c0.step.seq : C s₁ s₂ K { rcases sok with ⟨_, _, _, _, _, τ, _, _, _, t, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, tτ, sok, si, Kok⟩, cases si, cases id sok, rcases Kok with ⟨⟨⟩⟩|Kok, { exact state.ok.stmt t ⟨σok, Eok, ηok, Sok⟩ tτ a si_a (or.inl Kok_a) }, { exact state.ok.stmt t ⟨σok, Eok, ηok, Sok⟩ tτ a si_a (or.inr $ stmt_list.ok.one a_1 Kok_a si_a_1) }, { exact state.ok.stmt t ⟨σok, Eok, ηok, Sok⟩ tτ a si_a (or.inr $ Kok.cons a_1 si_a_1) } }, case c0.step.int : C n K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, ⟨⟩, tτ⟩, Kok⟩, cases tτ, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ value.ok.int Kok }, case c0.step.bool : C b K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, ⟨⟩, tτ⟩, Kok⟩, cases tτ, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ value.ok.bool Kok }, case c0.step.null : C K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, ⟨⟩, tτ⟩, Kok⟩, cases tτ, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ value.ok.null Kok }, case c0.step.var : C i v K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨_, _|_|_|⟨_, t, iΔ⟩, tτ⟩, Kok⟩, rcases finmap.exists_mem_lookup_iff.2 (finmap.mem_keys.1 eu) with ⟨τ', iτ'⟩, cases vtype.of_ty_determ tτ (σok.ok_of_mem iτ' iΔ), exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (ηok.ok_of_mem iτ' H_a) Kok }, case c0.step.binop₁ : C op e₁ e₂ K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, ⟨eu₁, eu₂⟩, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, rcases vtype.of_ty_fn (exp.type.reg eok_τ₁) with ⟨vτ₁, hv₁⟩, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu₁ ⟨⟩ ⟨_, eok_a, hv₁⟩ (cont.ok.binop₁ eok_a_2 hv₁ tτ eok_a_1 eu₂ Kok) }, case c0.step.binop₂ : C op v₁ e₂ K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ Kok_a_4 ⟨⟩ ⟨_, Kok_a_3, Kok_a_1⟩ (cont.ok.binop₂ Kok_a Kok_a_1 Kok_a_2 vok Kok_a_5) }, case c0.step.binop₃ : C op v₁ v₂ v K sb { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok₂, Kok⟩, cases Kok, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (sb.ok Kok_a Kok_a_1 Kok_a_2 Kok_a_3 vok₂) Kok_a_4 }, case c0.step.binop_err : C op v₁ v₂ err K sb { apply state.ok.err }, case c0.step.unop₁ : C op e K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, rcases vtype.of_ty_fn (exp.type.reg eok_τ₁) with ⟨vτ₁, hv₁⟩, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu ⟨⟩ ⟨_, eok_a, hv₁⟩ (cont.ok.unop eok_a_1 hv₁ tτ Kok) }, case c0.step.unop₂ : C op v v' K su { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (su.ok Kok_a Kok_a_1 Kok_a_2 vok) Kok_a_3 }, case c0.step.cond₁ : C c e₁ e₂ K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, ⟨euc, eu₁, eu₂⟩, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ euc ⟨⟩ ⟨_, eok_a, vtype.of_ty.bool⟩ (cont.ok.cond ⟨_, eok_a_1, tτ⟩ eu₁ ⟨_, eok_a_2, tτ⟩ eu₂ Kok) }, case c0.step.cond₂ : C b e₁ e₂ K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, cases b, { exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ Kok_a_3 ⟨⟩ Kok_a_2 Kok_a_4 }, { exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ Kok_a_1 ⟨⟩ Kok_a Kok_a_4 } }, case c0.step.nil : C K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, ⟨⟩, tτ⟩, Kok⟩, cases tτ, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ value.ok.nil Kok }, case c0.step.cons₁ : C e es K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, ⟨eu₁, eu₂⟩, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, cases tτ, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu₁ ⟨⟩ ⟨_, eok_a, tτ_a⟩ (cont.ok.cons₁ ⟨_, eok_a_1, tτ_a_1⟩ eu₂ Kok) }, case c0.step.cons₂ : C v es K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ Kok_a_1 ⟨⟩ Kok_a (cont.ok.cons₂ vok Kok_a_2) }, case c0.step.cons₃ : C v₁ v₂ K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok₂, Kok⟩, cases Kok, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (value.ok.cons Kok_a vok₂) Kok_a_1 }, case c0.step.call₁ : C op e K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, ⟨fok, eu⟩, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, rcases vtype.of_ty_fn (exp.type.ls eok_τs) with ⟨vτs, tτs⟩, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu ⟨⟩ ⟨_, eok_a_1, tτs⟩ (cont.ok.call eok_a fok tτ tτs Kok) }, case c0.step.call₂ : H S η η' f τ Δ' s vs K bok sc { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, cases ok.fdef_uniq bok.get_fdef Kok_a, rcases sc.ok Kok_a_3 vok with ⟨σ', σok', ηok', ss, _⟩, rcases get_body_ok' ok.ind bok with ⟨sok, r⟩, rcases ok.ok_init bok with ⟨δ, si⟩, rcases si.mono ss with ⟨δ', ss', si'⟩, exact state.ok.stmt _ ⟨σok', Eok, ηok', Sok.cons σok ηok Kok_a_4⟩ Kok_a_2 sok si' (r.imp_right stmt_list.ok.nil) }, case c0.step.call_extern : H S η f vs H' v K ext { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, rcases iok ext Kok_a Kok_a_2 Kok_a_3 Eok vok with ⟨E', EE, Eok', vok'⟩, exact state.ok.ret ⟨σok, Eok', ηok.mono EE, Sok.mono EE⟩ vok' (Kok_a_4.mono EE) }, case c0.step.deref : C e K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu ⟨⟩ ⟨_, eok_a, tτ.ref⟩ (cont.ok.addr_deref $ cont.ok.deref Kok) }, case c0.step.index : C e n K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, ⟨eu₁, eu₂⟩, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu₁ ⟨⟩ ⟨_, eok_a, tτ.arr⟩ (cont.ok.addr_index₁ eok_a_1 eu₂ $ cont.ok.deref Kok) }, case c0.step.field : C e n K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu (lv_ok_of_struct ok.ind eok_a) ⟨_, eok_a, vtype.of_ty.struct⟩ (cont.ok.addr_field eok_a_1 eok_a_2 tτ $ cont.ok.deref Kok) }, case c0.step.deref' : _ C a K sd { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, aok, Kok⟩, cases Kok, exact sd.ok σok Eok ηok Sok aok Kok_a }, case c0.step.alloc_ref : _ C τ τ' v K ττ' v0 sa { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, cases ast.eval_ty.determ ok.ind ττ' eok_a, cases tτ, refine sa.ok σok Eok ηok Sok (v0.ok' ok _ tτ_a) Kok }, case c0.step.alloc_arr₁ : C τ τ' e K ττ' { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, cases ast.eval_ty.determ ok.ind ττ' eok_a, cases tτ, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu ⟨⟩ ⟨_, eok_a_2, vtype.of_ty.int⟩ (cont.ok.alloc_arr tτ eok_a_1 Kok) }, case c0.step.alloc_arr₂ : _ C τ v K i n e v0 sa { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, cases Kok_a, exact step_alloc_arr.ok σok Eok ηok Sok (v0.ok' ok _ Kok_a_a).repeat.arr Kok_a_2 sa }, case c0.step.alloc_arr_err : C τ i K i0 { apply state.ok.err }, case c0.step.addr_var : C v K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, rcases finmap.exists_mem_lookup_iff.2 (finmap.mem_keys.1 eu) with ⟨τ', vτ'⟩, cases vtype.of_ty_determ (σok.ok_of_mem vτ' eok_a) tτ, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (addr.ok.var vτ') Kok }, case c0.step.addr_deref₁ : C e K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu ⟨⟩ ⟨_, eok_a, tτ.ref⟩ (cont.ok.addr_deref Kok) }, case c0.step.addr_deref₂ : C v K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, refine state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (addr.ok.ref_opt vok) Kok_a }, case c0.step.addr_index₁ : C e n K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, ⟨eu₁, eu₂⟩, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu₁ ⟨⟩ ⟨_, eok_a, tτ.arr⟩ (cont.ok.addr_index₁ eok_a_1 eu₂ Kok) }, case c0.step.addr_index₂ : C a n K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, vok, Kok⟩, cases Kok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ Kok_a_1 ⟨⟩ ⟨_, Kok_a, vtype.of_ty.int⟩ (cont.ok.addr_index₂ (addr.ok.refarr_opt vok) Kok_a_2) }, case c0.step.addr_index₃ : C a n K i j len e lt { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, _, Kok⟩, cases Kok, cases len with _ _ v aok, cases Kok_a _ rfl with n h, cases addr.get.ok σok Eok ηok h aok, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (h.nth lt) Kok_a_1 }, case c0.step.addr_index_err₁ : C i K { apply state.ok.err }, case c0.step.addr_index_err₂ : C a n K i { apply state.ok.err }, case c0.step.addr_field₁ : C e f K { rcases sok with _|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, eu, _, ⟨t, eok, tτ⟩, Kok⟩, cases eok, exact state.ok.exp ⟨σok, Eok, ηok, Sok⟩ eu (lv_ok_of_struct ok.ind eok_a) ⟨_, eok_a, vtype.of_ty.struct⟩ (cont.ok.addr_field eok_a_1 eok_a_2 tτ Kok) }, case c0.step.addr_field₂ : C a f K { rcases sok with _|_|⟨E, σs, σ, H, η, S, Δ, ret, τ, α, v, K, ⟨E, σs, σ, H, η, S, Δ, _, σok, Eok, ηok, Sok⟩, aok, Kok⟩, cases Kok, exact state.ok.ret ⟨σok, Eok, ηok, Sok⟩ (addr.ok.field Kok_a Kok_a_1 Kok_a_2 aok) Kok_a_3 }, case c0.step.addr_field_err : C f K { apply state.ok.err } end end c0
bdcb3d1c2e52238631b62b2111d9d0c7af348756
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/rescale/normed_group.lean
d75e8a6ad37cbdb8ec3e6d373ba023107e074536
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,140
lean
import rescale.basic import locally_constant.Vhat import category_theory.preadditive.additive_functor import facts.nnreal noncomputable theory open_locale big_operators classical nnreal namespace rescale variables {N : ℝ≥0} {V : Type*} instance [has_norm V] : has_norm (rescale N V) := { norm := λ v, ∥of.symm v∥/N } lemma norm_def [has_norm V] (v : rescale N V) : ∥v∥ = ∥of.symm v∥/N := rfl instance [hN : fact (0 < N)] [semi_normed_group V] : semi_normed_group (rescale N V) := semi_normed_group.of_core (rescale N V) { norm_zero := show ∥(0 : V)∥/N = 0, by rw [norm_zero, zero_div], triangle := λ v w, begin simp only [norm_def, ← add_div], exact div_le_div_of_le hN.out.le (norm_add_le _ _), -- defeq abuse end, norm_neg := λ v, by { simp only [norm_def], congr' 1, exact norm_neg _ /- defeq abuse -/ } } instance [hN : fact (0 < N)] [normed_group V] : normed_group (rescale N V) := normed_group.of_core (rescale N V) { norm_eq_zero_iff := λ v, begin have aux : (N:ℝ) ≠ 0 := ne_of_gt hN.out, simp only [norm_def, div_eq_zero_iff, aux, or_false], exact norm_eq_zero -- defeq abuse end, triangle := λ v w, begin simp only [norm_def, ← add_div], exact div_le_div_of_le hN.out.le (norm_add_le _ _), -- defeq abuse end, norm_neg := λ v, by { simp only [norm_def], congr' 1, exact norm_neg _ /- defeq abuse -/ } } lemma nnnorm_def [hN : fact (0 < N)] [semi_normed_group V] (v : rescale N V) : ∥v∥₊ = ∥of.symm v∥₊ / N := rfl end rescale namespace SemiNormedGroup variables (r r₁ r₂ : ℝ≥0) [fact (0 < r₁)] [fact (0 < r₂)] @[simps] def rescale (r : ℝ≥0) [hr : fact (0 < r)] : SemiNormedGroup ⥤ SemiNormedGroup := { obj := λ V, of $ rescale r V, map := λ V₁ V₂ f, { to_fun := λ v, @rescale.of r V₂ $ f ((@rescale.of r V₁).symm v), map_add' := f.map_add, -- defeq abuse bound' := begin obtain ⟨C, C_pos, hC⟩ := f.bound, use C, intro v, have := hC ((@rescale.of r V₁).symm v), rw [← div_le_div_right (show 0 < (r:ℝ), from hr.1), mul_div_assoc] at this, exact this, end }, map_id' := λ V, rfl, -- defeq abuse map_comp' := λ V₁ V₂ V₃ f g, rfl /- defeq abuse -/ } instance rescale.additive [fact (0 < r)] : (rescale r).additive := { map_zero' := λ V W, rfl, -- defeq abuse map_add' := λ V W f g, rfl /- defeq abuse -/ } lemma norm_rescale_map_le [fact (0 < r)] {V₁ V₂ : SemiNormedGroup} {f : V₁ ⟶ V₂} {C : ℝ} (hf : ∥f∥ ≤ C) : ∥(rescale r).map f∥ ≤ C := begin refine normed_group_hom.op_norm_le_bound _ (le_trans (norm_nonneg _) hf) (λ v, _), dsimp, erw [rescale.norm_def, rescale.norm_def, equiv.symm_apply_apply, ← mul_div_assoc], refine div_le_div (mul_nonneg (le_trans (norm_nonneg _) hf) (norm_nonneg _)) (normed_group_hom.le_of_op_norm_le _ hf _) _ le_rfl, rw nnreal.coe_pos, apply fact.out end lemma rescale_map_isometry [fact (0 < r)] {V₁ V₂ : SemiNormedGroup} {f : V₁ ⟶ V₂} (hf : isometry f) : isometry ((rescale r).map f) := begin rw normed_group_hom.isometry_iff_norm at hf ⊢, intro v, erw [rescale.norm_def, rescale.norm_def, hf ((@rescale.of r _).symm v)], end lemma rescale_exact [fact (0 < r)] {V₁ V₂ V₃ : SemiNormedGroup} (f : V₁ ⟶ V₂) (g : V₂ ⟶ V₃) (hfg : f.range = g.ker) : ((rescale r).map f).range = ((rescale r).map g).ker := begin ext x, calc x ∈ ((rescale r).map f).range ↔ x ∈ f.range : iff.rfl ... ↔ x ∈ g.ker : by rw hfg ... ↔ x ∈ ((rescale r).map g).ker : iff.rfl, end lemma rescale_exists_norm_le [fact (0 < r)] {V₁ V₂ : SemiNormedGroup} (f : V₁ ⟶ V₂) (C : ℝ≥0) (hf : ∀ y, ∃ x, f x = y ∧ ∥x∥ ≤ C * ∥y∥) : ∀ y, ∃ x, (rescale r).map f x = y ∧ ∥x∥ ≤ C * ∥y∥ := begin intro y, obtain ⟨x, h1, h2⟩ := hf ((@rescale.of r _).symm y), refine ⟨@rescale.of r _ x, h1, _⟩, erw [rescale.norm_def, rescale.norm_def], simp only [div_eq_mul_inv, ← mul_assoc, equiv.symm_apply_apply, ← coe_nnnorm], norm_cast, exact mul_le_mul' h2 le_rfl, end lemma nnnorm_to_rescale {V : SemiNormedGroup} (v : V) : ∥(@rescale.of r V) v∥ ≤ r⁻¹ * ∥v∥ := by { rw ← div_eq_inv_mul, refl } def to_rescale [fact (0 < r)] : 𝟭 _ ⟶ rescale r := { app := λ V, add_monoid_hom.mk_normed_group_hom' (add_monoid_hom.mk' (@rescale.of r V) $ λ _ _, rfl) r⁻¹ (λ v, nnnorm_to_rescale _ v), naturality' := λ V W f, rfl /- defeq abuse -/ } def of_rescale [hr : fact (0 < r)] : rescale r ⟶ 𝟭 _ := { app := λ V, add_monoid_hom.mk_normed_group_hom' (add_monoid_hom.mk' (@rescale.of r V) .symm $ λ _ _, rfl) r begin intro v, erw [rescale.nnnorm_def, mul_div_cancel' _ hr.1.ne'], exact le_rfl end, naturality' := λ V W f, rfl /- defeq abuse -/ } @[simps] def iso_rescale [fact (0 < r)] : 𝟭 _ ≅ (rescale r) := { hom := to_rescale r, inv := of_rescale r, } open category_theory lemma iso_rescale_isometry [fact (0 < r)] (h : r = 1) (V : SemiNormedGroup) : isometry ((iso_rescale r).app V).hom := begin unfreezingI { cases h }, dsimp only [nat_iso.app_hom, iso_rescale_hom], apply normed_group_hom.isometry_of_norm, intro v, erw [rescale.norm_def], simp only [div_one, subtype.coe_mk], refl end lemma norm_to_rescale_le [fact (0 < r)] (V : SemiNormedGroup) : ∥(to_rescale r).app V∥ ≤ r⁻¹ := normed_group_hom.mk_normed_group_hom_norm_le _ (inv_nonneg.2 (nnreal.zero_le_coe)) (λ v, nnnorm_to_rescale _ v) lemma nnnorm_rescale_rescale_symm {V : SemiNormedGroup} (v : (rescale r₁).obj V) : ∥(@rescale.of r₂ V) ((@rescale.of r₁ V).symm v)∥₊ ≤ r₁ / r₂ * ∥v∥₊ := begin apply le_of_eq, show _ = r₁ / r₂ * (∥(@rescale.of r₁ V).symm v∥₊ / r₁), simp only [add_monoid_hom.mk'_apply, div_eq_inv_mul, rescale.nnnorm_def], rw [mul_assoc, mul_inv_cancel_left' (show r₁ ≠ 0, from ne_of_gt $ fact.out _)], refl end def scale : rescale r₁ ⟶ rescale r₂ := { app := λ V, add_monoid_hom.mk_normed_group_hom' (add_monoid_hom.mk' (λ v, (@rescale.of r₂ V) $ (@rescale.of r₁ V).symm v) $ λ _ _, rfl) (r₁ / r₂) (λ v, nnnorm_rescale_rescale_symm r₁ r₂ v), naturality' := λ V W f, rfl /- defeq abuse -/ } lemma norm_scale_le (V : SemiNormedGroup) : ∥(scale r₁ r₂).app V∥ ≤ (r₁ / r₂) := normed_group_hom.mk_normed_group_hom_norm_le _ (div_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) (λ v, nnnorm_rescale_rescale_symm r₁ r₂ v) lemma scale_comm {V₁ V₂ W₁ W₂ : SemiNormedGroup} (f₁ : V₁ ⟶ W₁) (f₂ : V₂ ⟶ W₂) (φ : V₁ ⟶ V₂) (ψ : W₁ ⟶ W₂) (h : f₁ ≫ ψ = φ ≫ f₂) : (rescale r₁).map f₁ ≫ ((rescale r₁).map ψ ≫ (scale r₁ r₂).app W₂) = ((rescale r₁).map φ ≫ (scale r₁ r₂).app V₂) ≫ (rescale r₂).map f₂ := by rw [← category.assoc, ← category_theory.functor.map_comp, nat_trans.naturality, nat_trans.naturality, category.assoc, ← category_theory.functor.map_comp, h] end SemiNormedGroup
e130840d733c2bc3ecad225b40259c3272f6b34f
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Data/Char/Basic.lean
c08b18437ba73e04602f3ccf7fc3541354fde9c9
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,592
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.UInt @[inline, reducible] def isValidChar (n : UInt32) : Prop := n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000) /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char := (val : UInt32) (valid : isValidChar val) instance : HasSizeof Char := ⟨fun c => c.val.toNat⟩ namespace Char def utf8Size (c : Char) : UInt32 := let v := c.val; if UInt32.land v 0x80 = 0 then 1 else if UInt32.land v 0xE0 = 0xC0 then 2 else if UInt32.land v 0xF0 = 0xE0 then 3 else if UInt32.land v 0xF8 = 0xF0 then 4 else if UInt32.land v 0xFC = 0xF8 then 5 else if UInt32.land v 0xFE = 0xFC then 6 else if v = 0xFF then 1 else 0 protected def Less (a b : Char) : Prop := a.val < b.val protected def LessEq (a b : Char) : Prop := a.val ≤ b.val instance : HasLess Char := ⟨Char.Less⟩ instance : HasLessEq Char := ⟨Char.LessEq⟩ protected def lt (a b : Char) : Bool := a.val < b.val instance decLt (a b : Char) : Decidable (a < b) := UInt32.decLt _ _ instance decLe (a b : Char) : Decidable (a ≤ b) := UInt32.decLe _ _ axiom isValidChar0 : isValidChar 0 @[noinline, matchPattern] def ofNat (n : Nat) : Char := if h : isValidChar n.toUInt32 then {val := n.toUInt32, valid := h} else {val := 0, valid := isValidChar0} @[inline] def toNat (c : Char) : Nat := c.val.toNat theorem eqOfVeq : ∀ {c d : Char}, c.val = d.val → c = d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem veqOfEq : ∀ {c d : Char}, c = d → c.val = d.val | _, _, rfl => rfl theorem neOfVne {c d : Char} (h : c.val ≠ d.val) : c ≠ d := fun h' => absurd (veqOfEq h') h theorem vneOfNe {c d : Char} (h : c ≠ d) : c.val ≠ d.val := fun h' => absurd (eqOfVeq h') h @[inline] instance : DecidableEq Char := fun i j => decidableOfDecidableOfIff (decEq i.val j.val) ⟨Char.eqOfVeq, Char.veqOfEq⟩ instance : Inhabited Char := ⟨'A'⟩ def isWhitespace (c : Char) : Bool := c = ' ' || c = '\t' || c = '\n' def isUpper (c : Char) : Bool := c.val ≥ 65 && c.val ≤ 90 def isLower (c : Char) : Bool := c.val ≥ 97 && c.val ≤ 122 def isAlpha (c : Char) : Bool := c.isUpper || c.isLower def isDigit (c : Char) : Bool := c.val ≥ 48 && c.val ≤ 57 def isAlphanum (c : Char) : Bool := c.isAlpha || c.isDigit def toLower (c : Char) : Char := let n := toNat c; if n >= 65 ∧ n <= 90 then ofNat (n + 32) else c end Char
55a0d44dab88af1ce355bce0a7ea02f0e8e4c5ea
cbb817439c51008d66b37ce6b1964fea61434d35
/theorem-proving-in-lean/src/chap_5.lean
70772cf3588b1729649b65d55edb2ff5220d7a28
[]
no_license
tomhoule/theorem-proving-in-lean-exercises
a07f99d4f6b41ce003e8a0274c7bc46359fa62b2
60ccc71b8a6df6924e7cc90aab713b804f78da9f
refs/heads/master
1,663,582,321,828
1,590,352,467,000
1,590,352,476,000
257,107,936
3
0
null
null
null
null
UTF-8
Lean
false
false
15,096
lean
section chap3ex1 variables p q r : Prop example : p ∧ q ↔ q ∧ p := begin apply iff.intro, repeat { intro h, exact and.intro h.right h.left, } end example : p ∨ q ↔ q ∨ p := begin apply iff.intro, intro h, apply or.elim h, intro hp, right, exact hp, intro hq, left, exact hq, intro h, apply or.elim h, intro hp, right, exact hp, intro hq, left, exact hq end example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := begin apply iff.intro, intro h, exact and.intro h.left.left ⟨h.left.right, h.right⟩, intro h, exact and.intro ⟨h.left, h.right.left⟩ h.right.right end example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := begin apply iff.intro, { intro h, cases h with hpq hr, { cases hpq with hp hq, { left, assumption }, { right, left, assumption }}, { right, right, exact hr }}, intro h, cases h with hp hqr, { left, left, exact hp }, { cases hqr with hq hr, { left, right, exact hq }, { right, exact hr }} end example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin apply iff.intro, { intro h, have hp : p, from h.left, have hqr : q ∨ r, from h.right, cases hqr with hq hr, { left, constructor, assumption, assumption }, right, constructor, assumption, assumption }, intro h, cases h with hpq hpr, { constructor, exact hpq.left, left, exact hpq.right }, constructor, exact hpr.left, right, exact hpr.right end example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := begin apply iff.intro, { intro h, cases h with hp hqr, { constructor, repeat { left, exact hp } }, { constructor; right, exact hqr.left, exact hqr.right } }, intro h, have pq : p ∨ q, from h.left, have pr : p ∨ r, from h.right, cases pq with hp hq, { left, exact hp }, have hq : q, from hq, cases pr with hp hr, { left, exact hp }, right, constructor, exact hq, exact hr end example : (p → (q → r)) ↔ (p ∧ q → r) := begin apply iff.intro, { intros h1 h2, exact h1 h2.left h2.right }, intros h1 hp hq, have pq : p ∧ q, { constructor, repeat { assumption }}, exact h1 pq end example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := begin apply iff.intro, { intro h, constructor ; { intro h1, have pq : p ∨ q, { { left, exact h1 } <|> { right, exact h1 } }, exact h pq }}, intros h1 h2, cases h2 with hp hq, exact h1.left hp, exact h1.right hq end example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := begin apply iff.intro, { intro hnpq, constructor ; { intro h1, have hpq : p ∨ q, { { left <|> right, exact h1 } <|> { right, exact h1 } }, exact absurd hpq hnpq }}, intros h hc, have hnp : ¬ p, from h.left, have hnq : ¬ q, from h.right, cases hc with hp hq; { apply absurd, exact hp <|> exact hq, assumption} end example : ¬p ∨ ¬q → ¬(p ∧ q) := begin intros hdis hconj, cases hdis with hnp hnq, { exact absurd hconj.left hnp }, exact absurd hconj.right hnq end example : ¬(p ∧ ¬p) := begin intro h, exact absurd h.left h.right end example : p ∧ ¬q → ¬(p → q) := begin intros hconj hn, have hq : q, { exact hn hconj.left }, exact absurd hq hconj.right end example : ¬p → (p → q) := begin intros hnp hp, exact (false.elim $ hnp hp) end example : (¬p ∨ q) → (p → q) := begin intros hdis hp, cases hdis with hnp hq, { exact absurd hp hnp }, assumption end example : p ∨ false ↔ p := begin apply iff.intro, { intro h, cases h with hp hfalse, assumption, exact false.elim hfalse }, intro hp, left, exact hp end example : p ∧ false ↔ false := begin apply iff.intro, { intro h, exact h.right }, intro hfalse, exact false.elim hfalse end example : ¬(p ↔ ¬p) := begin intro h, have l : p → ¬p, { exact iff.elim_left h }, have r : ¬p → p, { exact iff.elim_right h }, have hnp : ¬p, { intro hp, exact absurd hp (l hp) }, exact absurd (r hnp) hnp, end example : (p → q) → (¬q → ¬p) := begin intros hptoq hnq hp, exact absurd (hptoq hp) hnq end end chap3ex1 section chap3ex2 open classical variables p q r s : Prop example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := begin intro h, cases (em p) with hp hnp, { cases (h hp) with hr hs, { left, exact (λ hp, hr) }, right, exact (λ hp, hs)}, left, intro hp, contradiction end example : ¬(p ∧ q) → ¬p ∨ ¬q := begin intro h, cases (em p) with hp hnp, { cases (em q) with hq hnq, { exact (false.elim $ h ⟨hp, hq⟩) }, right, exact hnq }, left, exact hnp end example : ¬(p → q) → p ∧ ¬q := begin intro h, cases (em p) with hp hnp, { cases (em q) with hq hnq, { have ptoq : (p → q), from λ hp, hq, contradiction }, constructor, assumption, assumption }, cases (em q) with hq hnq, { have ptoq : p → q, from λ hp, absurd hp hnp, contradiction }, have ptoq : p → q, { intro hp, contradiction }, contradiction end example : (p → q) → (¬p ∨ q) := begin intro h, cases (em p) with hp hnp, { right, exact h hp }, left, exact hnp end example : (¬q → ¬p) → (p → q) := begin intro h, cases (em q) with hq hnq, { exact (λ hp, hq) }, have hnp : ¬p, from h hnq, exact (λ hp, absurd hp hnp) end example : p ∨ ¬p := begin cases (em p) with hp hnp, { left, assumption }, right, assumption end example : (((p → q) → p) → p) := begin intro h, cases (em p) with hp hnp, { assumption }, have ptoq : p → q, { intro hp, contradiction }, exact h ptoq end end chap3ex2 section chap3ex3 example { p : Prop } : ¬(p ↔ ¬p) := begin intro h, have nptop : ¬p → p, from iff.elim_right h, have ptonp : p → ¬p, from iff.elim_left h, have np : ¬p, { intro hp, exact absurd hp (ptonp hp) }, exact absurd (nptop np) np end end chap3ex3 section chap4ex1 variables (α : Type) (p q : α → Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := begin apply iff.intro, { intro h, constructor, repeat { intro ha, let h1 := h ha, exact h1.left <|> exact h1.right }}, intros h ha, constructor, { exact h.left ha }, exact h.right ha end example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := begin intros h1 h2 hx, exact (h1 hx $ h2 hx) end example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := begin intros h1 hx, cases h1 with hpx hqx, { left, exact hpx hx }, right, exact hqx hx end end chap4ex1 section chap4ex2 variables (α : Type) (p q : α → Prop) variable r : Prop example : α → ((∀ x : α, r) ↔ r) := begin intro ha, apply iff.intro, { intro hr, exact hr ha }, intros hr hx, assumption end -- one branch requires classical logic example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := begin apply iff.intro, { intros h, cases (classical.em r) with hr hnr, { right, assumption }, left, intro hx, cases (h hx), assumption, contradiction }, intros h hx, cases h with hpx hr, { left, exact hpx hx }, right, exact hr end example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := begin apply iff.intro, { intros h hr hx, exact h hx hr }, intros h hx hr, exact (h hr) hx end end chap4ex2 section chap4ex3 variables (men : Type) (barber : men) variable (shaves : men → men → Prop) example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := begin have barber_case : shaves barber barber ↔ ¬ shaves barber barber, from h barber, have barber_doesnt_shave_himself: ¬(shaves barber barber), begin intro h1, have : ¬ shaves barber barber, from (iff.elim_left barber_case) h1, contradiction end, have does_he_though : shaves barber barber, from (iff.elim_right barber_case) barber_doesnt_shave_himself, contradiction end end chap4ex3 -- chap4ex4 doesn't involve any proof section chap4ex5 open classical variables (α : Type) (p q : α → Prop) variable a : α variable r : Prop include a example : (∃ x : α, r) → r := begin intro h, cases h, assumption end example : r → (∃ x : α, r) := begin intro h, constructor, exact a, exact h end example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := begin apply iff.intro, { intro h, cases h with ha hconj, constructor, { existsi ha, exact hconj.left }, exact hconj.right }, intro h, have ex : ∃ x, p x, from h.left, cases ex with hx hpx, existsi hx, constructor, { exact hpx }, exact h.right, end example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := begin apply iff.intro, { intro h, cases h with hx hdisj, cases hdisj with hpx hqx, { left, existsi hx, exact hpx }, right, existsi hx, exact hqx }, intro h, cases h with hpx hqx, { cases hpx with hx hpx', existsi hx, left, exact hpx' }, cases hqx with hx hqx', existsi hx, right, exact hqx' end def forall_px_not_exists_not_px : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := begin apply iff.intro, { intros h hcon, cases hcon with hx hnpx, have hpx : p hx, from h hx, contradiction }, intros h hx, cases (classical.em (p hx)) with _ hnpx, { show p hx, by assumption }, show p hx, have : ∃ x, ¬p x, { existsi hx, exact hnpx }, contradiction end example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := @forall_px_not_exists_not_px α p a def exists_p_x_not_forall_not_px : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := begin apply iff.intro, { intros h hcon, cases h with hx hpx, have hnpx : ¬ p hx, { exact hcon hx }, contradiction }, show ¬(∀ x, ¬p x) → (∃ x, p x), intro h, cases (classical.em (∃ x, p x)) with _ hnex, { assumption }, have hcont : ∀x, ¬p x, { intros hx hpx, have hex : ∃ x, p x, { existsi hx, exact hpx }, contradiction }, contradiction end example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := @exists_p_x_not_forall_not_px α p a example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := begin apply iff.intro, { intros h hx, cases (em (p hx)) with hpx hnpx, { have : ∃ x, p x, from ⟨hx, hpx⟩, contradiction }, assumption }, intros h hcont, cases hcont with hx hpx, have nphx : ¬ p hx, from h hx, contradiction end def not_forall_exists_not_equivalence : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := begin apply iff.intro, { intro h, cases (em (p a)) with hpa hnpa, { cases (em ∃ x, ¬ p x) with hexists hnexists, { assumption }, have : ∀ x, p x, from iff.elim_right (@forall_px_not_exists_not_px α p a) hnexists, contradiction }, existsi a, exact hnpa }, intros h hcont, cases h with hx hnpx, have hpx : p hx, from hcont hx, contradiction end example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := @not_forall_exists_not_equivalence α p a example : (∀ x, p x → r) ↔ (∃ x, p x) → r := begin apply iff.intro, { intros h hex, cases hex with hx hpx, exact h hx hpx}, intros h hx hphx, have : ∃ x, p x, from ⟨hx, hphx⟩, exact h this end example : (∃ x, p x → r) ↔ (∀ x, p x) → r := begin apply iff.intro, { intros hex hfa, cases hex with hx hphx, have hhx : p hx, from hfa hx, exact hphx hhx }, intros h, cases (em (∀ (x : α), p x)) with hyes hno, { existsi a, intro hpa, exact h hyes }, have : (∃ x, ¬ p x), from iff.elim_left (@not_forall_exists_not_equivalence α p a) hno, cases this with hx hnpx, existsi hx, intro hpx, contradiction end example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := begin apply iff.intro, { intros hex hr, cases hex with hx hrtopx, existsi hx, exact hrtopx hr }, intro h, cases (em r) with hr hnr, { have : (∃ (x : α), p x), from h hr, cases this with hx hpx, existsi hx, intro hr, exact hpx }, existsi a, intro hr, contradiction end end chap4ex5 section chap4ex6 variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw [exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq h theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := let x := x, y := y in begin have s1 : log (x * y) = log (x * y), by reflexivity, have s2 : log (x * y) = log (exp (log x) * (exp (log y))), by { rw (exp_log_eq hx), rw (exp_log_eq hy) }, have s3 : log (exp (log x) * (exp (log y))) = log (exp (log x + log y)), by { rw exp_add }, have s4 : log (exp (log x + log y)) = log x + log y, by rw log_exp_eq, show log (x * y) = log x + log y, by rw [s1, s2, s3, s4], end end chap4ex6 section chap4ex7 #check sub_self example (x : ℤ) : x * 0 = 0 := calc x * 0 = 0 * x : by rw [mul_comm] ... = (x - x) * x : by rw sub_self ... = (x * x) - (x * x) : by rw sub_mul ... = 0 : by rw sub_self end chap4ex7 section chap5ex2 example (p q r : Prop) (hp : p) : (p ∨ q ∨ r) ∧ (q ∨ p ∨ r) ∧ (q ∨ r ∨ p) := by repeat { constructor, repeat { { left, exact hp } <|> { right, left, exact hp } <|> { right, right, exact hp } } } end chap5ex2
97703dc37dd6bc67ce9ef5007c855fde2dbaa4a1
4727251e0cd73359b15b664c3170e5d754078599
/src/combinatorics/simple_graph/strongly_regular.lean
524ac8e540e0dbbe95ad806763071c20b46c7036
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,036
lean
/- Copyright (c) 2021 Alena Gusakov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov -/ import combinatorics.simple_graph.basic import data.set.finite /-! # Strongly regular graphs ## Main definitions * `G.is_SRG_with n k ℓ μ` (see `simple_graph.is_SRG_with`) is a structure for a `simple_graph` satisfying the following conditions: * The cardinality of the vertex set is `n` * `G` is a regular graph with degree `k` * The number of common neighbors between any two adjacent vertices in `G` is `ℓ` * The number of common neighbors between any two nonadjacent vertices in `G` is `μ` ## TODO - Prove that the parameters of a strongly regular graph obey the relation `(n - k - 1) * μ = k * (k - ℓ - 1)` - Prove that if `I` is the identity matrix and `J` is the all-one matrix, then the adj matrix `A` of SRG obeys relation `A^2 = kI + ℓA + μ(J - I - A)` -/ open finset universes u namespace simple_graph variables {V : Type u} variables [fintype V] [decidable_eq V] variables (G : simple_graph V) [decidable_rel G.adj] /-- A graph is strongly regular with parameters `n k ℓ μ` if * its vertex set has cardinality `n` * it is regular with degree `k` * every pair of adjacent vertices has `ℓ` common neighbors * every pair of nonadjacent vertices has `μ` common neighbors -/ structure is_SRG_with (n k ℓ μ : ℕ) : Prop := (card : fintype.card V = n) (regular : G.is_regular_of_degree k) (of_adj : ∀ (v w : V), G.adj v w → fintype.card (G.common_neighbors v w) = ℓ) (of_not_adj : ∀ (v w : V), v ≠ w → ¬G.adj v w → fintype.card (G.common_neighbors v w) = μ) variables {G} {n k ℓ μ : ℕ} /-- Empty graphs are strongly regular. Note that `ℓ` can take any value for empty graphs, since there are no pairs of adjacent vertices. -/ lemma bot_strongly_regular : (⊥ : simple_graph V).is_SRG_with (fintype.card V) 0 ℓ 0 := { card := rfl, regular := bot_degree, of_adj := λ v w h, h.elim, of_not_adj := λ v w h, begin simp only [card_eq_zero, filter_congr_decidable, fintype.card_of_finset, forall_true_left, not_false_iff, bot_adj], ext, simp [mem_common_neighbors], end } /-- Complete graphs are strongly regular. Note that `μ` can take any value for complete graphs, since there are no distinct pairs of non-adjacent vertices. -/ lemma is_SRG_with.top : (⊤ : simple_graph V).is_SRG_with (fintype.card V) (fintype.card V - 1) (fintype.card V - 2) μ := { card := rfl, regular := is_regular_of_degree.top, of_adj := λ v w h, begin rw card_common_neighbors_top, exact h, end, of_not_adj := λ v w h h', false.elim $ by simpa using h } lemma is_SRG_with.card_neighbor_finset_union_eq {v w : V} (h : G.is_SRG_with n k ℓ μ) : (G.neighbor_finset v ∪ G.neighbor_finset w).card = 2 * k - fintype.card (G.common_neighbors v w) := begin apply @nat.add_right_cancel _ (fintype.card (G.common_neighbors v w)), rw [nat.sub_add_cancel, ← set.to_finset_card], { simp [neighbor_finset, common_neighbors, set.to_finset_inter, finset.card_union_add_card_inter, h.regular.degree_eq, two_mul], }, { apply le_trans (card_common_neighbors_le_degree_left _ _ _), simp [h.regular.degree_eq, two_mul], }, end /-- Assuming `G` is strongly regular, `2*(k + 1) - m` in `G` is the number of vertices that are adjacent to either `v` or `w` when `¬G.adj v w`. So it's the cardinality of `G.neighbor_set v ∪ G.neighbor_set w`. -/ lemma is_SRG_with.card_neighbor_finset_union_of_not_adj {v w : V} (h : G.is_SRG_with n k ℓ μ) (hne : v ≠ w) (ha : ¬G.adj v w) : (G.neighbor_finset v ∪ G.neighbor_finset w).card = 2 * k - μ := begin rw ← h.of_not_adj v w hne ha, apply h.card_neighbor_finset_union_eq, end lemma is_SRG_with.card_neighbor_finset_union_of_adj {v w : V} (h : G.is_SRG_with n k ℓ μ) (ha : G.adj v w) : (G.neighbor_finset v ∪ G.neighbor_finset w).card = 2 * k - ℓ := begin rw ← h.of_adj v w ha, apply h.card_neighbor_finset_union_eq, end lemma compl_neighbor_finset_sdiff_inter_eq {v w : V} : (G.neighbor_finset v)ᶜ \ {v} ∩ ((G.neighbor_finset w)ᶜ \ {w}) = (G.neighbor_finset v)ᶜ ∩ (G.neighbor_finset w)ᶜ \ ({w} ∪ {v}) := by { ext, rw ← not_iff_not, simp [imp_iff_not_or, or_assoc, or_comm, or.left_comm], } lemma sdiff_compl_neighbor_finset_inter_eq {v w : V} (h : G.adj v w) : (G.neighbor_finset v)ᶜ ∩ (G.neighbor_finset w)ᶜ \ ({w} ∪ {v}) = (G.neighbor_finset v)ᶜ ∩ (G.neighbor_finset w)ᶜ := begin ext, simp only [and_imp, mem_union, mem_sdiff, mem_compl, and_iff_left_iff_imp, mem_neighbor_finset, mem_inter, mem_singleton], rintros hnv hnw (rfl|rfl), { exact hnv h, }, { apply hnw, rwa adj_comm, }, end lemma is_SRG_with.compl_is_regular (h : G.is_SRG_with n k ℓ μ) : Gᶜ.is_regular_of_degree (n - k - 1) := begin rw [← h.card, nat.sub_sub, add_comm, ←nat.sub_sub], exact h.regular.compl, end lemma is_SRG_with.card_common_neighbors_eq_of_adj_compl (h : G.is_SRG_with n k ℓ μ) {v w : V} (ha : Gᶜ.adj v w) : fintype.card ↥(Gᶜ.common_neighbors v w) = n - (2 * k - μ) - 2 := begin simp only [←set.to_finset_card, common_neighbors, set.to_finset_inter, neighbor_set_compl, set.to_finset_sdiff, set.to_finset_singleton, set.to_finset_compl, ←neighbor_finset_def], simp_rw compl_neighbor_finset_sdiff_inter_eq, have hne : v ≠ w := ne_of_adj _ ha, rw compl_adj at ha, rw [card_sdiff, ← insert_eq, card_insert_of_not_mem, card_singleton, ← finset.compl_union], { change (1 + 1) with 2, rw [card_compl, h.card_neighbor_finset_union_of_not_adj hne ha.2, ← h.card], }, { simp only [hne.symm, not_false_iff, mem_singleton], }, { intro u, simp only [mem_union, mem_compl, mem_neighbor_finset, mem_inter, mem_singleton], rintro (rfl|rfl); simpa [adj_comm] using ha.2, }, end lemma is_SRG_with.card_common_neighbors_eq_of_not_adj_compl (h : G.is_SRG_with n k ℓ μ) {v w : V} (hn : v ≠ w) (hna : ¬Gᶜ.adj v w) : fintype.card ↥(Gᶜ.common_neighbors v w) = n - (2 * k - ℓ) := begin simp only [←set.to_finset_card, common_neighbors, set.to_finset_inter, neighbor_set_compl, set.to_finset_sdiff, set.to_finset_singleton, set.to_finset_compl, ←neighbor_finset_def], simp only [not_and, not_not, compl_adj] at hna, have h2' := hna hn, simp_rw [compl_neighbor_finset_sdiff_inter_eq, sdiff_compl_neighbor_finset_inter_eq h2'], rwa [← finset.compl_union, card_compl, h.card_neighbor_finset_union_of_adj, ← h.card], end /-- The complement of a strongly regular graph is strongly regular. -/ lemma is_SRG_with.compl (h : G.is_SRG_with n k ℓ μ) : Gᶜ.is_SRG_with n (n - k - 1) (n - (2 * k - μ) - 2) (n - (2 * k - ℓ)) := { card := h.card, regular := h.compl_is_regular, of_adj := λ v w ha, h.card_common_neighbors_eq_of_adj_compl ha, of_not_adj := λ v w hn hna, h.card_common_neighbors_eq_of_not_adj_compl hn hna, } end simple_graph
03504bb7d47855b721fcc0e5787648c4fe7464be
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/probability/martingale/basic.lean
222656ee7ace411e135c5a67b9028d34d1191a6c
[ "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
24,864
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Kexing Ying -/ import probability.notation import probability.process.stopping /-! # Martingales A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if every `f i` is integrable, `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] =ᵐ[μ] f i`. On the other hand, `f : ι → Ω → E` is said to be a supermartingale with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with resepct to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] ≤ᵐ[μ] f i`. Finally, `f : ι → Ω → E` is said to be a submartingale with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with resepct to `ℱ` and for all `i ≤ j`, `f i ≤ᵐ[μ] μ[f j | ℱ i]`. The definitions of filtration and adapted can be found in `probability.stopping`. ### Definitions * `measure_theory.martingale f ℱ μ`: `f` is a martingale with respect to filtration `ℱ` and measure `μ`. * `measure_theory.supermartingale f ℱ μ`: `f` is a supermartingale with respect to filtration `ℱ` and measure `μ`. * `measure_theory.submartingale f ℱ μ`: `f` is a submartingale with respect to filtration `ℱ` and measure `μ`. ### Results * `measure_theory.martingale_condexp f ℱ μ`: the sequence `λ i, μ[f | ℱ i, ℱ.le i])` is a martingale with respect to `ℱ` and `μ`. -/ open topological_space filter open_locale nnreal ennreal measure_theory probability_theory big_operators namespace measure_theory variables {Ω E ι : Type*} [preorder ι] {m0 : measurable_space Ω} {μ : measure Ω} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f g : ι → Ω → E} {ℱ : filtration ι m0} /-- A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] =ᵐ[μ] f i`. -/ def martingale (f : ι → Ω → E) (ℱ : filtration ι m0) (μ : measure Ω . volume_tac) : Prop := adapted ℱ f ∧ ∀ i j, i ≤ j → μ[f j | ℱ i] =ᵐ[μ] f i /-- A family of integrable functions `f : ι → Ω → E` is a supermartingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ.le i] ≤ᵐ[μ] f i`. -/ def supermartingale [has_le E] (f : ι → Ω → E) (ℱ : filtration ι m0) (μ : measure Ω . volume_tac) : Prop := adapted ℱ f ∧ (∀ i j, i ≤ j → μ[f j | ℱ i] ≤ᵐ[μ] f i) ∧ ∀ i, integrable (f i) μ /-- A family of integrable functions `f : ι → Ω → E` is a submartingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `f i ≤ᵐ[μ] μ[f j | ℱ.le i]`. -/ def submartingale [has_le E] (f : ι → Ω → E) (ℱ : filtration ι m0) (μ : measure Ω . volume_tac) : Prop := adapted ℱ f ∧ (∀ i j, i ≤ j → f i ≤ᵐ[μ] μ[f j | ℱ i]) ∧ ∀ i, integrable (f i) μ lemma martingale_const (ℱ : filtration ι m0) (μ : measure Ω) [is_finite_measure μ] (x : E) : martingale (λ _ _, x) ℱ μ := ⟨adapted_const ℱ _, λ i j hij, by rw condexp_const (ℱ.le _)⟩ lemma martingale_const_fun [order_bot ι] (ℱ : filtration ι m0) (μ : measure Ω) [is_finite_measure μ] {f : Ω → E} (hf : strongly_measurable[ℱ ⊥] f) (hfint : integrable f μ) : martingale (λ _, f) ℱ μ := begin refine ⟨λ i, hf.mono $ ℱ.mono bot_le, λ i j hij, _⟩, rw condexp_of_strongly_measurable (ℱ.le _) (hf.mono $ ℱ.mono bot_le) hfint, apply_instance, end variables (E) lemma martingale_zero (ℱ : filtration ι m0) (μ : measure Ω) : martingale (0 : ι → Ω → E) ℱ μ := ⟨adapted_zero E ℱ, λ i j hij, by { rw [pi.zero_apply, condexp_zero], simp, }⟩ variables {E} namespace martingale @[protected] lemma adapted (hf : martingale f ℱ μ) : adapted ℱ f := hf.1 @[protected] lemma strongly_measurable (hf : martingale f ℱ μ) (i : ι) : strongly_measurable[ℱ i] (f i) := hf.adapted i lemma condexp_ae_eq (hf : martingale f ℱ μ) {i j : ι} (hij : i ≤ j) : μ[f j | ℱ i] =ᵐ[μ] f i := hf.2 i j hij @[protected] lemma integrable (hf : martingale f ℱ μ) (i : ι) : integrable (f i) μ := integrable_condexp.congr (hf.condexp_ae_eq (le_refl i)) lemma set_integral_eq [sigma_finite_filtration μ ℱ] (hf : martingale f ℱ μ) {i j : ι} (hij : i ≤ j) {s : set Ω} (hs : measurable_set[ℱ i] s) : ∫ ω in s, f i ω ∂μ = ∫ ω in s, f j ω ∂μ := begin rw ← @set_integral_condexp _ _ _ _ _ (ℱ i) m0 _ _ _ (ℱ.le i) _ (hf.integrable j) hs, refine set_integral_congr_ae (ℱ.le i s hs) _, filter_upwards [hf.2 i j hij] with _ heq _ using heq.symm, end lemma add (hf : martingale f ℱ μ) (hg : martingale g ℱ μ) : martingale (f + g) ℱ μ := begin refine ⟨hf.adapted.add hg.adapted, λ i j hij, _⟩, exact (condexp_add (hf.integrable j) (hg.integrable j)).trans ((hf.2 i j hij).add (hg.2 i j hij)), end lemma neg (hf : martingale f ℱ μ) : martingale (-f) ℱ μ := ⟨hf.adapted.neg, λ i j hij, (condexp_neg (f j)).trans ((hf.2 i j hij).neg)⟩ lemma sub (hf : martingale f ℱ μ) (hg : martingale g ℱ μ) : martingale (f - g) ℱ μ := by { rw sub_eq_add_neg, exact hf.add hg.neg, } lemma smul (c : ℝ) (hf : martingale f ℱ μ) : martingale (c • f) ℱ μ := begin refine ⟨hf.adapted.smul c, λ i j hij, _⟩, refine (condexp_smul c (f j)).trans ((hf.2 i j hij).mono (λ x hx, _)), rw [pi.smul_apply, hx, pi.smul_apply, pi.smul_apply], end lemma supermartingale [preorder E] (hf : martingale f ℱ μ) : supermartingale f ℱ μ := ⟨hf.1, λ i j hij, (hf.2 i j hij).le, λ i, hf.integrable i⟩ lemma submartingale [preorder E] (hf : martingale f ℱ μ) : submartingale f ℱ μ := ⟨hf.1, λ i j hij, (hf.2 i j hij).symm.le, λ i, hf.integrable i⟩ end martingale lemma martingale_iff [partial_order E] : martingale f ℱ μ ↔ supermartingale f ℱ μ ∧ submartingale f ℱ μ := ⟨λ hf, ⟨hf.supermartingale, hf.submartingale⟩, λ ⟨hf₁, hf₂⟩, ⟨hf₁.1, λ i j hij, (hf₁.2.1 i j hij).antisymm (hf₂.2.1 i j hij)⟩⟩ lemma martingale_condexp (f : Ω → E) (ℱ : filtration ι m0) (μ : measure Ω) [sigma_finite_filtration μ ℱ] : martingale (λ i, μ[f | ℱ i]) ℱ μ := ⟨λ i, strongly_measurable_condexp, λ i j hij, condexp_condexp_of_le (ℱ.mono hij) (ℱ.le j)⟩ namespace supermartingale @[protected] lemma adapted [has_le E] (hf : supermartingale f ℱ μ) : adapted ℱ f := hf.1 @[protected] lemma strongly_measurable [has_le E] (hf : supermartingale f ℱ μ) (i : ι) : strongly_measurable[ℱ i] (f i) := hf.adapted i @[protected] lemma integrable [has_le E] (hf : supermartingale f ℱ μ) (i : ι) : integrable (f i) μ := hf.2.2 i lemma condexp_ae_le [has_le E] (hf : supermartingale f ℱ μ) {i j : ι} (hij : i ≤ j) : μ[f j | ℱ i] ≤ᵐ[μ] f i := hf.2.1 i j hij lemma set_integral_le [sigma_finite_filtration μ ℱ] {f : ι → Ω → ℝ} (hf : supermartingale f ℱ μ) {i j : ι} (hij : i ≤ j) {s : set Ω} (hs : measurable_set[ℱ i] s) : ∫ ω in s, f j ω ∂μ ≤ ∫ ω in s, f i ω ∂μ := begin rw ← set_integral_condexp (ℱ.le i) (hf.integrable j) hs, refine set_integral_mono_ae integrable_condexp.integrable_on (hf.integrable i).integrable_on _, filter_upwards [hf.2.1 i j hij] with _ heq using heq, end lemma add [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : supermartingale g ℱ μ) : supermartingale (f + g) ℱ μ := begin refine ⟨hf.1.add hg.1, λ i j hij, _, λ i, (hf.2.2 i).add (hg.2.2 i)⟩, refine (condexp_add (hf.integrable j) (hg.integrable j)).le.trans _, filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij], intros, refine add_le_add _ _; assumption, end lemma add_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : martingale g ℱ μ) : supermartingale (f + g) ℱ μ := hf.add hg.supermartingale lemma neg [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) : submartingale (-f) ℱ μ := begin refine ⟨hf.1.neg, λ i j hij, _, λ i, (hf.2.2 i).neg⟩, refine eventually_le.trans _ (condexp_neg (f j)).symm.le, filter_upwards [hf.2.1 i j hij] with _ _, simpa, end end supermartingale namespace submartingale @[protected] lemma adapted [has_le E] (hf : submartingale f ℱ μ) : adapted ℱ f := hf.1 @[protected] lemma strongly_measurable [has_le E] (hf : submartingale f ℱ μ) (i : ι) : strongly_measurable[ℱ i] (f i) := hf.adapted i @[protected] lemma integrable [has_le E] (hf : submartingale f ℱ μ) (i : ι) : integrable (f i) μ := hf.2.2 i lemma ae_le_condexp [has_le E] (hf : submartingale f ℱ μ) {i j : ι} (hij : i ≤ j) : f i ≤ᵐ[μ] μ[f j | ℱ i] := hf.2.1 i j hij lemma add [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : submartingale g ℱ μ) : submartingale (f + g) ℱ μ := begin refine ⟨hf.1.add hg.1, λ i j hij, _, λ i, (hf.2.2 i).add (hg.2.2 i)⟩, refine eventually_le.trans _ (condexp_add (hf.integrable j) (hg.integrable j)).symm.le, filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij], intros, refine add_le_add _ _; assumption, end lemma add_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : martingale g ℱ μ) : submartingale (f + g) ℱ μ := hf.add hg.submartingale lemma neg [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) : supermartingale (-f) ℱ μ := begin refine ⟨hf.1.neg, λ i j hij, (condexp_neg (f j)).le.trans _, λ i, (hf.2.2 i).neg⟩, filter_upwards [hf.2.1 i j hij] with _ _, simpa, end /-- The converse of this lemma is `measure_theory.submartingale_of_set_integral_le`. -/ lemma set_integral_le [sigma_finite_filtration μ ℱ] {f : ι → Ω → ℝ} (hf : submartingale f ℱ μ) {i j : ι} (hij : i ≤ j) {s : set Ω} (hs : measurable_set[ℱ i] s) : ∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f j ω ∂μ := begin rw [← neg_le_neg_iff, ← integral_neg, ← integral_neg], exact supermartingale.set_integral_le hf.neg hij hs, end lemma sub_supermartingale [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : supermartingale g ℱ μ) : submartingale (f - g) ℱ μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } lemma sub_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : martingale g ℱ μ) : submartingale (f - g) ℱ μ := hf.sub_supermartingale hg.supermartingale protected lemma sup {f g : ι → Ω → ℝ} (hf : submartingale f ℱ μ) (hg : submartingale g ℱ μ) : submartingale (f ⊔ g) ℱ μ := begin refine ⟨λ i, @strongly_measurable.sup _ _ _ _ (ℱ i) _ _ _ (hf.adapted i) (hg.adapted i), λ i j hij, _, λ i, integrable.sup (hf.integrable _) (hg.integrable _)⟩, refine eventually_le.sup_le _ _, { exact eventually_le.trans (hf.2.1 i j hij) (condexp_mono (hf.integrable _) (integrable.sup (hf.integrable j) (hg.integrable j)) (eventually_of_forall (λ x, le_max_left _ _))) }, { exact eventually_le.trans (hg.2.1 i j hij) (condexp_mono (hg.integrable _) (integrable.sup (hf.integrable j) (hg.integrable j)) (eventually_of_forall (λ x, le_max_right _ _))) } end protected lemma pos {f : ι → Ω → ℝ} (hf : submartingale f ℱ μ) : submartingale (f⁺) ℱ μ := hf.sup (martingale_zero _ _ _).submartingale end submartingale section submartingale lemma submartingale_of_set_integral_le [is_finite_measure μ] {f : ι → Ω → ℝ} (hadp : adapted ℱ f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i j : ι, i ≤ j → ∀ s : set Ω, measurable_set[ℱ i] s → ∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f j ω ∂μ) : submartingale f ℱ μ := begin refine ⟨hadp, λ i j hij, _, hint⟩, suffices : f i ≤ᵐ[μ.trim (ℱ.le i)] μ[f j| ℱ i], { exact ae_le_of_ae_le_trim this }, suffices : 0 ≤ᵐ[μ.trim (ℱ.le i)] μ[f j| ℱ i] - f i, { filter_upwards [this] with x hx, rwa ← sub_nonneg }, refine ae_nonneg_of_forall_set_integral_nonneg ((integrable_condexp.sub (hint i)).trim _ (strongly_measurable_condexp.sub $ hadp i)) (λ s hs h's, _), specialize hf i j hij s hs, rwa [← set_integral_trim _ (strongly_measurable_condexp.sub $ hadp i) hs, integral_sub' integrable_condexp.integrable_on (hint i).integrable_on, sub_nonneg, set_integral_condexp (ℱ.le i) (hint j) hs], end lemma submartingale_of_condexp_sub_nonneg [is_finite_measure μ] {f : ι → Ω → ℝ} (hadp : adapted ℱ f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i j, i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i | ℱ i]) : submartingale f ℱ μ := begin refine ⟨hadp, λ i j hij, _, hint⟩, rw [← condexp_of_strongly_measurable (ℱ.le _) (hadp _) (hint _), ← eventually_sub_nonneg], exact eventually_le.trans (hf i j hij) (condexp_sub (hint _) (hint _)).le, apply_instance end lemma submartingale.condexp_sub_nonneg {f : ι → Ω → ℝ} (hf : submartingale f ℱ μ) {i j : ι} (hij : i ≤ j) : 0 ≤ᵐ[μ] μ[f j - f i | ℱ i] := begin by_cases h : sigma_finite (μ.trim (ℱ.le i)), swap, { rw condexp_of_not_sigma_finite (ℱ.le i) h }, refine eventually_le.trans _ (condexp_sub (hf.integrable _) (hf.integrable _)).symm.le, rw [eventually_sub_nonneg, condexp_of_strongly_measurable (ℱ.le _) (hf.adapted _) (hf.integrable _)], { exact hf.2.1 i j hij }, { exact h } end lemma submartingale_iff_condexp_sub_nonneg [is_finite_measure μ] {f : ι → Ω → ℝ} : submartingale f ℱ μ ↔ adapted ℱ f ∧ (∀ i, integrable (f i) μ) ∧ ∀ i j, i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i | ℱ i] := ⟨λ h, ⟨h.adapted, h.integrable, λ i j, h.condexp_sub_nonneg⟩, λ ⟨hadp, hint, h⟩, submartingale_of_condexp_sub_nonneg hadp hint h⟩ end submartingale namespace supermartingale lemma sub_submartingale [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : submartingale g ℱ μ) : supermartingale (f - g) ℱ μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } lemma sub_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : martingale g ℱ μ) : supermartingale (f - g) ℱ μ := hf.sub_submartingale hg.submartingale section variables {F : Type*} [normed_lattice_add_comm_group F] [normed_space ℝ F] [complete_space F] [ordered_smul ℝ F] lemma smul_nonneg {f : ι → Ω → F} {c : ℝ} (hc : 0 ≤ c) (hf : supermartingale f ℱ μ) : supermartingale (c • f) ℱ μ := begin refine ⟨hf.1.smul c, λ i j hij, _, λ i, (hf.2.2 i).smul c⟩, refine (condexp_smul c (f j)).le.trans _, filter_upwards [hf.2.1 i j hij] with _ hle, simp, exact smul_le_smul_of_nonneg hle hc, end lemma smul_nonpos {f : ι → Ω → F} {c : ℝ} (hc : c ≤ 0) (hf : supermartingale f ℱ μ) : submartingale (c • f) ℱ μ := begin rw [← neg_neg c, (by { ext i x, simp } : - -c • f = -(-c • f))], exact (hf.smul_nonneg $ neg_nonneg.2 hc).neg, end end end supermartingale namespace submartingale section variables {F : Type*} [normed_lattice_add_comm_group F] [normed_space ℝ F] [complete_space F] [ordered_smul ℝ F] lemma smul_nonneg {f : ι → Ω → F} {c : ℝ} (hc : 0 ≤ c) (hf : submartingale f ℱ μ) : submartingale (c • f) ℱ μ := begin rw [← neg_neg c, (by { ext i x, simp } : - -c • f = -(c • -f))], exact supermartingale.neg (hf.neg.smul_nonneg hc), end lemma smul_nonpos {f : ι → Ω → F} {c : ℝ} (hc : c ≤ 0) (hf : submartingale f ℱ μ) : supermartingale (c • f) ℱ μ := begin rw [← neg_neg c, (by { ext i x, simp } : - -c • f = -(-c • f))], exact (hf.smul_nonneg $ neg_nonneg.2 hc).neg, end end end submartingale section nat variables {𝒢 : filtration ℕ m0} lemma submartingale_of_set_integral_le_succ [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, ∀ s : set Ω, measurable_set[𝒢 i] s → ∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f (i + 1) ω ∂μ) : submartingale f 𝒢 μ := begin refine submartingale_of_set_integral_le hadp hint (λ i j hij s hs, _), induction hij with k hk₁ hk₂, { exact le_rfl }, { exact le_trans hk₂ (hf k s (𝒢.mono hk₁ _ hs)) } end lemma supermartingale_of_set_integral_succ_le [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, ∀ s : set Ω, measurable_set[𝒢 i] s → ∫ ω in s, f (i + 1) ω ∂μ ≤ ∫ ω in s, f i ω ∂μ) : supermartingale f 𝒢 μ := begin rw ← neg_neg f, refine (submartingale_of_set_integral_le_succ hadp.neg (λ i, (hint i).neg) _).neg, simpa only [integral_neg, pi.neg_apply, neg_le_neg_iff], end lemma martingale_of_set_integral_eq_succ [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, ∀ s : set Ω, measurable_set[𝒢 i] s → ∫ ω in s, f i ω ∂μ = ∫ ω in s, f (i + 1) ω ∂μ) : martingale f 𝒢 μ := martingale_iff.2 ⟨supermartingale_of_set_integral_succ_le hadp hint $ λ i s hs, (hf i s hs).ge, submartingale_of_set_integral_le_succ hadp hint $ λ i s hs, (hf i s hs).le⟩ lemma submartingale_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, f i ≤ᵐ[μ] μ[f (i + 1) | 𝒢 i]) : submartingale f 𝒢 μ := begin refine submartingale_of_set_integral_le_succ hadp hint (λ i s hs, _), have : ∫ ω in s, f (i + 1) ω ∂μ = ∫ ω in s, μ[f (i + 1)|𝒢 i] ω ∂μ := (set_integral_condexp (𝒢.le i) (hint _) hs).symm, rw this, exact set_integral_mono_ae (hint i).integrable_on integrable_condexp.integrable_on (hf i), end lemma supermartingale_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, μ[f (i + 1) | 𝒢 i] ≤ᵐ[μ] f i) : supermartingale f 𝒢 μ := begin rw ← neg_neg f, refine (submartingale_nat hadp.neg (λ i, (hint i).neg) $ λ i, eventually_le.trans _ (condexp_neg _).symm.le).neg, filter_upwards [hf i] with x hx using neg_le_neg hx, end lemma martingale_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, f i =ᵐ[μ] μ[f (i + 1) | 𝒢 i]) : martingale f 𝒢 μ := martingale_iff.2 ⟨supermartingale_nat hadp hint $ λ i, (hf i).symm.le, submartingale_nat hadp hint $ λ i, (hf i).le⟩ lemma submartingale_of_condexp_sub_nonneg_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, 0 ≤ᵐ[μ] μ[f (i + 1) - f i | 𝒢 i]) : submartingale f 𝒢 μ := begin refine submartingale_nat hadp hint (λ i, _), rw [← condexp_of_strongly_measurable (𝒢.le _) (hadp _) (hint _), ← eventually_sub_nonneg], exact eventually_le.trans (hf i) (condexp_sub (hint _) (hint _)).le, apply_instance end lemma supermartingale_of_condexp_sub_nonneg_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, 0 ≤ᵐ[μ] μ[f i - f (i + 1) | 𝒢 i]) : supermartingale f 𝒢 μ := begin rw ← neg_neg f, refine (submartingale_of_condexp_sub_nonneg_nat hadp.neg (λ i, (hint i).neg) _).neg, simpa only [pi.zero_apply, pi.neg_apply, neg_sub_neg] end lemma martingale_of_condexp_sub_eq_zero_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, μ[f (i + 1) - f i | 𝒢 i] =ᵐ[μ] 0) : martingale f 𝒢 μ := begin refine martingale_iff.2 ⟨supermartingale_of_condexp_sub_nonneg_nat hadp hint $ λ i, _, submartingale_of_condexp_sub_nonneg_nat hadp hint $ λ i, (hf i).symm.le⟩, rw ← neg_sub, refine (eventually_eq.trans _ (condexp_neg _).symm).le, filter_upwards [hf i] with x hx, simpa only [pi.zero_apply, pi.neg_apply, zero_eq_neg], end -- Note that one cannot use `submartingale.zero_le_of_predictable` to prove the other two -- corresponding lemmas without imposing more restrictions to the ordering of `E` /-- A predictable submartingale is a.e. greater equal than its initial state. -/ lemma submartingale.zero_le_of_predictable [preorder E] [sigma_finite_filtration μ 𝒢] {f : ℕ → Ω → E} (hfmgle : submartingale f 𝒢 μ) (hfadp : adapted 𝒢 (λ n, f (n + 1))) (n : ℕ) : f 0 ≤ᵐ[μ] f n := begin induction n with k ih, { refl }, { exact ih.trans ((hfmgle.2.1 k (k + 1) k.le_succ).trans_eq $ germ.coe_eq.mp $ congr_arg coe $ condexp_of_strongly_measurable (𝒢.le _) (hfadp _) $ hfmgle.integrable _) } end /-- A predictable supermartingale is a.e. less equal than its initial state. -/ lemma supermartingale.le_zero_of_predictable [preorder E] [sigma_finite_filtration μ 𝒢] {f : ℕ → Ω → E} (hfmgle : supermartingale f 𝒢 μ) (hfadp : adapted 𝒢 (λ n, f (n + 1))) (n : ℕ) : f n ≤ᵐ[μ] f 0 := begin induction n with k ih, { refl }, { exact ((germ.coe_eq.mp $ congr_arg coe $ condexp_of_strongly_measurable (𝒢.le _) (hfadp _) $ hfmgle.integrable _).symm.trans_le (hfmgle.2.1 k (k + 1) k.le_succ)).trans ih } end /-- A predictable martingale is a.e. equal to its initial state. -/ lemma martingale.eq_zero_of_predictable [sigma_finite_filtration μ 𝒢] {f : ℕ → Ω → E} (hfmgle : martingale f 𝒢 μ) (hfadp : adapted 𝒢 (λ n, f (n + 1))) (n : ℕ) : f n =ᵐ[μ] f 0 := begin induction n with k ih, { refl }, { exact ((germ.coe_eq.mp (congr_arg coe $ condexp_of_strongly_measurable (𝒢.le _) (hfadp _) (hfmgle.integrable _))).symm.trans (hfmgle.2 k (k + 1) k.le_succ)).trans ih } end namespace submartingale @[protected] lemma integrable_stopped_value [has_le E] {f : ℕ → Ω → E} (hf : submartingale f 𝒢 μ) {τ : Ω → ℕ} (hτ : is_stopping_time 𝒢 τ) {N : ℕ} (hbdd : ∀ ω, τ ω ≤ N) : integrable (stopped_value f τ) μ := integrable_stopped_value ℕ hτ hf.integrable hbdd end submartingale lemma submartingale.sum_mul_sub [is_finite_measure μ] {R : ℝ} {ξ f : ℕ → Ω → ℝ} (hf : submartingale f 𝒢 μ) (hξ : adapted 𝒢 ξ) (hbdd : ∀ n ω, ξ n ω ≤ R) (hnonneg : ∀ n ω, 0 ≤ ξ n ω) : submartingale (λ n, ∑ k in finset.range n, ξ k * (f (k + 1) - f k)) 𝒢 μ := begin have hξbdd : ∀ i, ∃ C, ∀ ω, |ξ i ω| ≤ C := λ i, ⟨R, λ ω, (abs_of_nonneg (hnonneg i ω)).trans_le (hbdd i ω)⟩, have hint : ∀ m, integrable (∑ k in finset.range m, ξ k * (f (k + 1) - f k)) μ := λ m, integrable_finset_sum' _ (λ i hi, integrable.bdd_mul ((hf.integrable _).sub (hf.integrable _)) hξ.strongly_measurable.ae_strongly_measurable (hξbdd _)), have hadp : adapted 𝒢 (λ n, ∑ k in finset.range n, ξ k * (f (k + 1) - f k)), { intro m, refine finset.strongly_measurable_sum' _ (λ i hi, _), rw finset.mem_range at hi, exact (hξ.strongly_measurable_le hi.le).mul ((hf.adapted.strongly_measurable_le (nat.succ_le_of_lt hi)).sub (hf.adapted.strongly_measurable_le hi.le)) }, refine submartingale_of_condexp_sub_nonneg_nat hadp hint (λ i, _), simp only [← finset.sum_Ico_eq_sub _ (nat.le_succ _), finset.sum_apply, pi.mul_apply, pi.sub_apply, nat.Ico_succ_singleton, finset.sum_singleton], exact eventually_le.trans (eventually_le.mul_nonneg (eventually_of_forall (hnonneg _)) (hf.condexp_sub_nonneg (nat.le_succ _))) (condexp_strongly_measurable_mul (hξ _) (((hf.integrable _).sub (hf.integrable _)).bdd_mul hξ.strongly_measurable.ae_strongly_measurable (hξbdd _)) ((hf.integrable _).sub (hf.integrable _))).symm.le, end /-- Given a discrete submartingale `f` and a predictable process `ξ` (i.e. `ξ (n + 1)` is adapted) the process defined by `λ n, ∑ k in finset.range n, ξ (k + 1) * (f (k + 1) - f k)` is also a submartingale. -/ lemma submartingale.sum_mul_sub' [is_finite_measure μ] {R : ℝ} {ξ f : ℕ → Ω → ℝ} (hf : submartingale f 𝒢 μ) (hξ : adapted 𝒢 (λ n, ξ (n + 1))) (hbdd : ∀ n ω, ξ n ω ≤ R) (hnonneg : ∀ n ω, 0 ≤ ξ n ω) : submartingale (λ n, ∑ k in finset.range n, ξ (k + 1) * (f (k + 1) - f k)) 𝒢 μ := hf.sum_mul_sub hξ (λ n, hbdd _) (λ n, hnonneg _) end nat end measure_theory
ad086c459c08f08cff69e87a8c6250e05de68837
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/computability/halting.lean
304c5579c0b5f857d9134b8156402a31d1fbbfc2
[ "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
13,447
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import computability.partrec_code /-! # Computability theory and the halting problem A universal partial recursive function, Rice's theorem, and the halting problem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open computable roption theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin rcases code.exists_code.1 hf with ⟨cf, rfl⟩, rcases code.exists_code.1 hg with ⟨cg, rfl⟩, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp [dom_iff_mem, code.evaln_complete] at h, rcases h with ⟨x, k, e⟩ | ⟨x, k, e⟩, { refine ⟨k, x, _⟩, simp [e] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp [e]⟩ }, { exact ⟨y, by simp⟩ } } }, { intros x h, rcases nat.rfind_opt_spec h with ⟨k, e⟩, revert e, simp; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable roption nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode2_iff.1 hf) (bind_decode2_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, simp [k'], have hk : (k (encode a)).dom := (H _).2.2 (by simpa [encodek2] using h), existsi hk, cases (H _).1 _ ⟨hk, rfl⟩ with h h; { simp at h, rcases h with ⟨a', ha', y, hy, e⟩, simp [e.symm, encodek] } }, { intros x h', simp [k'] at h', rcases h' with ⟨n, hn, hx⟩, have := (H _).1 _ hn, simp [mem_decode2, encode_injective.eq_iff] at this, cases this with h h; { rcases h with ⟨a', ha, rfl⟩, simp [encodek] at hx, subst a', simp [ha] } }, end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp end partrec def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /- recursively enumerable predicate -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, roption.assert (p a) (λ _, roption.some ())) theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem computable_iff {p : α → Prop} : computable_pred p ↔ ∃ f : α → bool, computable f ∧ p = λ a, f a := ⟨λ ⟨D, h⟩, by exactI ⟨_, h, funext $ λ a, propext (to_bool_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by apply_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : computable_pred p) : computable_pred (λ a, ¬ p a) := by rcases computable_iff.1 hp with ⟨f, hf, rfl⟩; exact ⟨by apply_instance, (cond hf (const ff) (const tt)).of_eq (λ n, by {dsimp, cases f n; refl})⟩ theorem to_re {p : α → Prop} (hp : computable_pred p) : re_pred p := begin rcases computable_iff.1 hp with ⟨f, hf, rfl⟩, unfold re_pred, refine (partrec.cond hf (partrec.const' (roption.some ())) partrec.none).of_eq (λ n, roption.ext $ λ a, _), cases a, cases f n; simp end theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, rcases fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂ with ⟨c, e⟩, simp at e, by_cases eval c ∈ C, { simp [h] at e, rwa ← e }, { simp at h, simp [h] at e, rw e at h, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by haveI := classical.dec; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.ne_empty_iff_nonempty.1 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by rcases h with rfl | rfl; simp [computable_pred]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. @[nolint decidable_classical] theorem computable_iff_re_compl_re {p : α → Prop} [decidable_pred p] : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := ⟨λ h, ⟨h.to_re, h.not.to_re⟩, λ ⟨h₁, h₂⟩, ⟨‹_›, begin rcases partrec.merge (h₁.map (computable.const tt).to₂) (h₂.map (computable.const ff).to₂) _ with ⟨k, pk, hk⟩, { refine partrec.of_eq pk (λ n, roption.eq_some_iff.2 _), rw hk, simp, apply decidable.em }, { intros a x hx y hy, simp at hx hy, cases hy.1 hx.1 } end⟩⟩ end computable_pred namespace nat open vector roption /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n :: v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.part, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a :: v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, roption.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a :: v))) := by simp [(roption.bind_some_eq_map _ _).symm]; exact hf.bind hg def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v :: g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a :: v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, roption.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, roption.ext $ λ b, begin simp [nat.rfind_opt, -nat.mem_rfind], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr; funext n, simp, cases f (n :: v); simp [nat.succ_ne_zero]; refl }, { have := nat.rfind_spec h, simp at this, cases f (a :: v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp [g]; simp [encodek, roption.map_id']), end, λ f hf, begin rcases exists_code.1 hf with ⟨c, rfl⟩, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
6dfa97e727965870e38397439164d3f0eac8afbf
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/finset/sort.lean
03b9234fbce4ec8db4e161b9b108d280bf8476f5
[ "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
9,827
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.fintype.basic import data.multiset.sort import data.list.nodup_equiv_fin /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {α β : Type*} /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section sort_linear_order variables [linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le _ this } end lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} : (s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) := sorted_zero_eq_min'_aux _ _ _ lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} : s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) := (sorted_zero_eq_min'_aux _ _ _).symm lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.le_pred_of_lt i_lt) }, end lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) := sorted_last_eq_max'_aux _ _ _ lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} : s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) (by simpa using sub_lt (card_pos.mpr h) zero_lt_one) := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h` is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid casting issues in further uses of this function. -/ def order_iso_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃o (s : set α) := order_iso.trans (fin.cast ((length_sort (≤)).trans h).symm) $ (s.sort_sorted_lt.nth_le_iso _).trans $ order_iso.set_congr _ _ $ set.ext $ λ x, mem_sort _ /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to avoid casting issues in further uses of this function. -/ def order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ↪o α := (order_iso_of_fin s h).to_order_embedding.trans (order_embedding.subtype _) @[simp] lemma coe_order_iso_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : ↑(order_iso_of_fin s h i) = order_emb_of_fin s h i := rfl lemma order_iso_of_fin_symm_apply (s : finset α) {k : ℕ} (h : s.card = k) (x : (s : set α)) : ↑((s.order_iso_of_fin h).symm x) = (s.sort (≤)).index_of x := rfl lemma order_emb_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i = (s.sort (≤)).nth_le i (by { rw [length_sort, h], exact i.2 }) := rfl @[simp] lemma order_emb_of_fin_mem (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i ∈ s := (s.order_iso_of_fin h i).2 @[simp] lemma range_order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : set.range (s.order_emb_of_fin h) = s := by simp [order_emb_of_fin, set.range_comp coe (s.order_iso_of_fin h)] /-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/ lemma order_emb_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := by simp only [order_emb_of_fin_apply, subtype.coe_mk, sorted_zero_eq_min'] /-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma order_emb_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) := by simp [order_emb_of_fin_apply, max'_eq_sorted_last, h] /-- `order_emb_of_fin {a} h` sends any argument to `a`. -/ @[simp] lemma order_emb_of_fin_singleton (a : α) (i : fin 1) : order_emb_of_fin {a} (card_singleton a) i = a := by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, order_emb_of_fin_zero _ zero_lt_one, min'_singleton] /-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hfs : ∀ x, f x ∈ s) (hmono : strict_mono f) : f = s.order_emb_of_fin h := begin apply fin.strict_mono_unique hmono (s.order_emb_of_fin h).strict_mono, rw [range_order_emb_of_fin, ← set.image_univ, ← coe_fin_range, ← coe_image, coe_inj], refine eq_of_subset_of_card_le (λ x hx, _) _, { rcases mem_image.1 hx with ⟨x, hx, rfl⟩, exact hfs x }, { rw [h, card_image_of_injective _ hmono.injective, fin_range_card] } end /-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k ↪o α} (hfs : ∀ x, f x ∈ s) : f = s.order_emb_of_fin h := rel_embedding.ext $ function.funext_iff.1 $ order_emb_of_fin_unique h hfs f.strict_mono /-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/ @[simp] lemma order_emb_of_fin_eq_order_emb_of_fin_iff {k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.order_emb_of_fin h i = s.order_emb_of_fin h' j ↔ (i : ℕ) = (j : ℕ) := begin substs k l, exact (s.order_emb_of_fin rfl).eq_iff_eq.trans (fin.ext_iff _ _) end lemma card_le_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ t.card + 1 := begin have h1 : ∀ i : fin (s.card - 1), ↑i + 1 < (s.sort (≤)).length, { intro i, rw [finset.length_sort, ←nat.lt_sub_right_iff_add_lt], exact i.2 }, have h0 : ∀ i : fin (s.card - 1), ↑i < (s.sort (≤)).length := λ i, lt_of_le_of_lt (nat.le_succ i) (h1 i), have p := λ i : fin (s.card - 1), h ((s.sort (≤)).nth_le i (h0 i)) ((s.sort (≤)).nth_le (i + 1) (h1 i)) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h0 i))) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h1 i))) (s.sort_sorted_lt.rel_nth_le_of_lt (h0 i) (h1 i) (nat.lt_succ_self i)), let f : fin (s.card - 1) → (t : set α) := λ i, ⟨classical.some (p i), (exists_prop.mp (classical.some_spec (p i))).1⟩, have hf : ∀ i j : fin (s.card - 1), i < j → f i < f j := λ i j hij, subtype.coe_lt_coe.mp ((exists_prop.mp (classical.some_spec (p i))).2.2.trans (lt_of_le_of_lt ((s.sort_sorted (≤)).rel_nth_le_of_le (h1 i) (h0 j) (nat.succ_le_iff.mpr hij)) (exists_prop.mp (classical.some_spec (p j))).2.1)), have key := fintype.card_le_of_embedding (function.embedding.mk f (λ i j hij, le_antisymm (not_lt.mp (mt (hf j i) (not_lt.mpr (le_of_eq hij)))) (not_lt.mp (mt (hf i j) (not_lt.mpr (ge_of_eq hij)))))), rwa [fintype.card_fin, fintype.card_coe, nat.sub_le_right_iff_le_add] at key, end end sort_linear_order instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ end finset
cf80d3eb0781aca846fa3d9022f5e033306596b9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/concrete_category/elementwise.lean
5f3f03bfc0badb225b5ff248dc624c58d3b841f7
[ "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
570
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import tactic.elementwise import category_theory.limits.has_limits import category_theory.limits.shapes.kernels /-! In this file we provide various simp lemmas in its elementwise form via `tactic.elementwise`. -/ open category_theory category_theory.limits attribute [elementwise] cone.w limit.lift_π limit.w cocone.w colimit.ι_desc colimit.w kernel.lift_ι cokernel.π_desc kernel.condition cokernel.condition
d17be29107be2100f2d094c24919f8cb376f7e22
82e44445c70db0f03e30d7be725775f122d72f3e
/src/combinatorics/simple_graph/adj_matrix.lean
bcc2905beeeeb962367194cd9127ea6ec0e22dfd
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
3,165
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import combinatorics.simple_graph.basic import data.rel import linear_algebra.matrix.trace /-! # Adjacency Matrices This module defines the adjacency matrix of a graph, and provides theorems connecting graph properties to computational properties of the matrix. ## Main definitions * `adj_matrix` is the adjacency matrix of a `simple_graph` with coefficients in a given semiring. -/ open_locale big_operators matrix open finset matrix simple_graph universes u v variables {α : Type u} [fintype α] variables (R : Type v) [semiring R] namespace simple_graph variables (G : simple_graph α) (R) [decidable_rel G.adj] /-- `adj_matrix G R` is the matrix `A` such that `A i j = (1 : R)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adj_matrix : matrix α α R | i j := if (G.adj i j) then 1 else 0 variable {R} @[simp] lemma adj_matrix_apply (v w : α) : G.adj_matrix R v w = if (G.adj v w) then 1 else 0 := rfl @[simp] theorem transpose_adj_matrix : (G.adj_matrix R)ᵀ = G.adj_matrix R := by { ext, simp [adj_comm] } @[simp] lemma adj_matrix_dot_product (v : α) (vec : α → R) : dot_product (G.adj_matrix R v) vec = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter] @[simp] lemma dot_product_adj_matrix (v : α) (vec : α → R) : dot_product vec (G.adj_matrix R v) = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter, finset.sum_apply] @[simp] lemma adj_matrix_mul_vec_apply (v : α) (vec : α → R) : ((G.adj_matrix R).mul_vec vec) v = ∑ u in G.neighbor_finset v, vec u := by rw [mul_vec, adj_matrix_dot_product] @[simp] lemma adj_matrix_vec_mul_apply (v : α) (vec : α → R) : ((G.adj_matrix R).vec_mul vec) v = ∑ u in G.neighbor_finset v, vec u := begin rw [← dot_product_adj_matrix, vec_mul], refine congr rfl _, ext, rw [← transpose_apply (adj_matrix R G) x v, transpose_adj_matrix], end @[simp] lemma adj_matrix_mul_apply (M : matrix α α R) (v w : α) : (G.adj_matrix R ⬝ M) v w = ∑ u in G.neighbor_finset v, M u w := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter] @[simp] lemma mul_adj_matrix_apply (M : matrix α α R) (v w : α) : (M ⬝ G.adj_matrix R) v w = ∑ u in G.neighbor_finset w, M v u := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter, adj_comm] variable (R) theorem trace_adj_matrix : matrix.trace α R R (G.adj_matrix R) = 0 := by simp variable {R} theorem adj_matrix_mul_self_apply_self (i : α) : ((G.adj_matrix R) ⬝ (G.adj_matrix R)) i i = degree G i := by simp [degree] variable {G} @[simp] lemma adj_matrix_mul_vec_const_apply {r : R} {v : α} : (G.adj_matrix R).mul_vec (function.const _ r) v = G.degree v * r := by simp [degree] lemma adj_matrix_mul_vec_const_apply_of_regular {d : ℕ} {r : R} (hd : G.is_regular_of_degree d) {v : α} : (G.adj_matrix R).mul_vec (function.const _ r) v = (d * r) := by simp [hd v] end simple_graph
080680c5fc35921bb3f909ff9baf95f7db2aaecc
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/category/Cat.lean
f7048648a0db2b56795c9d12b765d8af6b4802a6
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,370
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 category_theory.concrete_category /-! # Category of categories This file contains definition of category `Cat` of all categories. In this category objects are categories and morphisms are functors between these categories. ## Implementation notes Though `Cat` is not a concrete category, we use `bundled` to define its carrier type. -/ universes v u namespace category_theory /-- Category of categories. -/ def Cat := bundled category.{v u} namespace Cat instance str (C : Cat.{v u}) : category.{v u} C.α := C.str /-- Construct a bundled `Cat` from the underlying type and the typeclass. -/ def of (C : Type u) [category.{v} C] : Cat.{v u} := bundled.of C /-- Category structure on `Cat` -/ instance category : large_category.{max v u} Cat.{v u} := { hom := λ C D, C.α ⥤ D.α, id := λ C, 𝟭 C.α, comp := λ C D E F G, F ⋙ G, id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- Functor that gets the set of objects of a category. It is not called `forget`, because it is not a faithful functor. -/ def objects : Cat.{v u} ⥤ Type u := { obj := bundled.α, map := λ C D F, F.obj } end Cat end category_theory
0d497b7d2d6e3a514103ad063061c0cf081db3c7
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/let3.lean
a6d7d62decc8b30b533b702169c3beafa5425de6
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
182
lean
import Int. variable magic : forall (H : Bool), H set_option pp::notation false set_option pp::coercion true print let a : Int := 1, H : a > 0 := magic (a > 0) in H
066845b1216e6f0b63bc4b1dbc37567c62088adf
87fd6b43d22688237c02b87c30d2a524f53bab24
/src/game/sup_inf/infSumConst.lean
a1301f47f59ce13fb83b7aeb937b0f423bdda846
[ "Apache-2.0" ]
permissive
grthomson/real-number-game
66142fedf0987db90f66daed52f9c8b42b70f909
8ddc15fdddc241c246653f7bb341df36e4e880a8
refs/heads/master
1,668,059,330,605
1,592,873,454,000
1,592,873,454,000
262,025,764
0
0
null
1,588,849,107,000
1,588,849,106,000
null
UTF-8
Lean
false
false
686
lean
import game.sup_inf.infSumSets namespace xena -- hide /- # Chapter 3 : Sup and Inf ## Level 7 Another level that showcases the infimum. -/ def sum_set_const (A : set ℝ) (c : ℝ) := { x : ℝ | ∃ y ∈ A, x = y + c} /- Lemma If $A$ is a set of reals, then $$ \textrm{inf} (c + A) = c + \textrm{inf} (A)$$ -/ lemma inf_sum_set_const (A : set ℝ) (h1A : A.nonempty) (h2A : bdd_below A) (a : ℝ) (c : ℝ): (is_glb A a) → is_glb (sum_set_const A c) (c + a) := begin intro h, cases h with hA hB, split, -- prove that (c+a) is a lower bound intros x h0, cases h0 with y h1, cases h1 with yA h2, sorry, sorry, --needs being worked out end end xena -- hide
9c33296e62a7cfac1e1336c8b8da24b08fb0069f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/category/Module/monoidal.lean
dea21e486a38a5832092e62151250b78bca2620c
[ "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
12,191
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Scott Morrison, Jakob von Raumer -/ import category_theory.monoidal.braided import category_theory.closed.monoidal import algebra.category.Module.basic import linear_algebra.tensor_product import category_theory.linear.yoneda import category_theory.monoidal.linear /-! # The symmetric monoidal category structure on R-modules Mostly this uses existing machinery in `linear_algebra.tensor_product`. We just need to provide a few small missing pieces to build the `monoidal_category` instance and then the `symmetric_category` instance. Note the universe level of the modules must be at least the universe level of the ring, so that we have a monoidal unit. For now, we simplify by insisting both universe levels are the same. We then construct the monoidal closed structure on `Module R`. If you're happy using the bundled `Module R`, it may be possible to mostly use this as an interface and not need to interact much with the implementation details. -/ universes v w x u open category_theory namespace Module variables {R : Type u} [comm_ring R] namespace monoidal_category -- The definitions inside this namespace are essentially private. -- After we build the `monoidal_category (Module R)` instance, -- you should use that API. open_locale tensor_product local attribute [ext] tensor_product.ext /-- (implementation) tensor product of R-modules -/ def tensor_obj (M N : Module R) : Module R := Module.of R (M ⊗[R] N) /-- (implementation) tensor product of morphisms R-modules -/ def tensor_hom {M N M' N' : Module R} (f : M ⟶ N) (g : M' ⟶ N') : tensor_obj M M' ⟶ tensor_obj N N' := tensor_product.map f g lemma tensor_id (M N : Module R) : tensor_hom (𝟙 M) (𝟙 N) = 𝟙 (Module.of R (M ⊗ N)) := by { ext1, refl } lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom f₁ f₂ ≫ tensor_hom g₁ g₂ := by { ext1, refl } /-- (implementation) the associator for R-modules -/ def associator (M : Module.{v} R) (N : Module.{w} R) (K : Module.{x} R) : tensor_obj (tensor_obj M N) K ≅ tensor_obj M (tensor_obj N K) := (tensor_product.assoc R M N K).to_Module_iso section /-! The `associator_naturality` and `pentagon` lemmas below are very slow to elaborate. We give them some help by expressing the lemmas first non-categorically, then using `convert _aux using 1` to have the elaborator work as little as possible. -/ open tensor_product (assoc map) private lemma associator_naturality_aux {X₁ X₂ X₃ : Type*} [add_comm_monoid X₁] [add_comm_monoid X₂] [add_comm_monoid X₃] [module R X₁] [module R X₂] [module R X₃] {Y₁ Y₂ Y₃ : Type*} [add_comm_monoid Y₁] [add_comm_monoid Y₂] [add_comm_monoid Y₃] [module R Y₁] [module R Y₂] [module R Y₃] (f₁ : X₁ →ₗ[R] Y₁) (f₂ : X₂ →ₗ[R] Y₂) (f₃ : X₃ →ₗ[R] Y₃) : (↑(assoc R Y₁ Y₂ Y₃) ∘ₗ (map (map f₁ f₂) f₃)) = ((map f₁ (map f₂ f₃)) ∘ₗ ↑(assoc R X₁ X₂ X₃)) := begin apply tensor_product.ext_threefold, intros x y z, refl end variables (R) private lemma pentagon_aux (W X Y Z : Type*) [add_comm_monoid W] [add_comm_monoid X] [add_comm_monoid Y] [add_comm_monoid Z] [module R W] [module R X] [module R Y] [module R Z] : ((map (1 : W →ₗ[R] W) (assoc R X Y Z).to_linear_map).comp (assoc R W (X ⊗[R] Y) Z).to_linear_map) .comp (map ↑(assoc R W X Y) (1 : Z →ₗ[R] Z)) = (assoc R W X (Y ⊗[R] Z)).to_linear_map.comp (assoc R (W ⊗[R] X) Y Z).to_linear_map := begin apply tensor_product.ext_fourfold, intros w x y z, refl end end lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom (tensor_hom f₁ f₂) f₃ ≫ (associator Y₁ Y₂ Y₃).hom = (associator X₁ X₂ X₃).hom ≫ tensor_hom f₁ (tensor_hom f₂ f₃) := by convert associator_naturality_aux f₁ f₂ f₃ using 1 lemma pentagon (W X Y Z : Module R) : tensor_hom (associator W X Y).hom (𝟙 Z) ≫ (associator W (tensor_obj X Y) Z).hom ≫ tensor_hom (𝟙 W) (associator X Y Z).hom = (associator (tensor_obj W X) Y Z).hom ≫ (associator W X (tensor_obj Y Z)).hom := by convert pentagon_aux R W X Y Z using 1 /-- (implementation) the left unitor for R-modules -/ def left_unitor (M : Module.{u} R) : Module.of R (R ⊗[R] M) ≅ M := (linear_equiv.to_Module_iso (tensor_product.lid R M) : of R (R ⊗ M) ≅ of R M).trans (of_self_iso M) lemma left_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom (𝟙 (Module.of R R)) f ≫ (left_unitor N).hom = (left_unitor M).hom ≫ f := begin ext x y, dsimp, erw [tensor_product.lid_tmul, tensor_product.lid_tmul], rw linear_map.map_smul, refl, end /-- (implementation) the right unitor for R-modules -/ def right_unitor (M : Module.{u} R) : Module.of R (M ⊗[R] R) ≅ M := (linear_equiv.to_Module_iso (tensor_product.rid R M) : of R (M ⊗ R) ≅ of R M).trans (of_self_iso M) lemma right_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom f (𝟙 (Module.of R R)) ≫ (right_unitor N).hom = (right_unitor M).hom ≫ f := begin ext x y, dsimp, erw [tensor_product.rid_tmul, tensor_product.rid_tmul], rw linear_map.map_smul, refl, end lemma triangle (M N : Module.{u} R) : (associator M (Module.of R R) N).hom ≫ tensor_hom (𝟙 M) (left_unitor N).hom = tensor_hom (right_unitor M).hom (𝟙 N) := begin apply tensor_product.ext_threefold, intros x y z, change R at y, dsimp [tensor_hom, associator], erw [tensor_product.lid_tmul, tensor_product.rid_tmul], exact (tensor_product.smul_tmul _ _ _).symm end end monoidal_category open monoidal_category instance monoidal_category : monoidal_category (Module.{u} R) := { -- data tensor_obj := tensor_obj, tensor_hom := @tensor_hom _ _, tensor_unit := Module.of R R, associator := associator, left_unitor := left_unitor, right_unitor := right_unitor, -- properties tensor_id' := λ M N, tensor_id M N, tensor_comp' := λ M N K M' N' K' f g h, tensor_comp f g h, associator_naturality' := λ M N K M' N' K' f g h, associator_naturality f g h, left_unitor_naturality' := λ M N f, left_unitor_naturality f, right_unitor_naturality' := λ M N f, right_unitor_naturality f, pentagon' := λ M N K L, pentagon M N K L, triangle' := λ M N, triangle M N, } /-- Remind ourselves that the monoidal unit, being just `R`, is still a commutative ring. -/ instance : comm_ring ((𝟙_ (Module.{u} R) : Module.{u} R) : Type u) := (by apply_instance : comm_ring R) namespace monoidal_category @[simp] lemma hom_apply {K L M N : Module.{u} R} (f : K ⟶ L) (g : M ⟶ N) (k : K) (m : M) : (f ⊗ g) (k ⊗ₜ m) = f k ⊗ₜ g m := rfl @[simp] lemma left_unitor_hom_apply {M : Module.{u} R} (r : R) (m : M) : ((λ_ M).hom : 𝟙_ (Module R) ⊗ M ⟶ M) (r ⊗ₜ[R] m) = r • m := tensor_product.lid_tmul m r @[simp] lemma left_unitor_inv_apply {M : Module.{u} R} (m : M) : ((λ_ M).inv : M ⟶ 𝟙_ (Module.{u} R) ⊗ M) m = 1 ⊗ₜ[R] m := tensor_product.lid_symm_apply m @[simp] lemma right_unitor_hom_apply {M : Module.{u} R} (m : M) (r : R) : ((ρ_ M).hom : M ⊗ 𝟙_ (Module R) ⟶ M) (m ⊗ₜ r) = r • m := tensor_product.rid_tmul m r @[simp] lemma right_unitor_inv_apply {M : Module.{u} R} (m : M) : ((ρ_ M).inv : M ⟶ M ⊗ 𝟙_ (Module.{u} R)) m = m ⊗ₜ[R] 1 := tensor_product.rid_symm_apply m @[simp] lemma associator_hom_apply {M N K : Module.{u} R} (m : M) (n : N) (k : K) : ((α_ M N K).hom : (M ⊗ N) ⊗ K ⟶ M ⊗ (N ⊗ K)) ((m ⊗ₜ n) ⊗ₜ k) = (m ⊗ₜ (n ⊗ₜ k)) := rfl @[simp] lemma associator_inv_apply {M N K : Module.{u} R} (m : M) (n : N) (k : K) : ((α_ M N K).inv : M ⊗ (N ⊗ K) ⟶ (M ⊗ N) ⊗ K) (m ⊗ₜ (n ⊗ₜ k)) = ((m ⊗ₜ n) ⊗ₜ k) := rfl end monoidal_category /-- (implementation) the braiding for R-modules -/ def braiding (M N : Module R) : tensor_obj M N ≅ tensor_obj N M := linear_equiv.to_Module_iso (tensor_product.comm R M N) @[simp] lemma braiding_naturality {X₁ X₂ Y₁ Y₂ : Module.{u} R} (f : X₁ ⟶ Y₁) (g : X₂ ⟶ Y₂) : (f ⊗ g) ≫ (Y₁.braiding Y₂).hom = (X₁.braiding X₂).hom ≫ (g ⊗ f) := begin apply tensor_product.ext', intros x y, refl end @[simp] lemma hexagon_forward (X Y Z : Module.{u} R) : (α_ X Y Z).hom ≫ (braiding X _).hom ≫ (α_ Y Z X).hom = ((braiding X Y).hom ⊗ 𝟙 Z) ≫ (α_ Y X Z).hom ≫ (𝟙 Y ⊗ (braiding X Z).hom) := begin apply tensor_product.ext_threefold, intros x y z, refl, end @[simp] lemma hexagon_reverse (X Y Z : Module.{u} R) : (α_ X Y Z).inv ≫ (braiding _ Z).hom ≫ (α_ Z X Y).inv = (𝟙 X ⊗ (Y.braiding Z).hom) ≫ (α_ X Z Y).inv ≫ ((X.braiding Z).hom ⊗ 𝟙 Y) := begin apply (cancel_epi (α_ X Y Z).hom).1, apply tensor_product.ext_threefold, intros x y z, refl, end local attribute [ext] tensor_product.ext /-- The symmetric monoidal structure on `Module R`. -/ instance symmetric_category : symmetric_category (Module.{u} R) := { braiding := braiding, braiding_naturality' := λ X₁ X₂ Y₁ Y₂ f g, braiding_naturality f g, hexagon_forward' := hexagon_forward, hexagon_reverse' := hexagon_reverse, } namespace monoidal_category @[simp] lemma braiding_hom_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).hom : M ⊗ N ⟶ N ⊗ M) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] lemma braiding_inv_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).inv : N ⊗ M ⟶ M ⊗ N) (n ⊗ₜ m) = m ⊗ₜ n := rfl end monoidal_category open opposite instance : monoidal_preadditive (Module.{u} R) := { tensor_zero' := by { intros, ext, simp, }, zero_tensor' := by { intros, ext, simp, }, tensor_add' := by { intros, ext, simp [tensor_product.tmul_add], }, add_tensor' := by { intros, ext, simp [tensor_product.add_tmul], }, } instance : monoidal_linear R (Module.{u} R) := { tensor_smul' := by { intros, ext, simp, }, smul_tensor' := by { intros, ext, simp [tensor_product.smul_tmul], }, } /-- Auxiliary definition for the `monoidal_closed` instance on `Module R`. (This is only a separate definition in order to speed up typechecking. ) -/ @[simps] def monoidal_closed_hom_equiv (M N P : Module.{u} R) : ((monoidal_category.tensor_left M).obj N ⟶ P) ≃ (N ⟶ ((linear_coyoneda R (Module R)).obj (op M)).obj P) := { to_fun := λ f, linear_map.compr₂ (tensor_product.mk R N M) ((β_ N M).hom ≫ f), inv_fun := λ f, (β_ M N).hom ≫ tensor_product.lift f, left_inv := λ f, begin ext m n, simp only [tensor_product.mk_apply, tensor_product.lift.tmul, linear_map.compr₂_apply, function.comp_app, coe_comp, monoidal_category.braiding_hom_apply], end, right_inv := λ f, begin ext m n, simp only [tensor_product.mk_apply, tensor_product.lift.tmul, linear_map.compr₂_apply, symmetric_category.symmetry_assoc], end, } instance : monoidal_closed (Module.{u} R) := { closed' := λ M, { is_adj := { right := (linear_coyoneda R (Module.{u} R)).obj (op M), adj := adjunction.mk_of_hom_equiv { hom_equiv := λ N P, monoidal_closed_hom_equiv M N P, } } } } -- I can't seem to express the function coercion here without writing `@coe_fn`. @[simp] lemma monoidal_closed_curry {M N P : Module.{u} R} (f : M ⊗ N ⟶ P) (x : M) (y : N) : @coe_fn _ _ linear_map.has_coe_to_fun ((monoidal_closed.curry f : N →ₗ[R] (M →ₗ[R] P)) y) x = f (x ⊗ₜ[R] y) := rfl @[simp] lemma monoidal_closed_uncurry {M N P : Module.{u} R} (f : N ⟶ (M ⟶[Module.{u} R] P)) (x : M) (y : N) : monoidal_closed.uncurry f (x ⊗ₜ[R] y) = (@coe_fn _ _ linear_map.has_coe_to_fun (f y)) x := by { simp only [monoidal_closed.uncurry, ihom.adjunction, is_left_adjoint.adj], simp, } end Module
45cc0af609ee65ef48f450b18f1716100f45c46a
26ac254ecb57ffcb886ff709cf018390161a9225
/src/ring_theory/polynomial/basic.lean
4629b96c861acd645d55e77087c24cd201f80440
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
19,810
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Ring-theoretic supplement of data.polynomial. Main result: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. -/ import algebra.char_p import data.mv_polynomial import data.polynomial.ring_division import ring_theory.noetherian noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v w namespace polynomial instance {R : Type u} [comm_semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p := let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩ variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker /-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/ def degree_lt (n : ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl @[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← finsupp.sum_single p, finsupp.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end theorem mem_degree_lt {n : ℕ} {f : polynomial R} : f ∈ degree_lt R n ↔ degree f < n := by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), finsupp.mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl } @[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) : degree_lt R m ≤ degree_lt R n := λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H) theorem degree_lt_eq_span_X_pow {n : ℕ} : degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_lt.1 hp, rw [← finsupp.sum_single p, finsupp.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_lt.2, exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk) end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [comm_ring S] {f : R →+* S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f.comp (is_subring.subtype _)) x p.restriction := rfl section to_subring variables (p : polynomial R) (T : set R) [is_subring T] /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : ↑p.frange ⊆ T) : polynomial T := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans (finset.coe_subset.2 finsupp.frange_single) (finset.singleton_subset_set_iff.2 is_submonoid.one_mem)) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefificents are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ⟨p.support, subtype.val ∘ p.to_fun, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩ @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2 end polynomial variables {R : Type u} {σ : Type v} [comm_ring R] namespace ideal open polynomial /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero_mem' := I.zero_mem, add_mem' := λ _ _, I.add_mem, smul_mem' := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := ⟨assume I : ideal (polynomial R), let L := I.leading_coeff in let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin change I ≤ ideal.span ↑s, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace polynomial theorem exists_irreducible_of_degree_pos {R : Type u} [integral_domain R] [is_noetherian_ring R] {f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f := is_noetherian_ring.exists_irreducible_factor (λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf) (λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _) theorem exists_irreducible_of_nat_degree_pos {R : Type u} [integral_domain R] [is_noetherian_ring R] {f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf } theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [integral_domain R] [is_noetherian_ring R] {f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf end polynomial namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.pempty_ring_equiv R).symm.trans (mv_polynomial.ring_equiv_of_equiv _ fin_zero_equiv'.symm)) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (mv_polynomial.ring_equiv_of_equiv _ e.symm) is_noetherian_ring_fin lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial (fin 0) R) := ring_equiv.is_integral_domain R hR ((ring_equiv_of_equiv R fin_zero_equiv').trans (mv_polynomial.pempty_ring_equiv R)) /-- Auxilliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) : ∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R) | 0 := is_integral_domain_fin_zero R hR | (n+1) := ring_equiv.is_integral_domain (polynomial (mv_polynomial (fin n) R)) (is_integral_domain_fin n).polynomial (mv_polynomial.fin_succ_equiv _ n) lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (ring_equiv_of_equiv R e) /-- Auxilliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] : integral_domain (mv_polynomial σ R) := @is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $ integral_domain.to_is_integral_domain R protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : p.rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) * q.rename (subtype.map id (finset.subset_union_right s t)) = 0, { apply rename_injective _ subtype.val_injective, simpa using h }, letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [integral_domain R] : integral_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, exists_pair_ne := ⟨0, 1, λ H, begin have : eval₂ id (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ id (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end⟩, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } end mv_polynomial
ab88f923839d1b374e33619ddaafddd198459ef2
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic11.lean
0d1a6c865f868dda5ff8c68331777f325279c960
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
301
lean
import standard using tactic theorem tst (a b : Prop) (H : a ↔ b) : b ↔ a := have H1 [fact] : a → b, -- We need to mark H1 as fact, otherwise it is not visible by tactics from iff_elim_left H, by apply iff_intro; apply (assume Hb, iff_mp_right H Hb); apply (assume Ha, H1 Ha)
bb78fc7daccb0aa891ad7936109d942082fc6842
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world2/level1.lean
def41de2cdb4d054960dd4773ab41728d2d87d06
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
7,844
lean
import mynat.definition -- Imports the natural numbers. import mynat.add -- imports addition. namespace mynat -- hide -- World name : Addition world /- Axiom : add_zero (a : mynat) : a + 0 = a -/ /- Axiom : add_succ (a b : mynat) : a + succ(b) = succ(a + b) -/ /- Tactic : induction ## Summary if `n : mynat` is in our assumptions, then `induction n with d hd` attempts to prove the goal by induction on `n`, with the inductive assumption in the `succ` case being `hd`. ## Details If you have a natural number `n : mynat` in your context (above the `⊢`) then `induction n with d hd` turns your goal into two goals, a base case with `n = 0` and an inductive step where `hd` is a proof of the `n = d` case and your goal is the `n = succ(d)` case. ### Example: If this is our local context: ``` n : mynat ⊢ 2 * n = n + n ``` then `induction n with d hd` will give us two goals: ``` ⊢ 2 * 0 = 0 + 0 ``` and ``` d : mynat, hd : 2 * d = d + d ⊢ 2 * succ d = succ d + succ d ``` -/ /- # Addition World. Welcome to Addition World. If you've done all four levels in tutorial world and know about `rw` and `refl`, then you're in the right place. Here's a reminder of the things you're now equipped with which we'll need in this world. ## Data: * a type called `mynat` * a term `0 : mynat`, interpreted as the number zero. * a function `succ : mynat → mynat`, with `succ n` interpreted as "the number after `n`". * Usual numerical notation 0,1,2 etc (although 2 onwards will be of no use to us until much later ;-) ). * Addition (with notation `a + b`). ## Theorems: * `add_zero (a : mynat) : a + 0 = a`. Use with `rw add_zero`. * `add_succ (a b : mynat) : a + succ(b) = succ(a + b)`. Use with `rw add_succ`. * The principle of mathematical induction. Use with `induction` (see below) ## Tactics: * `refl` : proves goals of the form `X = X` * `rw h` : if h is a proof of `A = B`, changes all A's in the goal to B's. * `induction n with d hd` : we're going to learn this right now. # Important thing: This is a *really* good time to check you understand about the box on the left with the drop down menus. All the theorems and all the tactics above are documented there. You can find all you need to know about what theorems you have collected in Theorem statements -> Addition world. Have a click around and check that you can find statements of the theorems above, and explanations of the tactics above. As we go through the game, these lists will grow. The box on the left will prove invaluable as the number of theorems we prove gets bigger. On the other hand, we only need to learn one more tactic to really start going places, so let's learn about that tactic right now. ## Level 1: the `induction` tactic. OK so let's see induction in action. We're going to prove `zero_add (n : mynat) : 0 + n = n`. That is: for all natural numbers $n$, $0+n=n$. Wait $-$ what is going on here? Didn't we already prove that adding zero to $n$ gave us $n$? No we didn't! We proved $n + 0 = n$, and that proof was called `add_zero`. We're now trying to establish `zero_add`, the proof that $0 + n = n$. But aren't these two theorems the same? No they're not! It is *true* that `x + y = y + x`, but we haven't *proved* it yet, and in fact we will need both `add_zero` and `zero_add` in order to prove this. In fact `x + y = y + x` is the boss level for addition world, and `induction` is the only other tactic you'll need to beat it. Now `add_zero` is one of Peano's axioms, so we don't need to prove it, we already have it (indeed, if you've opened the Addition World theorem statements on the left, you can even see it). To prove `0 + n = n` we need to use induction on $n$. While we're here, note that `zero_add` is about zero add something, and `add_zero` is about something add zero. The names of the proofs tell you what the theorems are. Anyway, let's prove `0 + n = n`. Delete `sorry` and replace it with `induction n with d hd,` and **don't forget the comma**. Hit enter, wait for Lean to finish thinking, and let's see what we have. When Lean has finished thinking, we see that we now have *two goals*! The induction tactic has generated for us a base case with `n = 0` (the goal at the top) and an inductive step (the goal underneath). The golden rule: **Tactics operate on the first goal** -- the goal at the top. So let's just worry about that top goal now, the base case `⊢ 0 + 0 = 0`. Remember that `add_zero` (the proof we have already) is the proof of `x + 0 = x` (for any $x$) so we can try `rw add_zero,` . What do you think the goal will change to? Remember to just keep focussing on the top goal, ignore the other one for now, it's not changing and we're not working on it. You should be able to solve the top goal yourself now with `refl`. When you solved this base case goal, we are now be back down to one goal -- the inductive step. Take a look at the text below the lemma to see an explanation of this goal. -/ /- Lemma For all natural numbers $n$, we have $$0 + n = n.$$ -/ lemma zero_add (n : mynat) : 0 + n = n := end /- We're in the successor case, and your top right box should look something like this: ``` case mynat.succ d : mynat, hd : 0 + d = d ⊢ 0 + succ d = succ d ``` *Important:* make sure that you only have one goal at this point. You should have proved `0 + 0 = 0` by now. Tactics only operate on the top goal. The first line just reminds us we're doing the inductive step. We have a fixed natural number `d`, and the inductive hypothesis `hd : 0 + d = d` saying that we have a proof of `0 + d = d`. Our goal is to prove `0 + succ d = succ d`. In words, we're showing that if the lemma is true for `d`, then it's also true for the number after `d`. That's the inductive step. Once we've proved this inductive step, we will have proved `zero_add` by the principle of mathematical induction. To prove our goal, we need to use `add_succ`. We know that `add_succ 0 d` is the result that `0 + succ d = succ (0 + d)`, so the first thing we need to do is to replace the left hand side `0 + succ d` of our goal with the right hand side. We do this with the `rw` command. You can write `rw add_succ,` (or even `rw add_succ 0 d,` if you want to give Lean all the inputs instead of making it figure them out itself). Don't forget the comma though. Hit enter. The goal should change to `⊢ succ (0 + d) = succ d` Now remember our inductive hypothesis `hd : 0 + d = d`. We need to rewrite this too! Type `rw hd,` (don't forget the comma). The goal will now change to `⊢ succ d = succ d` This goal can be solved with the `refl` tactic. After you apply it, Lean will inform you that there are no goals left. You are done! ## Now venture off on your own. Those three tactics -- * `induction n with d hd,` * `rw h,` * `refl,` will get you quite a long way through this game. Using only these tactics you can beat Addition World level 4 (the boss level of Addition World), all of Multiplication World including the boss level `a * b = b * a`, and even all of Power World including the fiendish final boss. This route will give you a good grounding in these three basic tactics; after that, if you are still interested, there are other worlds to master, where you can learn more tactics. But we're getting ahead of ourselves, you still have to beat the rest of Addition World. We're going to stop explaining stuff carefully now. If you get stuck or want to know more about Lean (e.g. how to do much harder maths in Lean), ask in `#new members` at <a href="https://leanprover.zulipchat.com" target="blank">the Lean chat</a> (login required, real name preferred). Kevin or Mohammad or one of the other people there might be able to help. Good luck! Click on "next level" to solve some levels on your own. -/ end mynat -- hide
f41237a7dab1218892e45d57279df723245045a6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/int/cast/defs.lean
ec6e9b20d54631d3f5fdd1896418a7ff0d15dc62
[ "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,447
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import data.nat.cast.defs /-! # Cast of integers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the *canonical* homomorphism from the integers into an additive group with a one (typically a `ring`). In additive groups with a one element, there exists a unique such homomorphism and we store it in the `int_cast : ℤ → R` field. Preferentially, the homomorphism is written as a coercion. ## Main declarations * `int.cast`: Canonical homomorphism `ℤ → R`. * `add_group_with_one`: Type class for `int.cast`. -/ universes u set_option old_structure_cmd true attribute [simp] int.of_nat_eq_coe /-- Default value for `add_group_with_one.int_cast`. -/ protected def int.cast_def {R : Type u} [has_nat_cast R] [has_neg R] : ℤ → R | (n : ℕ) := n | -[1+ n] := -(n+1 : ℕ) /-- Type class for the canonical homomorphism `ℤ → R`. -/ class has_int_cast (R : Type u) := (int_cast : ℤ → R) /-- An `add_group_with_one` is an `add_group` with a `1`. It also contains data for the unique homomorphisms `ℕ → R` and `ℤ → R`. -/ @[protect_proj, ancestor has_int_cast add_group add_monoid_with_one] class add_group_with_one (R : Type u) extends has_int_cast R, add_group R, add_monoid_with_one R := (int_cast := int.cast_def) (int_cast_of_nat : ∀ n : ℕ, int_cast n = (n : R) . control_laws_tac) (int_cast_neg_succ_of_nat : ∀ n : ℕ, int_cast (-(n+1 : ℕ)) = -((n+1 : ℕ) : R) . control_laws_tac) /-- An `add_comm_group_with_one` is an `add_group_with_one` satisfying `a + b = b + a`. -/ @[protect_proj, ancestor add_comm_group add_group_with_one add_comm_monoid_with_one] class add_comm_group_with_one (R : Type u) extends add_comm_group R, add_group_with_one R, add_comm_monoid_with_one R /-- Canonical homomorphism from the integers to any ring(-like) structure `R` -/ protected def int.cast {R : Type u} [has_int_cast R] (i : ℤ) : R := has_int_cast.int_cast i open nat namespace int variables {R : Type u} [add_group_with_one R] -- see Note [coercion into rings] @[priority 900] instance cast_coe {R} [has_int_cast R] : has_coe_t ℤ R := ⟨int.cast⟩ theorem cast_of_nat (n : ℕ) : (of_nat n : R) = n := add_group_with_one.int_cast_of_nat n end int
55ce7eafa9b957e8c1fba2449f2fc6e6b34bc3de
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/function_expected.lean
867e68a13bfc552b6cfadec3c4ee5bf8b56f18c5
[ "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
497
lean
import data.sigma open function namespace Lob inductive TypeExpr : Type₁ := | Arrow : TypeExpr → TypeExpr → TypeExpr | QuotedTermExpr : TypeExpr → TypeExpr open TypeExpr inductive TermExpr : TypeExpr → Type := | Lob : ∀ { LT : TypeExpr }, TermExpr (Arrow (QuotedTermExpr LT) LT) → TermExpr LT open TermExpr definition denoteTermExpr : Π {typeExpr : TypeExpr}, TermExpr typeExpr → Type₁ | _ (@Lob typeExpr1 termExpr1) := (denoteTermExpr termExpr1) (Lob termExpr1) end Lob
46144309811b3a2eb9874699bb3585967d9a350f
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/int/order.lean
2b9bd73beb2dfc53332905863fada8c50b98c314
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,026
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The order relation on the integers. -/ import data.int.basic namespace int theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z < b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, z < lb → ¬ P z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (le_of_not_gt (λ h : elt < b, Hb _ h Helt)), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, if zl : z < b then Hb _ zl else match z, le.dest (le_of_not_gt zl), h with | ._, ⟨n, rfl⟩, h := nat.find_min EX $ lt_of_coe_nat_lt_coe_nat $ lt_of_add_lt_add_left h end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z > b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, z > ub → ¬ P z) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), z < b → ¬P (-z), from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, Hb _ (lt_neg_of_lt_neg h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, by rw [← neg_neg z]; exact al _ (neg_lt_of_neg_lt h)⟩ lemma of_nat_le_of_nat_of_le {n m : ℕ} (h : n ≤ m) : of_nat n ≤ of_nat m := coe_nat_le_coe_nat_of_le h lemma le_of_of_nat_le_of_nat {n m : ℕ} (h : of_nat n ≤ of_nat m) : n ≤ m := let ⟨i, (hi : of_nat n + of_nat i = of_nat m)⟩ := le.dest h in have i + n = m, by apply int.of_nat_inj; rwa [add_comm, of_nat_add], this ▸ nat.le_add_left _ _ end int /- /- more facts specific to int -/ theorem coe_nat_nonneg (n : ℕ) : 0 ≤ ↑n := trivial theorem coe_nat_pos {n : ℕ} (Hpos : #nat n > 0) : ↑n > 0 := coe_nat_lt_coe_nat_of_lt Hpos theorem coe_nat_succ_pos (n : nat) : ↑(nat.succ n) > 0 := coe_nat_pos !nat.succ_pos theorem exists_eq_coe_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = ↑n := obtain (n : ℕ) (H1 : 0 + ↑n = a), from le.dest H, exists.intro n (!zero_add ▸ (H1⁻¹)) theorem exists_eq_neg_coe_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(↑n) := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, obtain (n : ℕ) (Hn : -a = ↑n), from exists_eq_coe_nat this, exists.intro n (eq_neg_of_eq_neg (Hn⁻¹)) theorem coe_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : ↑(nat_abs a) = a := obtain (n : ℕ) (Hn : a = ↑n), from exists_eq_coe_nat H, Hn⁻¹ ▸ congr_arg coe_nat (nat_abs_↑n) theorem coe_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : ↑(nat_abs a) = -a := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, calc coe_nat (nat_abs a) = coe_nat (nat_abs (-a)) : nat_abs_neg ... = -a : coe_nat_nat_abs_of_nonneg this theorem coe_nat_nat_abs (b : ℤ) : nat_abs b = abs b := or.elim (le.total 0 b) (assume H : b ≥ 0, coe_nat_nat_abs_of_nonneg H ⬝ (abs_of_nonneg H)⁻¹) (assume H : b ≤ 0, coe_nat_nat_abs_of_nonpos H ⬝ (abs_of_nonpos H)⁻¹) theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := abs.by_cases rfl !nat_abs_neg theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := obtain (n : nat) (H1 : a + 1 + n = b), from le.dest H, have a + succ n = b, by rewrite [←H1, add.assoc, add.comm 1], lt.intro this theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := obtain (n : nat) (H1 : a + succ n = b), from lt.elim H, have a + 1 + n = b, by rewrite [←H1, add.assoc, add.comm 1], le.intro this theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 := lt_add_of_le_of_pos H trivial theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b := have H1 : a + 1 ≤ b + 1, from add_one_le_of_lt H, le_of_add_le_add_right H1 theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b := lt_of_add_one_le (begin rewrite sub_add_cancel, exact H end) theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b := !sub_add_cancel ▸ add_one_le_of_lt H theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 := le_of_lt_add_one begin rewrite sub_add_cancel, exact H end theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b := !sub_add_cancel ▸ (lt_add_one_of_le H) theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := sign_of_pos (coe_nat_pos !nat.succ_pos) theorem exists_eq_neg_succ_coe_nat {a : ℤ} : a < 0 → ∃m : ℕ, a = -[1+m] := int.cases_on a (assume (m : nat) H, absurd (coe_nat_nonneg m : 0 ≤ m) (not_le_of_gt H)) (assume (m : nat) H, exists.intro m rfl) theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := have a * b > 0, by rewrite H'; apply trivial, have b > 0, from pos_of_mul_pos_left this H, have a > 0, from pos_of_mul_pos_right `a * b > 0` (le_of_lt `b > 0`), or.elim (le_or_gt a 1) (assume : a ≤ 1, show a = 1, from le.antisymm this (add_one_le_of_lt `a > 0`)) (assume : a > 1, have a * b ≥ 2 * 1, from mul_le_mul (add_one_le_of_lt `a > 1`) (add_one_le_of_lt `b > 0`) trivial H, have false, by rewrite [H' at this]; exact this, false.elim this) theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (!mul.comm ▸ H') theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ (one_mul a)⁻¹) theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := dvd.elim H' (assume b, assume : 1 = a * b, eq_one_of_mul_eq_one_right H this⁻¹) theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≤ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, z < lb → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b + coe_nat (least (λ n, P (b + ↑n)) (nat.succ (nat_abs (elt - b)))), have Heltb : elt > b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b + coe_nat (nat_abs (elt - b))), begin rewrite [coe_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), add.comm, sub_add_cancel], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≤ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b + coe_nat (nat_abs (z - b)), by rewrite [coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.add_comm, sub_add_cancel], have Hk : nat_abs (z - b) < least (λ n, P (b + ↑n)) (nat.succ (nat_abs (elt - b))), begin have Hz' := iff.mp !lt_add_iff_sub_lt_left Hz, rewrite [←coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_coe_nat_lt_coe_nat Hz' end, let Hk' := not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≥ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, z > ub → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b - coe_nat (least (λ n, P (b - ↑n)) (nat.succ (nat_abs (b - elt)))), have Heltb : elt < b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b - coe_nat (nat_abs (b - elt))), begin rewrite [coe_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), sub_sub_self], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≥ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b - coe_nat (nat_abs (b - z)), by rewrite [coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), sub_sub_self], have Hk : nat_abs (b - z) < least (λ n, P (b - ↑n)) (nat.succ (nat_abs (b - elt))), begin have Hz' := iff.mp !lt_add_iff_sub_lt_left (iff.mpr !lt_add_iff_sub_lt_right Hz), rewrite [←coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_coe_nat_lt_coe_nat Hz' end, let Hk' := not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end end int -/
73ea9b308dd9f2fb5a077fb210c763bff89f570c
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/meta2.lean
2e5531d401160dc97c709305b561da9a2b0d6ef1
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
241
lean
import system.io open io meta definition foo : nat → nat | a := nat.cases_on a 1 (λ n, foo n + 2) #eval (foo 10) variable [io.interface] meta definition loop : nat → io unit | a := do put_str ">> ", print a, put_str "\n", loop (a+1)
1e6c3e197eb98bbf2ae9c1890403aa3d475cec4c
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/uniform_space/compact_separated.lean
44d7312423510b46bff3f1e538c639a5a176f686
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
10,489
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.separation /-! # Compact separated uniform spaces ## Main statements * `compact_space_uniformity`: On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. * `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform structure. This uniform structure is described in the previous item. * Heine-Cantor theorem: continuous functions on compact separated uniform spaces with values in uniform spaces are automatically uniformly continuous. There are several variations, the main one is `compact_space.uniform_continuous_of_continuous`. ## Implementation notes The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly loop. ## tags uniform space, uniform continuity, compact space -/ open_locale classical uniformity topological_space filter open filter uniform_space set variables {α β : Type*} [uniform_space α] [uniform_space β] /-! ### Uniformity on compact separated spaces -/ lemma compact_space_uniformity [compact_space α] [separated_space α] : 𝓤 α = ⨆ x : α, 𝓝 (x, x) := begin symmetry, refine le_antisymm nhds_le_uniformity _, by_contra H, obtain ⟨V, hV, h⟩ : ∃ V : set (α × α), (∀ x : α, V ∈ 𝓝 (x, x)) ∧ ne_bot (𝓤 α ⊓ 𝓟 Vᶜ), { simpa [le_iff_forall_inf_principal_compl] using H }, let F := 𝓤 α ⊓ 𝓟 Vᶜ, haveI : ne_bot F := h, obtain ⟨⟨x, y⟩, hx⟩ : ∃ (p : α × α), cluster_pt p F := cluster_point_of_compact F, have : cluster_pt (x, y) (𝓤 α) := hx.of_inf_left, have hxy : x = y := eq_of_uniformity_inf_nhds this, subst hxy, have : cluster_pt (x, x) (𝓟 Vᶜ) := hx.of_inf_right, have : (x, x) ∉ interior V, { have : (x, x) ∈ closure Vᶜ, by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have : (x, x) ∈ interior V, { rw mem_interior_iff_mem_nhds, exact hV x }, contradiction end lemma unique_uniformity_of_compact_t2 {α : Type*} [t : topological_space α] [compact_space α] [t2_space α] {u u' : uniform_space α} (h : u.to_topological_space = t) (h' : u'.to_topological_space = t) : u = u' := begin apply uniform_space_eq, change uniformity _ = uniformity _, haveI : @compact_space α u.to_topological_space := by rw h ; assumption, haveI : @compact_space α u'.to_topological_space := by rw h' ; assumption, haveI : @separated_space α u := by rwa [separated_iff_t2, h], haveI : @separated_space α u' := by rwa [separated_iff_t2, h'], rw [compact_space_uniformity, compact_space_uniformity, h, h'] end /-- The unique uniform structure inducing a given compact Hausdorff topological structure. -/ def uniform_space_of_compact_t2 {α : Type*} [topological_space α] [compact_space α] [t2_space α] : uniform_space α := { uniformity := ⨆ x, 𝓝 (x, x), refl := begin simp_rw [filter.principal_le_iff, mem_supr_sets], rintros V V_in ⟨x, _⟩ ⟨⟩, exact mem_of_nhds (V_in x), end, symm := begin refine le_of_eq _, rw map_supr, congr' with x : 1, erw [nhds_prod_eq, ← prod_comm], end, comp := begin /- This is the difficult part of the proof. We need to prove that, for each neighborhood W of the diagonal Δ, W ○ W is still a neighborhood of the diagonal. -/ set 𝓝Δ := ⨆ x : α, 𝓝 (x, x), -- The filter of neighborhoods of Δ set F := 𝓝Δ.lift' (λ (s : set (α × α)), s ○ s), -- Compositions of neighborhoods of Δ -- If this weren't true, then there would be V ∈ 𝓝Δ such that F ⊓ 𝓟 Vᶜ ≠ ⊥ rw le_iff_forall_inf_principal_compl, intros V V_in, by_contra H, haveI : ne_bot (F ⊓ 𝓟 Vᶜ) := H, -- Hence compactness would give us a cluster point (x, y) for F ⊓ 𝓟 Vᶜ obtain ⟨⟨x, y⟩, hxy⟩ : ∃ (p : α × α), cluster_pt p (F ⊓ 𝓟 Vᶜ) := cluster_point_of_compact _, -- In particular (x, y) is a cluster point of 𝓟 Vᶜ, hence is not in the interior of V, -- and a fortiori not in Δ, so x ≠ y have clV : cluster_pt (x, y) (𝓟 $ Vᶜ) := hxy.of_inf_right, have : (x, y) ∉ interior V, { have : (x, y) ∈ closure (Vᶜ), by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have diag_subset : diagonal α ⊆ interior V, { rw subset_interior_iff_nhds, rintros ⟨x, x⟩ ⟨⟩, exact (mem_supr_sets.mp V_in : _) x }, have x_ne_y : x ≠ y, { intro h, apply this, apply diag_subset, simp [h] }, -- Since α is compact and Hausdorff, it is normal, hence regular. haveI : normal_space α := normal_of_compact_t2, -- So there are closed neighboords V₁ and V₂ of x and y contained in disjoint open neighborhoods -- U₁ and U₂. obtain ⟨U₁, V₁, U₁_in, V₁_in, U₂, V₂, U₂_in₂, V₂_in, V₁_cl, V₂_cl, U₁_op, U₂_op, VU₁, VU₂, hU₁₂⟩ : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := disjoint_nested_nhds x_ne_y, -- We set U₃ := (V₁ ∪ V₂)ᶜ so that W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃) is an open -- neighborhood of Δ. let U₃ := (V₁ ∪ V₂)ᶜ, have U₃_op : is_open U₃ := is_open_compl_iff.mpr (is_closed_union V₁_cl V₂_cl), let W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃), have W_in : W ∈ 𝓝Δ, { rw mem_supr_sets, intros x, apply mem_nhds_sets (is_open_union (is_open_union _ _) _), { by_cases hx : x ∈ V₁ ∪ V₂, { left, cases hx with hx hx ; [left, right] ; split ; tauto }, { right, rw mem_prod, tauto }, }, all_goals { simp only [is_open.prod, *] } }, -- So W ○ W ∈ F by definition of F have : W ○ W ∈ F, by simpa only using mem_lift' W_in, -- And V₁.prod V₂ ∈ 𝓝 (x, y) have hV₁₂ : V₁.prod V₂ ∈ 𝓝 (x, y) := prod_mem_nhds_sets V₁_in V₂_in, -- But (x, y) is also a cluster point of F so (V₁.prod V₂) ∩ (W ○ W) ≠ ∅ have clF : cluster_pt (x, y) F := hxy.of_inf_left, obtain ⟨p, p_in⟩ : ∃ p, p ∈ (V₁.prod V₂) ∩ (W ○ W) := cluster_pt_iff.mp clF hV₁₂ this, -- However the construction of W implies (V₁.prod V₂) ∩ (W ○ W) = ∅. -- Indeed assume for contradiction there is some (u, v) in the intersection. -- So u ∈ V₁, v ∈ V₂, and there exists some w such that (u, w) ∈ W and (w ,v) ∈ W. -- Because u is in V₁ which is disjoint from U₂ and U₃, (u, w) ∈ W forces (u, w) ∈ U₁.prod U₁. -- Similarly, because v ∈ V₂, (w ,v) ∈ W forces (w, v) ∈ U₂.prod U₂. -- Hence w ∈ U₁ ∩ U₂ which is empty. have inter_empty : (V₁.prod V₂) ∩ (W ○ W) = ∅, { rw eq_empty_iff_forall_not_mem, rintros ⟨u, v⟩ ⟨⟨u_in, v_in⟩, w, huw, hwv⟩, have uw_in : (u, w) ∈ U₁.prod U₁ := set.mem_prod.2 ((huw.resolve_right (λ h, (h.1 $ or.inl u_in))).resolve_right (λ h, have u ∈ U₁ ∩ U₂, from ⟨VU₁ u_in, h.1⟩, by rwa hU₁₂ at this)), have wv_in : (w, v) ∈ U₂.prod U₂ := set.mem_prod.2 ((hwv.resolve_right (λ h, (h.2 $ or.inr v_in))).resolve_left (λ h, have v ∈ U₁ ∩ U₂, from ⟨h.2, VU₂ v_in⟩, by rwa hU₁₂ at this)), have : w ∈ U₁ ∩ U₂ := ⟨uw_in.2, wv_in.1⟩, rwa hU₁₂ at this }, -- So we have a contradiction rwa inter_empty at p_in, end, is_open_uniformity := begin -- Here we need to prove the topology induced by the constructed uniformity is the -- topology we started with. suffices : ∀ x : α, comap (prod.mk x) (⨆ y, 𝓝 (y ,y)) = 𝓝 x, { intros s, change is_open s ↔ _, simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity_aux, this] }, intros x, simp_rw [comap_supr, nhds_prod_eq, comap_prod, show prod.fst ∘ prod.mk x = λ y : α, x, by ext ; simp, show prod.snd ∘ (prod.mk x) = (id : α → α), by ext ; refl, comap_id], rw [supr_split_single _ x, comap_const_of_mem (λ V, mem_of_nhds)], suffices : ∀ y ≠ x, comap (λ (y : α), x) (𝓝 y) ⊓ 𝓝 y ≤ 𝓝 x, by simpa, intros y hxy, simp [comap_const_of_not_mem (compl_singleton_mem_nhds hxy) (by simp)], end } /-! ### Heine-Cantor theorem -/ /-- Heine-Cantor: a continuous function on a compact separated uniform space is uniformly continuous. -/ lemma compact_space.uniform_continuous_of_continuous [compact_space α] [separated_space α] {f : α → β} (h : continuous f) : uniform_continuous f := calc map (prod.map f f) (𝓤 α) = map (prod.map f f) (⨆ x, 𝓝 (x, x)) : by rw compact_space_uniformity ... = ⨆ x, map (prod.map f f) (𝓝 (x, x)) : by rw map_supr ... ≤ ⨆ x, 𝓝 (f x, f x) : supr_le_supr (λ x, (h.prod_map h).continuous_at) ... ≤ ⨆ y, 𝓝 (y, y) : supr_comp_le (λ y, 𝓝 (y, y)) f ... ≤ 𝓤 β : nhds_le_uniformity /-- Heine-Cantor: a continuous function on a compact separated set of a uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous' {s : set α} {f : α → β} (hs : is_compact s) (hs' : is_separated s) (hf : continuous_on f s) : uniform_continuous_on f s := begin rw uniform_continuous_on_iff_restrict, rw is_separated_iff_induced at hs', rw compact_iff_compact_space at hs, rw continuous_on_iff_continuous_restrict at hf, resetI, exact compact_space.uniform_continuous_of_continuous hf, end /-- Heine-Cantor: a continuous function on a compact set of a separated uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous [separated_space α] {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : uniform_continuous_on f s := hs.uniform_continuous_on_of_continuous' (is_separated_of_separated_space s) hf
1f78068b780c94b1dc699561422f2fc64d5ba785
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/widget/replace_save_info.lean
c3d749b78907225c8b08e1f2c95e712cc9f01ec3
[]
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
242
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.widget.interactive_expr namespace Mathlib
3330b0556e2d41b733d8019a454417b4dec7c548
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/sites/plus.lean
f286b413aecf404980b1244bfe22002924a43c36
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
11,563
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.sites.sheaf /-! # The plus construction for presheaves. This file contains the construction of `P⁺`, for a presheaf `P : Cᵒᵖ ⥤ D` where `C` is endowed with a grothendieck topology `J`. See <https://stacks.math.columbia.edu/tag/00W1> for details. -/ namespace category_theory.grothendieck_topology open category_theory open category_theory.limits open opposite universes w v u variables {C : Type u} [category.{v} C] (J : grothendieck_topology C) variables {D : Type w} [category.{max v u} D] noncomputable theory variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)] variables (P : Cᵒᵖ ⥤ D) /-- The diagram whose colimit defines the values of `plus`. -/ @[simps] def diagram (X : C) : (J.cover X)ᵒᵖ ⥤ D := { obj := λ S, multiequalizer (S.unop.index P), map := λ S T f, multiequalizer.lift _ _ (λ I, multiequalizer.ι (S.unop.index P) (I.map f.unop)) $ λ I, multiequalizer.condition (S.unop.index P) (I.map f.unop), map_id' := λ S, by { ext I, cases I, simpa }, map_comp' := λ S T W f g, by { ext I, simpa } } /-- A helper definition used to define the morphisms for `plus`. -/ @[simps] def diagram_pullback {X Y : C} (f : X ⟶ Y) : J.diagram P Y ⟶ (J.pullback f).op ⋙ J.diagram P X := { app := λ S, multiequalizer.lift _ _ (λ I, multiequalizer.ι (S.unop.index P) I.base) $ λ I, multiequalizer.condition (S.unop.index P) I.base, naturality' := λ S T f, by { ext, dsimp, simpa } } /-- A natural transformation `P ⟶ Q` induces a natural transformation between diagrams whose colimits define the values of `plus`. -/ @[simps] def diagram_nat_trans {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (X : C) : J.diagram P X ⟶ J.diagram Q X := { app := λ W, multiequalizer.lift _ _ (λ i, multiequalizer.ι _ i ≫ η.app _) begin intros i, erw [category.assoc, category.assoc, ← η.naturality, ← η.naturality, ← category.assoc, ← category.assoc, multiequalizer.condition], refl, end, naturality' := λ _ _ _, by { dsimp, ext, simpa } } @[simp] lemma diagram_nat_trans_id (X : C) (P : Cᵒᵖ ⥤ D) : J.diagram_nat_trans (𝟙 P) X = 𝟙 (J.diagram P X) := begin ext, dsimp, simp only [multiequalizer.lift_ι, category.id_comp], erw category.comp_id end @[simp] lemma diagram_nat_trans_zero [preadditive D] (X : C) (P Q : Cᵒᵖ ⥤ D) : J.diagram_nat_trans (0 : P ⟶ Q) X = 0 := by { ext j x, dsimp, rw [zero_comp, multiequalizer.lift_ι, comp_zero] } @[simp] lemma diagram_nat_trans_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (X : C) : J.diagram_nat_trans (η ≫ γ) X = J.diagram_nat_trans η X ≫ J.diagram_nat_trans γ X := by { ext, dsimp, simp } variable (D) /-- `J.diagram P`, as a functor in `P`. -/ @[simps] def diagram_functor (X : C) : (Cᵒᵖ ⥤ D) ⥤ (J.cover X)ᵒᵖ ⥤ D := { obj := λ P, J.diagram P X, map := λ P Q η, J.diagram_nat_trans η X, map_id' := λ P, J.diagram_nat_trans_id _ _, map_comp' := λ P Q R η γ, J.diagram_nat_trans_comp _ _ _ } variable {D} variable [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] /-- The plus construction, associating a presheaf to any presheaf. See `plus_functor` below for a functorial version. -/ def plus_obj : Cᵒᵖ ⥤ D := { obj := λ X, colimit (J.diagram P X.unop), map := λ X Y f, colim_map (J.diagram_pullback P f.unop) ≫ colimit.pre _ _, map_id' := begin intros X, ext S, dsimp, simp only [diagram_pullback_app, colimit.ι_pre, ι_colim_map_assoc, category.comp_id], let e := S.unop.pullback_id, dsimp only [functor.op, pullback_obj], erw [← colimit.w _ e.inv.op, ← category.assoc], convert category.id_comp _, ext I, dsimp, simp only [multiequalizer.lift_ι, category.id_comp, category.assoc], dsimp [cover.arrow.map, cover.arrow.base], cases I, congr, simp, end, map_comp' := begin intros X Y Z f g, ext S, dsimp, simp only [diagram_pullback_app, colimit.ι_pre_assoc, colimit.ι_pre, ι_colim_map_assoc, category.assoc], let e := S.unop.pullback_comp g.unop f.unop, dsimp only [functor.op, pullback_obj], erw [← colimit.w _ e.inv.op, ← category.assoc, ← category.assoc], congr' 1, ext I, dsimp, simp only [multiequalizer.lift_ι, category.assoc], cases I, dsimp only [cover.arrow.base, cover.arrow.map], congr' 2, simp, end } /-- An auxiliary definition used in `plus` below. -/ def plus_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : J.plus_obj P ⟶ J.plus_obj Q := { app := λ X, colim_map (J.diagram_nat_trans η X.unop), naturality' := begin intros X Y f, dsimp [plus_obj], ext, simp only [diagram_pullback_app, ι_colim_map, colimit.ι_pre_assoc, colimit.ι_pre, ι_colim_map_assoc, category.assoc], simp_rw ← category.assoc, congr' 1, ext, dsimp, simpa, end } @[simp] lemma plus_map_id (P : Cᵒᵖ ⥤ D) : J.plus_map (𝟙 P) = 𝟙 _ := begin ext x : 2, dsimp only [plus_map, plus_obj], rw [J.diagram_nat_trans_id, nat_trans.id_app], ext, dsimp, simp, end @[simp] lemma plus_map_zero [preadditive D] (P Q : Cᵒᵖ ⥤ D) : J.plus_map (0 : P ⟶ Q) = 0 := by { ext, erw [comp_zero, colimit.ι_map, J.diagram_nat_trans_zero, zero_comp] } @[simp] lemma plus_map_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) : J.plus_map (η ≫ γ) = J.plus_map η ≫ J.plus_map γ := begin ext : 2, dsimp only [plus_map], rw J.diagram_nat_trans_comp, ext, dsimp, simp, end variable (D) /-- The plus construction, a functor sending `P` to `J.plus_obj P`. -/ @[simps] def plus_functor : (Cᵒᵖ ⥤ D) ⥤ Cᵒᵖ ⥤ D := { obj := λ P, J.plus_obj P, map := λ P Q η, J.plus_map η, map_id' := λ _, plus_map_id _ _, map_comp' := λ _ _ _ _ _, plus_map_comp _ _ _ } variable {D} /-- The canonical map from `P` to `J.plus.obj P`. See `to_plus` for a functorial version. -/ def to_plus : P ⟶ J.plus_obj P := { app := λ X, cover.to_multiequalizer (⊤ : J.cover X.unop) P ≫ colimit.ι (J.diagram P X.unop) (op ⊤), naturality' := begin intros X Y f, dsimp [plus_obj], delta cover.to_multiequalizer, simp only [diagram_pullback_app, colimit.ι_pre, ι_colim_map_assoc, category.assoc], dsimp only [functor.op, unop_op], let e : (J.pullback f.unop).obj ⊤ ⟶ ⊤ := hom_of_le (order_top.le_top _), rw [← colimit.w _ e.op, ← category.assoc, ← category.assoc, ← category.assoc], congr' 1, ext, dsimp, simp only [multiequalizer.lift_ι, category.assoc], dsimp [cover.arrow.base], simp, end } @[simp, reassoc] lemma to_plus_naturality {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : η ≫ J.to_plus Q = J.to_plus _ ≫ J.plus_map η := begin ext, dsimp [to_plus, plus_map], delta cover.to_multiequalizer, simp only [ι_colim_map, category.assoc], simp_rw ← category.assoc, congr' 1, ext, dsimp, simp, end variable (D) /-- The natural transformation from the identity functor to `plus`. -/ @[simps] def to_plus_nat_trans : (𝟭 (Cᵒᵖ ⥤ D)) ⟶ J.plus_functor D := { app := λ P, J.to_plus P, naturality' := λ _ _ _, to_plus_naturality _ _ } variable {D} /-- `(P ⟶ P⁺)⁺ = P⁺ ⟶ P⁺⁺` -/ @[simp] lemma plus_map_to_plus : J.plus_map (J.to_plus P) = J.to_plus (J.plus_obj P) := begin ext X S, dsimp [to_plus, plus_obj, plus_map], delta cover.to_multiequalizer, simp only [ι_colim_map], let e : S.unop ⟶ ⊤ := hom_of_le (order_top.le_top _), simp_rw [← colimit.w _ e.op, ← category.assoc], congr' 1, ext I, dsimp, simp only [diagram_pullback_app, colimit.ι_pre, multiequalizer.lift_ι, ι_colim_map_assoc, category.assoc], dsimp only [functor.op], let ee : (J.pullback (I.map e).f).obj S.unop ⟶ ⊤ := hom_of_le (order_top.le_top _), simp_rw [← colimit.w _ ee.op, ← category.assoc], congr' 1, ext II, dsimp, simp only [limit.lift_π, multifork.of_ι_π_app, multiequalizer.lift_ι, category.assoc], dsimp [multifork.of_ι], convert multiequalizer.condition (S.unop.index P) ⟨_, _, _, II.f, 𝟙 _, I.f, II.f ≫ I.f, I.hf, sieve.downward_closed _ I.hf _, by simp⟩, { cases I, refl }, { dsimp [cover.index], erw [P.map_id, category.comp_id], refl } end lemma is_iso_to_plus_of_is_sheaf (hP : presheaf.is_sheaf J P) : is_iso (J.to_plus P) := begin rw presheaf.is_sheaf_iff_multiequalizer at hP, rsufficesI : ∀ X, is_iso ((J.to_plus P).app X), { apply nat_iso.is_iso_of_is_iso_app }, intros X, dsimp, rsufficesI : is_iso (colimit.ι (J.diagram P X.unop) (op ⊤)), { apply is_iso.comp_is_iso }, rsufficesI : ∀ (S T : (J.cover X.unop)ᵒᵖ) (f : S ⟶ T), is_iso ((J.diagram P X.unop).map f), { apply is_iso_ι_of_is_initial (initial_op_of_terminal is_terminal_top) }, intros S T e, have : S.unop.to_multiequalizer P ≫ (J.diagram P (X.unop)).map e = T.unop.to_multiequalizer P, by { ext, dsimp, simpa }, have : (J.diagram P (X.unop)).map e = inv (S.unop.to_multiequalizer P) ≫ T.unop.to_multiequalizer P, by simp [← this], rw this, apply_instance, end /-- The natural isomorphism between `P` and `P⁺` when `P` is a sheaf. -/ def iso_to_plus (hP : presheaf.is_sheaf J P) : P ≅ J.plus_obj P := by letI := is_iso_to_plus_of_is_sheaf J P hP; exact as_iso (J.to_plus P) @[simp] lemma iso_to_plus_hom (hP : presheaf.is_sheaf J P) : (J.iso_to_plus P hP).hom = J.to_plus P := rfl /-- Lift a morphism `P ⟶ Q` to `P⁺ ⟶ Q` when `Q` is a sheaf. -/ def plus_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) : J.plus_obj P ⟶ Q := J.plus_map η ≫ (J.iso_to_plus Q hQ).inv @[simp, reassoc] lemma to_plus_plus_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) : J.to_plus P ≫ J.plus_lift η hQ = η := begin dsimp [plus_lift], rw ← category.assoc, rw iso.comp_inv_eq, dsimp only [iso_to_plus, as_iso], rw to_plus_naturality, end lemma plus_lift_unique {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) (γ : J.plus_obj P ⟶ Q) (hγ : J.to_plus P ≫ γ = η) : γ = J.plus_lift η hQ := begin dsimp only [plus_lift], rw [iso.eq_comp_inv, ← hγ, plus_map_comp], dsimp, simp, end lemma plus_hom_ext {P Q : Cᵒᵖ ⥤ D} (η γ : J.plus_obj P ⟶ Q) (hQ : presheaf.is_sheaf J Q) (h : J.to_plus P ≫ η = J.to_plus P ≫ γ) : η = γ := begin have : γ = J.plus_lift (J.to_plus P ≫ γ) hQ, { apply plus_lift_unique, refl }, rw this, apply plus_lift_unique, exact h end @[simp] lemma iso_to_plus_inv (hP : presheaf.is_sheaf J P) : (J.iso_to_plus P hP).inv = J.plus_lift (𝟙 _) hP := begin apply J.plus_lift_unique, rw [iso.comp_inv_eq, category.id_comp], refl, end @[simp] lemma plus_map_plus_lift {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (hR : presheaf.is_sheaf J R) : J.plus_map η ≫ J.plus_lift γ hR = J.plus_lift (η ≫ γ) hR := begin apply J.plus_lift_unique, rw [← category.assoc, ← J.to_plus_naturality, category.assoc, J.to_plus_plus_lift], end instance plus_functor_preserves_zero_morphisms [preadditive D] : (plus_functor J D).preserves_zero_morphisms := { map_zero' := λ F G, by { ext, dsimp, rw [J.plus_map_zero, nat_trans.app_zero] } } end category_theory.grothendieck_topology
cf44410e48d181400c816900bb29a8fae6b39295
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/toFromJson.lean
e87e9aa81723f786b68083b148d2c1fcd7aa1f85
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,099
lean
import Lean open Lean declare_syntax_cat json syntax str : json syntax num : json syntax "{" (ident ": " json),* "}" : json syntax "[" json,* "]" : json syntax "json " json : term /- declare a micro json parser, so we can write our tests in a more legible way. -/ open Json in macro_rules | `(json $s:str) => pure s | `(json $n:num) => pure n | `(json { $[$ns : $js],* }) => do let mut fields := #[] for n in ns, j in js do fields := fields.push (← `(($(quote n.getId.getString!), json $j))) `(mkObj [$fields,*]) | `(json [ $[$js],* ]) => do let mut fields := #[] for j in js do fields := fields.push (← `(json $j)) `(Json.arr #[$fields,*]) def checkToJson [ToJson α] (obj : α) (rhs : Json) : MetaM Unit := let lhs := (obj |> toJson).pretty if lhs == rhs.pretty then pure () else throwError "{lhs} ≟ {rhs}" def checkRoundTrip [Repr α] [BEq α] [ToJson α] [FromJson α] (obj : α) : MetaM Unit := do let roundTripped := obj |> toJson |> fromJson? if let Except.ok roundTripped := roundTripped then if obj == roundTripped then pure () else throwError "{repr obj} ≟ {repr roundTripped}" else throwError "couldn't parse: {repr obj} ≟ {obj |> toJson}" -- set_option trace.Meta.debug true in structure Foo where x : Nat y : String deriving ToJson, FromJson, Repr, BEq #eval checkToJson { x := 1, y := "bla" : Foo} (json { y : "bla", x : 1 }) #eval checkRoundTrip { x := 1, y := "bla" : Foo } -- set_option trace.Elab.command true structure WInfo where a : Nat b : Nat deriving ToJson, FromJson, Repr, BEq -- set_option trace.Elab.command true inductive E | W : WInfo → E | WAlt (a b : Nat) | X : Nat → Nat → E | Y : Nat → E | YAlt (a : Nat) | Z deriving ToJson, FromJson, Repr, BEq #eval checkToJson (E.W { a := 2, b := 3}) (json { W : { a : 2, b : 3 } }) #eval checkRoundTrip (E.W { a := 2, b := 3 }) #eval checkToJson (E.WAlt 2 3) (json { WAlt : { a : 2, b : 3 } }) #eval checkRoundTrip (E.WAlt 2 3) #eval checkToJson (E.X 2 3) (json { X : [2, 3] }) #eval checkRoundTrip (E.X 2 3) #eval checkToJson (E.Y 4) (json { Y : 4 }) #eval checkRoundTrip (E.Y 4) #eval checkToJson (E.YAlt 5) (json { YAlt : { a : 5 } }) #eval checkRoundTrip (E.YAlt 5) #eval checkToJson E.Z (json "Z") #eval checkRoundTrip E.Z inductive ERec | mk : Nat → ERec | W : ERec → ERec deriving ToJson, FromJson, Repr, BEq #eval checkToJson (ERec.W (ERec.mk 6)) (json { W : { mk : 6 }}) #eval checkRoundTrip (ERec.mk 7) #eval checkRoundTrip (ERec.W (ERec.mk 8)) inductive ENest | mk : Nat → ENest | W : (Array ENest) → ENest deriving ToJson, FromJson, Repr, BEq #eval checkToJson (ENest.W #[ENest.mk 9]) (json { W : [{ mk : 9 }]}) #eval checkRoundTrip (ENest.mk 10) #eval checkRoundTrip (ENest.W #[ENest.mk 11]) inductive EParam (α : Type) | mk : α → EParam α deriving ToJson, FromJson, Repr, BEq #eval checkToJson (EParam.mk 12) (json { mk : 12 }) #eval checkToJson (EParam.mk "abcd") (json { mk : "abcd" }) #eval checkRoundTrip (EParam.mk 13) #eval checkRoundTrip (EParam.mk "efgh")
eda75d6b25b4e6d21d990deaa6681940acda89d3
f57570f33b51ef0271f8c366142363d5ae8fff45
/src/enderton_predicate_logic.lean
f29ea8d478ea9b4a0f1d6e34ea288ccb8b884c36
[]
no_license
maxd13/lean-logic
4083cb3fbb45b423befca7fda7268b8ba85ff3a6
ddcab46b77adca91b120a5f37afbd48794da8b52
refs/heads/master
1,692,257,681,488
1,631,740,832,000
1,631,740,832,000
246,324,437
0
0
null
null
null
null
UTF-8
Lean
false
false
23,394
lean
import data.set.countable tactic.find tactic.tidy tactic.ring universe u -- We introduce a much simplified version of -- untyped first order (minimal) predicate logic. -- make all propositions decidable. -- Allows us to freely use ifs like in Haskell -- but then we must add noncomputable to all functions -- local attribute [instance] classical.prop_decidable namespace logic open logic list tactic set section formulas parameters {functional_symbol : Type u} [decidable_eq functional_symbol] parameter {relational_symbol : Type u} parameter {arity : functional_symbol -> ℕ} parameter {rarity : relational_symbol -> ℕ} -- arity types def is_constant (f : functional_symbol) := arity f = 0 def nary (n : ℕ) := subtype {f : functional_symbol | arity f = n} def nrary (n : ℕ) := subtype {r : relational_symbol | rarity r = n} @[reducible] def const := nary 0 -- terms in the language inductive term | var : ℕ → term | app {n : ℕ} (f : nary n) (v : fin n → term) : term -- constant terms. def const.term : const → term | c := term.app c fin_zero_elim @[reducible] def term.rw : term → ℕ → term → term | (term.var a) x t := if x = a then t else term.var a | (term.app f v) x t := let v₂ := λ m, term.rw (v m) x t in term.app f v₂ def term.vars : term → list ℕ | (term.var a) := [a] | (term.app f v) := let v₂ := λ m, term.vars (v m) in foldr (++) [] (of_fn v₂) @[reducible] def term.denotes (t : term) := t.vars = [] @[reducible] def term.conotes (t : term) := ¬ t.denotes -- a term in the proper sense of the term (pun intended). def pterm := subtype {t : term | t.denotes} def expression := subtype {t : term | t.conotes} -- def term.subterms : term → set term -- | (term.app f v) := -- let v₂ := λ m, term.subterms (v m) in -- (⋃ m, v₂ m) ∪ {(term.app f v)} -- | t := {t} def list.vars : list term → list ℕ | [] := ∅ | (hd :: tl) := hd.vars ++ tl.vars -- def list.subterms : list term → list term -- | [] := ∅ -- | (hd :: tl) := hd.subterms ++ tl.subterms def list.rw : list term → ℕ → term → list term | [] _ _:= ∅ | (hd :: tl) x t := (hd.rw x t) :: tl.rw x t -- def subterms : set term → list term -- | S := ⋃ x ∈ S, term.subterms x -- formulas inductive uformula | relational {n : ℕ} (r : nrary n) (v : fin n → term) : uformula | equation (t₁ t₂ : term) : uformula | false : uformula | for_all : ℕ → uformula → uformula | if_then : uformula → uformula → uformula def uformula.not (φ) := uformula.if_then φ uformula.false reserve infixr ` ⇒ `:55 class has_exp (α : Type u) := (exp : α → α → α) infixr ⇒ := has_exp.exp instance uformula.has_exp : has_exp uformula := ⟨uformula.if_then⟩ local notation `∼` := uformula.not @[reducible] def uformula.rw : uformula → ℕ → term → uformula | (uformula.relational r v) x t := let v₂ := λ m, (v m).rw x t in uformula.relational r v₂ | (uformula.equation t₁ t₂) x t := let t₃ := t₁.rw x t, t₄ := t₂.rw x t in uformula.equation t₃ t₄ | (uformula.for_all y φ) x t := let ψ := if y = x then φ else φ.rw x t in uformula.for_all y ψ | (uformula.if_then φ ψ) x t := uformula.if_then (φ.rw x t) (ψ.rw x t) | φ _ _ := φ def list_sub_aux {α} [decidable_eq α] : list α → list α → list α | [] _ := [] | (hd::tl) xs := begin cases list.decidable_mem hd xs, exact hd :: list_sub_aux tl xs, exact list_sub_aux tl xs, end instance list_sub {α} [decidable_eq α] : has_sub (list α) := ⟨list_sub_aux⟩ -- free variables @[reducible] def uformula.free : uformula → list ℕ | (uformula.relational r v) := list.vars (of_fn v) | (uformula.equation t₁ t₂) := t₁.vars ++ t₂.vars | (uformula.for_all x φ) := φ.free - [x] | (uformula.if_then φ ψ) := φ.free ++ ψ.free | _ := [] -- open and closed formulas. def uformula.closed : uformula → Prop | φ := φ.free = ∅ def uformula.open : uformula → Prop | φ := ¬ φ.closed def uformula.vars : uformula → list ℕ | (uformula.for_all x φ) := x::φ.free | (uformula.if_then φ ψ) := φ.vars ++ ψ.vars | φ := φ.free inductive uaxiom : uformula → Prop | p₁ (φ ψ : uformula) : uaxiom (φ ⇒ ψ ⇒ φ) | p₂ (φ ψ δ : uformula) : uaxiom ((φ ⇒ ψ ⇒ δ) ⇒ ((φ ⇒ ψ) ⇒ φ ⇒ δ)) | p₃ (φ ψ : uformula) : uaxiom ((∼φ ⇒ ∼ψ) ⇒ ψ ⇒ φ) | q₅ (x : ℕ) (φ : uformula) (t : pterm) : uaxiom ((uformula.for_all x φ) ⇒ φ.rw x t.val) | q₆ (x : ℕ) (φ ψ : uformula) : uaxiom ((uformula.for_all x φ ⇒ ψ) ⇒ (uformula.for_all x φ) ⇒ (uformula.for_all x ψ)) | q₇ (x : ℕ) (φ : uformula) (x ∉ φ.free) : uaxiom (φ ⇒ (uformula.for_all x φ)) inductive argument | silence {} : argument -- empty argument | node : uformula → argument → argument → argument → argument def argument.assumes (φ : uformula) : argument → Prop | argument.silence := false | (argument.node ψ argument.silence argument.silence argument.silence) := φ = ψ | (argument.node _ a₁ a₂ a₃) := a₁.assumes ∨ a₂.assumes ∨ a₃.assumes @[reducible] def argument.concludes (φ : uformula) : argument → Prop | argument.silence := false | (logic.argument.node ψ x y z) := ψ = φ -- def silence := argument.silence -- -- because I said so -- def argument.return : uformula → argument -- | φ := argument.node φ silence silence silence -- tells whether an argument is a proof from Γ -- TODO: CONVERT THIS TO INDUCTIVE DEFINITION !!!! @[reducible] def argument.proof_from (Γ : set uformula) : argument → Prop | (argument.node φ argument.silence argument.silence argument.silence) := φ ∈ Γ ∨ φ = uformula.true ∨ ∃ t, φ = uformula.equation t t -- introduction rules | (argument.node (uformula.and φ ψ) γ₁ γ₂ argument.silence) := γ₁.concludes φ ∧ γ₂.concludes ψ ∧ γ₁.proof_from ∧ γ₂.proof_from | (argument.node (uformula.or φ _) γ₁ argument.silence argument.silence) := γ₁.concludes φ ∧ γ₁.proof_from | (argument.node (uformula.or _ ψ) argument.silence γ₂ argument.silence) := γ₂.concludes ψ ∧ γ₂.proof_from | (argument.node (uformula.if_then φ ψ) γ argument.silence argument.silence) := γ.concludes ψ ∧ γ.assumes φ ∧ γ.proof_from | (argument.node (uformula.for_all x φ) γ argument.silence argument.silence) := ∃ c, γ.concludes (φ.rw x $ term.abs c) ∧ x ∈ φ.free ∧ γ.proof_from | (argument.node (uformula.exist x φ) γ argument.silence argument.silence) := ∃ t, γ.concludes (φ.rw x t) ∧ t.denotes ∧ x ∈ φ.free ∧ γ.proof_from -- elimination rules | (argument.node φ γ argument.silence argument.silence) := ((∃ ψ, γ.concludes $ uformula.and φ ψ) ∨ (∃ ψ, γ.concludes $ uformula.and ψ φ) ∨ (∃ x (ψ : uformula) (t : term), t.denotes ∧ x ∈ ψ.free ∧ γ.concludes (uformula.for_all x ψ) ∧ φ = ψ.rw x t)) ∧ γ.proof_from | (argument.node φ γ₁ γ₂ argument.silence) := ((∃ ψ, γ₁.concludes (ψ ⇒ φ) ∧ γ₂.concludes ψ) ∨ (∃ x (ψ : uformula) c, x ∈ ψ.free ∧ γ₁.concludes (uformula.exist x ψ) ∧ γ₂.concludes ((ψ.rw x $ term.abs c) ⇒ φ)) ∨ (∃ x (ψ : uformula) (t₁ t₂ : term), t₁.denotes ∧ t₂.denotes ∧ x ∈ ψ.free ∧ γ₁.concludes (ψ.rw x t₁) ∧ γ₂.concludes (uformula.equation t₁ t₂) ∧ φ = ψ.rw x t₂)) ∧ γ₁.proof_from ∧ γ₂.proof_from | (argument.node φ γ₁ γ₂ γ₃) := ∃ ψ₁ ψ₂, γ₁.concludes (uformula.or ψ₁ ψ₂) ∧ γ₂.concludes (ψ₁ ⇒ φ) ∧ γ₃.concludes (ψ₂ ⇒ φ) ∧ γ₁.proof_from ∧ γ₂.proof_from ∧ γ₃.proof_from | _ := false def argument.proof_of (φ : uformula) (Γ : set uformula) : argument → Prop | γ := γ.proof_from Γ ∧ γ.concludes φ variables (Γ : set uformula) (φ : uformula) theorem self_entailment : minimal.entails Γ (φ ⇒ φ) := begin apply minimal.entails.intro, apply minimal.entails.reflexive (Γ∪{φ}) φ, simp end theorem id_symm : ∀ (t₁ t₂ : pterm), minimal.entails Γ (uformula.equation t₁.val t₂.val) → minimal.entails Γ (uformula.equation t₂.val t₁.val) := let ne := var_ne in begin intros t₁ t₂ h, apply nonempty.elim ne, intro x, -- φ := "x = t₁" let φ := uformula.equation (term.var x) t₁.val, have den₁ := t₁.property.1, have den₂ := t₂.property.1, have c₀ : x ∈ φ.free, simp[φ], have c₁ : minimal.entails Γ (φ.rw x t₁.val), simp[φ], dunfold uformula.rw, simp, dunfold term.rw, simp, rw den_rw t₁.val t₁.val x t₁.property.1, apply minimal.entails.identity_intro Γ t₁.val, have c₂ : minimal.entails Γ (φ.rw x t₂.val), apply minimal.entails.identity_elim, --Γ φ x c₀ t₁ t₂ den₂ den₁, repeat {assumption <|> apply_assumption}, simp[φ] at c₂, have c₃ : (uformula.equation (term.var x) (t₁.val)).rw x (t₂.val) = uformula.equation (t₂.val) (t₁.val), dunfold uformula.rw, simp, constructor, dunfold term.rw, simp, apply den_rw t₁.val t₂.val x den₁, rwa c₃ at c₂, end variables (Δ : set uformula) (ψ : uformula) theorem monotonicity : Δ ⊆ Γ → minimal.entails Δ ψ → minimal.entails Γ ψ := begin intros H h, -- induction on the possible ways in which -- Δ could prove ψ induction h, -- case it was proven by reflection apply minimal.entails.reflexive Γ h_φ, exact H h_h, -- case it was proven by transitivity apply minimal.entails.transitivity Γ h_Δ h_φ, intros ψ₂ elem, repeat {assumption <|> apply_assumption}, -- case it was proven by and_intro apply minimal.entails.and_intro,-- h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by and_elim_left apply minimal.entails.and_elim_left h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by and_elim_right apply minimal.entails.and_elim_right h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by or_intro_left apply minimal.entails.or_intro_left h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by or_intro_right apply minimal.entails.or_intro_right h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by or_elim apply minimal.entails.or_elim,-- h_φ h_ψ h_δ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by modus ponens apply minimal.entails.modus_ponens h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by intro have c : minimal.entails h_Γ (h_φ ⇒ h_ψ), apply minimal.entails.intro h_φ h_ψ h_Γ, assumption, apply minimal.entails.transitivity Γ h_Γ (h_φ ⇒ h_ψ), intros ψ₂ elem, have c₂ := H elem, exact minimal.entails.reflexive Γ ψ₂ c₂, assumption, -- case it was proven by true_intro exact minimal.entails.true_intro Γ, -- case it was proven by for_all_intro apply minimal.entails.for_all_intro Γ h_φ h_x h_xf h_c, repeat {assumption <|> apply_assumption}, -- case it was proven by for_all_elim apply minimal.entails.for_all_elim Γ h_φ h_x h_xf, repeat {assumption <|> apply_assumption}, -- case it was proven by exists_intro apply minimal.entails.exists_intro Γ h_φ h_x h_xf h_t, repeat {assumption <|> apply_assumption}, -- case it was proven by exists_elim apply minimal.entails.exists_elim Γ h_φ h_ψ h_x h_xf, repeat {assumption <|> apply_assumption}, -- case it was proven by identity_intro apply minimal.entails.identity_intro Γ h_t, -- case it was proven by identity_elim apply minimal.entails.identity_elim Γ h_φ h_x h_xf h_t₁ h_t₂, repeat {assumption <|> apply_assumption}, end theorem proof_entails : (∃ p : argument, p.proof_of φ Γ) → minimal.entails Γ φ := begin intro h, obtain ⟨p, ph₁, ph₂⟩ := h, induction p, have c : false := ph₂, contradiction, have eq : φ = p_a := sorry, -- impossible to unfold at ph₂ for some reason -- simp [argument.concludes] at ph₂, rw ←eq at ph₁, admit, -- induction φ, -- simp at ph₁, end section semantics parameters {α : Type u} [inhabited α] -- functional interpretation def fint {n : ℕ} := nary n → (fin n → α) → α -- relational interpretation def rint {n : ℕ} := nrary n → (fin n → α) → Prop -- variable assignment def vasgn := ℕ → α parameter exists_ass : nonempty vasgn structure model := (I₁ : Π {n}, @fint n) -- required because any constant that would map -- to the default value, would be a "generic point" -- of the type α, i.e. any of its properties would be -- true of any instance of α. (constant_no_default : ∀ f : nary 0, I₁ f fin_zero_elim ≠ default α) (I₂ : Π {n}, @rint n) -- @[reducible] def model.reference' (M : model) : term → vasgn → α | (term.var x) asg := asg x | (@term.app _ _ _ _ _ _ _ 0 f _) _ := model.I₁ M f fin_zero_elim | (@term.app _ _ _ _ _ _ _ (n+1) f v) asg := let v₂ := λ k, model.reference' (v k) asg in model.I₁ M f v₂ -- An unavoidable trick. -- It is just ridiculously hard to try any other -- alternative. I gained A LOT of productivity -- from this. | _ _ := default α -- If the default value is considered to be -- a non-existent reference, like an option.none, -- then this reference is only defined for pterms. def model.reference (M : model) : pterm → α | ⟨(@term.app _ _ _ _ _ _ _ 0 f _),_⟩ := model.I₁ M f fin_zero_elim | ⟨(@term.app _ _ _ _ _ _ _ (n+1) f v),p⟩ := let v₂ := λ k, model.reference ⟨v k, begin admit, end⟩ in model.I₁ M f v₂ | _ := sorry -- | t := M.reference' t.val (λx, default α) using_well_founded well_founded_tactics.default -- begin -- constructor, -- intros x y, -- exact `[exact well_founded_tactics.cancel_nat_add_lt], -- exact assumption, -- end def model.satisfies' : model → uformula → vasgn → Prop | M (uformula.relational r v) asg := M.I₂ r $ λm, M.reference' (v m) asg | M (uformula.equation t₁ t₂) asg := let x := model.reference' M t₁ asg, y := model.reference' M t₂ asg in x = y | M uformula.true _ := true | M uformula.false _ := false | M (uformula.for_all x φ) asg := ∀ (a : α) (ass : vasgn), ass x = a → (∀ y, y ≠ x → ass y = asg y) → M.satisfies' φ ass | M (uformula.exist x φ) asg := ∃ (a : α), ∀ (ass : vasgn), ass x = a → (∀ y, y ≠ x → ass y = asg y) → M.satisfies' φ ass | M (uformula.and φ ψ) asg := let x := model.satisfies' M φ asg, y := model.satisfies' M ψ asg in x ∧ y | M (uformula.or φ ψ) asg := let x := model.satisfies' M φ asg, y := model.satisfies' M ψ asg in x ∨ y | M (uformula.if_then φ ψ) asg := let x := model.satisfies' M φ asg, y := model.satisfies' M ψ asg in x → y @[reducible] def model.satisfies : model → uformula → Prop | M φ := ∀ (ass : vasgn), M.satisfies' φ ass local infixr `⊨₁`:55 := model.satisfies local infixr `⊢`:55 := minimal.entails include exists_ass lemma false_is_unsat : ¬∃ M : model, M ⊨₁ uformula.false := begin intro h, obtain ⟨M, h⟩ := h, tactic.unfreeze_local_instances, obtain ⟨x⟩ := exists_ass, exact h x, end omit exists_ass def model.for : model → set uformula → Prop | M Γ := ∀ φ ∈ Γ, M ⊨₁ φ -- semantic consequence -- remember Γ and φ are already defined def theory.follows : Prop := ∀ (M : model) ass, (∀ ψ ∈ Γ, M.satisfies' ψ ass) → M.satisfies' φ ass local infixr `⊨`:55 := theory.follows def vasgn.bind (ass : vasgn) (x : ℕ) (val : α) : vasgn := λy, if y = x then val else ass y -- lemma uformula.rw.semantics (φ : uformula) -- (x : ℕ) -- (h₀ : x ∈ φ.free) -- (ass : vasgn) -- (M : model) -- (t : pterm) -- : -- M.satisfies' φ ass → -- M.satisfies' (φ.rw x t.val) -- (ass.bind x (M.reference' t.val ass)) -- := -- begin -- -- intro h, -- induction φ; -- dunfold uformula.rw; try{simp}; -- dunfold model.satisfies'; -- intro h, -- -- have c₁ : (λ (m : fin φ_n), M.reference' (φ_v m) ass) = (flip M.reference' ass) ∘ φ_v, -- -- dsimp [flip, function.comp], -- -- refl, -- have c : ∀ m, (M.reference' ((φ_v m).rw x t.val) (ass.bind x (M.reference' t.val ass))) = M.reference' (φ_v m) ass, -- focus { -- intro m, -- induction (φ_v m); -- dunfold term.rw; -- dunfold vasgn.bind, -- dunfold model.reference', -- by_cases h₂ : x = a; -- simp [h₂], -- obtain ⟨t, pt₁, pt₂⟩ := t, -- induction t, -- dunfold model.reference', -- simp, -- revert pt₁, -- dunfold term.denotes, -- dunfold term.vars, -- simp, -- revert pt₂, -- dunfold term.concrete, -- contradiction, -- simp, -- induction t_n; -- dunfold model.reference', -- -- dunfold model.reference', -- } -- end -- So pretty. theorem soundness : Γ ⊢ φ → Γ ⊨ φ := begin intros entails M ass h, induction entails, -- case reflexive exact h entails_φ entails_h, -- case transitivity apply entails_ih_h₂, intros ψ H, exact entails_ih_h₁ ψ H h, -- case and.intro have c₁ := entails_ih_h₁ h, have c₂ := entails_ih_h₂ h, exact ⟨c₁, c₂⟩, -- case and.elim_left have sat := entails_ih h, revert sat, dunfold model.satisfies', simp, intros sat aux, exact sat, -- case and.elim_right have sat := entails_ih h, revert sat, repeat {dunfold model.satisfies', simp}, left, exact entails_ih h, right, exact entails_ih h, -- case or_intro_left -- already solved -- case or_intro_right -- already solved -- case or_elim have c₁ := entails_ih_h₁ h, have c₂ := entails_ih_h₂ h, have c₃ := entails_ih_h₃ h, tactic.unfreeze_local_instances, dunfold model.satisfies' at *, simp at *, cases c₁, exact c₂ c₁, exact c₃ c₁, -- case modus ponens have c₁ := entails_ih_h₁ h, have c₂ := entails_ih_h₂ h, revert c₁, dunfold model.satisfies', simp, intro c₁, exact c₁ c₂, -- case intro intro h₂, have sat := entails_ih, apply sat, intros ψ H, cases H, exact h ψ H, simp at H, rwa H, -- case true.intro trivial, -- case universal intro -- intros x asg h₁ h₂, -- have sat := entails_ih h, -- focus { -- induction entails_φ; -- revert sat; -- dunfold uformula.rw; -- dunfold model.satisfies'; -- try{dunfold flip}; -- try{dunfold vector.of_fn}; -- try{dunfold vector.map}, -- intro sat, -- }, admit, -- case universal elim -- focus { -- induction entails_φ; -- have sat := entails_ih h; -- revert sat; -- dunfold uformula.rw; try{simp}, -- -- I cant go any further applying strategies to -- -- all goals because the linter gets very slow. -- dunfold model.satisfies', try{simp}, -- intro sat, -- }, admit, -- case exists intro have sat := entails_ih h, existsi M.reference' entails_t ass, intros asg h₁ h₂, admit, -- case exists elim admit, -- case identity intro -- already solved -- case identity elim admit, end end semantics section consistency end consistency end formulas end logic
0846b741dbc4528209ef58eb485b775f9a4dc8a7
1a61aba1b67cddccce19532a9596efe44be4285f
/hott/function.hlean
318f54eece56a623b32f4ae0583e9dd83f394a2b
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
4,438
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about embeddings and surjections -/ import hit.trunc types.equiv open equiv sigma sigma.ops eq trunc is_trunc pi is_equiv fiber prod variables {A B : Type} {f : A → B} {b : B} structure is_embedding [class] (f : A → B) := (elim : Π(a a' : A), is_equiv (ap f : a = a' → f a = f a')) structure is_surjective [class] (f : A → B) := (elim : Π(b : B), ∥ fiber f b ∥) structure is_split_surjective [class] (f : A → B) := (elim : Π(b : B), fiber f b) structure is_retraction [class] (f : A → B) := (sect : B → A) (right_inverse : Π(b : B), f (sect b) = b) definition is_weakly_constant [class] (f : A → B) (a a' : A) := f a = f a' structure is_constant [class] (f : A → B) := (pt : B) (eq : Π(a : A), f a = pt) structure conditionally_constant [class] (f : A → B) := (g : ∥A∥ → B) (eq : Π(a : A), f a = g (tr a)) namespace function attribute is_embedding.elim [instance] definition is_surjective_rec_on {P : Type} (H : is_surjective f) (b : B) [Pt : is_hprop P] (IH : fiber f b → P) : P := trunc.rec_on (is_surjective.elim f b) IH definition is_surjective_of_is_split_surjective [instance] [H : is_split_surjective f] : is_surjective f := is_surjective.mk (λb, tr (is_split_surjective.elim f b)) definition is_injective_of_is_embedding [reducible] [H : is_embedding f] {a a' : A} : f a = f a' → a = a' := (ap f)⁻¹ definition is_embedding_of_is_injective [HA : is_hset A] [HB : is_hset B] (H : Π(a a' : A), f a = f a' → a = a') : is_embedding f := begin fapply is_embedding.mk, intro a a', fapply adjointify, {exact (H a a')}, {intro p, apply is_hset.elim}, {intro p, apply is_hset.elim} end definition is_hprop_is_embedding [instance] (f : A → B) : is_hprop (is_embedding f) := begin have H : (Π(a a' : A), is_equiv (@ap A B f a a')) ≃ is_embedding f, begin fapply equiv.MK, {exact is_embedding.mk}, {intro h, cases h, exact elim}, {intro h, cases h, apply idp}, {intro p, apply idp}, end, apply is_trunc_equiv_closed, exact H, end definition is_hprop_is_surjective [instance] (f : A → B) : is_hprop (is_surjective f) := begin have H : (Π(b : B), merely (fiber f b)) ≃ is_surjective f, begin fapply equiv.MK, {exact is_surjective.mk}, {intro h, cases h, exact elim}, {intro h, cases h, apply idp}, {intro p, apply idp}, end, apply is_trunc_equiv_closed, exact H, end -- definition is_hprop_is_split_surjective [instance] (f : A → B) : is_hprop (is_split_surjective f) := -- begin -- have H : (Π(b : B), fiber f b) ≃ is_split_surjective f, -- begin -- fapply equiv.MK, -- {exact is_split_surjective.mk}, -- {intro h, cases h, exact elim}, -- {intro h, cases h, apply idp}, -- {intro p, apply idp}, -- end, -- apply is_trunc_equiv_closed, -- exact H, -- apply is_trunc_pi, intro b, -- apply is_trunc_equiv_closed_rev, -- apply fiber.sigma_char, -- end -- definition is_hprop_is_retraction [instance] (f : A → B) : is_hprop (is_retraction f) := -- begin -- have H : (Σ(g : B → A), Πb, f (g b) = b) ≃ is_retraction f, -- begin -- fapply equiv.MK, -- {intro x, induction x with g p, constructor, exact p}, -- {intro h, induction h, apply sigma.mk, assumption}, -- {intro h, induction h, reflexivity}, -- {intro x, induction x, reflexivity}, -- end, -- apply is_trunc_equiv_closed, -- exact H, -- apply is_trunc_of_imp_is_trunc, intro x, induction x with g p, -- apply is_contr_right_inverse -- end definition is_embedding_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_embedding f := is_embedding.mk _ definition is_equiv_of_is_surjective_of_is_embedding (f : A → B) [H : is_embedding f] [H' : is_surjective f] : is_equiv f := @is_equiv_of_is_contr_fun _ _ _ (λb, is_surjective_rec_on H' b (λa, is_contr.mk a (λa', fiber_eq ((ap f)⁻¹ ((point_eq a) ⬝ (point_eq a')⁻¹)) (by rewrite (right_inv (ap f)); rewrite inv_con_cancel_right)))) end function
70bc4257fade7c351fd6d665214c2be5077072fb
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab.lean
b6d22aa99b002b2d7753e33f55c3611c208a63c7
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
732
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Import import Lean.Elab.Exception import Lean.Elab.StrategyAttrs import Lean.Elab.Command import Lean.Elab.Term import Lean.Elab.App import Lean.Elab.Binders import Lean.Elab.LetRec import Lean.Elab.Quotation import Lean.Elab.Frontend import Lean.Elab.BuiltinNotation import Lean.Elab.Declaration import Lean.Elab.Tactic import Lean.Elab.Syntax import Lean.Elab.Match import Lean.Elab.Do import Lean.Elab.StructInst import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.Print import Lean.Elab.MutualDef import Lean.Elab.PreDefinition
324226e5c6cde69d2f3e94bc519a1dbc93f79e7c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Module/change_of_rings.lean
9d8c285ba51102861d8a50ea785e0967151683c7
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,242
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebra.category.Module.basic import ring_theory.tensor_product /-! # Change Of Rings ## Main definitions * `category_theory.Module.restrict_scalars`: given rings `R, S` and a ring homomorphism `R ⟶ S`, then `restrict_scalars : Module S ⥤ Module R` is defined by `M ↦ M` where `M : S-module` is seen as `R-module` by `r • m := f r • m` and `S`-linear map `l : M ⟶ M'` is `R`-linear as well. * `category_theory.Module.extend_scalars`: given **commutative** rings `R, S` and ring homomorphism `f : R ⟶ S`, then `extend_scalars : Module R ⥤ Module S` is defined by `M ↦ S ⨂ M` where the module structure is defined by `s • (s' ⊗ m) := (s * s') ⊗ m` and `R`-linear map `l : M ⟶ M'` is sent to `S`-linear map `s ⊗ m ↦ s ⊗ l m : S ⨂ M ⟶ S ⨂ M'`. ## List of notations Let `R, S` be rings and `f : R →+* S` * if `M` is an `R`-module, `s : S` and `m : M`, then `s ⊗ₜ[R, f] m` is the pure tensor `s ⊗ m : S ⊗[R, f] M`. -/ namespace category_theory.Module universes v u₁ u₂ namespace restrict_scalars variables {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) variable (M : Module.{v} S) /-- Any `S`-module M is also an `R`-module via a ring homomorphism `f : R ⟶ S` by defining `r • m := f r • m` (`module.comp_hom`). This is called restriction of scalars. -/ def obj' : Module R := { carrier := M, is_module := module.comp_hom M f } /-- Given an `S`-linear map `g : M → M'` between `S`-modules, `g` is also `R`-linear between `M` and `M'` by means of restriction of scalars. -/ def map' {M M' : Module.{v} S} (g : M ⟶ M') : obj' f M ⟶ obj' f M' := { map_smul' := λ r, g.map_smul (f r), ..g } end restrict_scalars /-- The restriction of scalars operation is functorial. For any `f : R →+* S` a ring homomorphism, * an `S`-module `M` can be considered as `R`-module by `r • m = f r • m` * an `S`-linear map is also `R`-linear -/ def restrict_scalars {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) : Module.{v} S ⥤ Module.{v} R := { obj := restrict_scalars.obj' f, map := λ _ _, restrict_scalars.map' f, map_id' := λ _, linear_map.ext $ λ m, rfl, map_comp' := λ _ _ _ g h, linear_map.ext $ λ m, rfl } @[simp] lemma restrict_scalars.map_apply {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) {M M' : Module.{v} S} (g : M ⟶ M') (x) : (restrict_scalars f).map g x = g x := rfl @[simp] lemma restrict_scalars.smul_def {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) {M : Module.{v} S} (r : R) (m : (restrict_scalars f).obj M) : r • m = (f r • m : M) := rfl lemma restrict_scalars.smul_def' {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) {M : Module.{v} S} (r : R) (m : M) : (r • m : (restrict_scalars f).obj M) = (f r • m : M) := rfl @[priority 100] instance smul_comm_class_mk {R : Type u₁} {S : Type u₂} [ring R] [comm_ring S] (f : R →+* S) (M : Type v) [add_comm_group M] [module S M] : @smul_comm_class R S M ((restrict_scalars.obj' f (Module.mk M)).is_module.to_has_smul) _ := { smul_comm := λ r s m, (by simp [←mul_smul, mul_comm] : f r • s • m = s • f r • m) } namespace extend_scalars open tensor_product variables {R : Type u₁} {S : Type u₂} [comm_ring R] [comm_ring S] (f : R →+* S) section unbundled variables (M : Type v) [add_comm_monoid M] [module R M] -- This notation is necessary because we need to reason about `s ⊗ₜ m` where `s : S` and `m : M`; -- without this notation, one need to work with `s : (restrict_scalars f).obj ⟨S⟩`. localized "notation s `⊗ₜ[` R `,` f `]` m := @tensor_product.tmul R _ _ _ _ _ (module.comp_hom _ f) _ s m" in change_of_rings end unbundled open_locale change_of_rings variables (M : Module.{v} R) /-- Extension of scalars turn an `R`-module into `S`-module by M ↦ S ⨂ M -/ def obj' : Module S := ⟨tensor_product R ((restrict_scalars f).obj ⟨S⟩) M⟩ /-- Extension of scalars is a functor where an `R`-module `M` is sent to `S ⊗ M` and `l : M1 ⟶ M2` is sent to `s ⊗ m ↦ s ⊗ l m` -/ def map' {M1 M2 : Module.{v} R} (l : M1 ⟶ M2) : (obj' f M1) ⟶ (obj' f M2) := -- The "by apply" part makes this require 75% fewer heartbeats to process (#16371). by apply (@linear_map.base_change R S M1 M2 _ _ ((algebra_map S _).comp f).to_algebra _ _ _ _ l) lemma map'_id {M : Module.{v} R} : map' f (𝟙 M) = 𝟙 _ := linear_map.ext $ λ (x : obj' f M), begin dsimp only [map', Module.id_apply], induction x using tensor_product.induction_on with _ _ m s ihx ihy, { simp only [map_zero], }, { rw [linear_map.base_change_tmul, Module.id_apply], }, { rw [map_add, ihx, ihy] }, end lemma map'_comp {M₁ M₂ M₃ : Module.{v} R} (l₁₂ : M₁ ⟶ M₂) (l₂₃ : M₂ ⟶ M₃) : map' f (l₁₂ ≫ l₂₃) = map' f l₁₂ ≫ map' f l₂₃ := linear_map.ext $ λ (x : obj' f M₁), begin dsimp only [map'], induction x using tensor_product.induction_on with _ _ x y ihx ihy, { refl, }, { refl, }, { simp only [map_add, ihx, ihy], }, end end extend_scalars /-- Extension of scalars is a functor where an `R`-module `M` is sent to `S ⊗ M` and `l : M1 ⟶ M2` is sent to `s ⊗ m ↦ s ⊗ l m` -/ def extend_scalars {R : Type u₁} {S : Type u₂} [comm_ring R] [comm_ring S] (f : R →+* S) : Module.{v} R ⥤ Module.{max v u₂} S := { obj := λ M, extend_scalars.obj' f M, map := λ M1 M2 l, extend_scalars.map' f l, map_id' := λ _, extend_scalars.map'_id f, map_comp' := λ _ _ _, extend_scalars.map'_comp f } namespace extend_scalars open_locale change_of_rings variables {R : Type u₁} {S : Type u₂} [comm_ring R] [comm_ring S] (f : R →+* S) @[simp] protected lemma smul_tmul {M : Module.{v} R} (s s' : S) (m : M) : s • (s' ⊗ₜ[R, f] m : (extend_scalars f).obj M) = (s * s') ⊗ₜ[R, f] m := rfl @[simp] lemma map_tmul {M M' : Module.{v} R} (g : M ⟶ M') (s : S) (m : M) : (extend_scalars f).map g (s ⊗ₜ[R, f] m) = s ⊗ₜ[R, f] g m := rfl end extend_scalars end category_theory.Module
24f7ce73df5830837e8ec227c4914921b1104ebc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/integral_eq_improper.lean
1cd7f2b27154178d2505f47df1a4e6816abf22ac
[ "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
48,248
lean
/- Copyright (c) 2021 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Bhavik Mehta -/ import analysis.special_functions.pow.deriv import measure_theory.integral.fund_thm_calculus import order.filter.at_top_bot import measure_theory.function.jacobian import measure_theory.measure.haar.normed_space /-! # Links between an integral and its "improper" version > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In its current state, mathlib only knows how to talk about definite ("proper") integrals, in the sense that it treats integrals over `[x, +∞)` the same as it treats integrals over `[y, z]`. For example, the integral over `[1, +∞)` is **not** defined to be the limit of the integral over `[1, x]` as `x` tends to `+∞`, which is known as an **improper integral**. Indeed, the "proper" definition is stronger than the "improper" one. The usual counterexample is `x ↦ sin(x)/x`, which has an improper integral over `[1, +∞)` but no definite integral. Although definite integrals have better properties, they are hardly usable when it comes to computing integrals on unbounded sets, which is much easier using limits. Thus, in this file, we prove various ways of studying the proper integral by studying the improper one. ## Definitions The main definition of this file is `measure_theory.ae_cover`. It is a rather technical definition whose sole purpose is generalizing and factoring proofs. Given an index type `ι`, a countably generated filter `l` over `ι`, and an `ι`-indexed family `φ` of subsets of a measurable space `α` equipped with a measure `μ`, one should think of a hypothesis `hφ : ae_cover μ l φ` as a sufficient condition for being able to interpret `∫ x, f x ∂μ` (if it exists) as the limit of `∫ x in φ i, f x ∂μ` as `i` tends to `l`. When using this definition with a measure restricted to a set `s`, which happens fairly often, one should not try too hard to use a `ae_cover` of subsets of `s`, as it often makes proofs more complicated than necessary. See for example the proof of `measure_theory.integrable_on_Iic_of_interval_integral_norm_tendsto` where we use `(λ x, Ioi x)` as an `ae_cover` w.r.t. `μ.restrict (Iic b)`, instead of using `(λ x, Ioc x b)`. ## Main statements - `measure_theory.ae_cover.lintegral_tendsto_of_countably_generated` : if `φ` is a `ae_cover μ l`, where `l` is a countably generated filter, and if `f` is a measurable `ennreal`-valued function, then `∫⁻ x in φ n, f x ∂μ` tends to `∫⁻ x, f x ∂μ` as `n` tends to `l` - `measure_theory.ae_cover.integrable_of_integral_norm_tendsto` : if `φ` is a `ae_cover μ l`, where `l` is a countably generated filter, if `f` is measurable and integrable on each `φ n`, and if `∫ x in φ n, ‖f x‖ ∂μ` tends to some `I : ℝ` as n tends to `l`, then `f` is integrable - `measure_theory.ae_cover.integral_tendsto_of_countably_generated` : if `φ` is a `ae_cover μ l`, where `l` is a countably generated filter, and if `f` is measurable and integrable (globally), then `∫ x in φ n, f x ∂μ` tends to `∫ x, f x ∂μ` as `n` tends to `+∞`. We then specialize these lemmas to various use cases involving intervals, which are frequent in analysis. In particular, - `measure_theory.integral_Ioi_of_has_deriv_at_of_tendsto` is a version of FTC-2 on the interval `(a, +∞)`, giving the formula `∫ x in (a, +∞), g' x = l - g a` if `g'` is integrable and `g` tends to `l` at `+∞`. - `measure_theory.integral_Ioi_of_has_deriv_at_of_nonneg` gives the same result assuming that `g'` is nonnegative instead of integrable. Its automatic integrability in this context is proved in `measure_theory.integrable_on_Ioi_deriv_of_nonneg`. - `measure_theory.integral_comp_smul_deriv_Ioi` is a version of the change of variables formula on semi-infinite intervals. -/ open measure_theory filter set topological_space open_locale ennreal nnreal topology namespace measure_theory section ae_cover variables {α ι : Type*} [measurable_space α] (μ : measure α) (l : filter ι) /-- A sequence `φ` of subsets of `α` is a `ae_cover` w.r.t. a measure `μ` and a filter `l` if almost every point (w.r.t. `μ`) of `α` eventually belongs to `φ n` (w.r.t. `l`), and if each `φ n` is measurable. This definition is a technical way to avoid duplicating a lot of proofs. It should be thought of as a sufficient condition for being able to interpret `∫ x, f x ∂μ` (if it exists) as the limit of `∫ x in φ n, f x ∂μ` as `n` tends to `l`. See for example `measure_theory.ae_cover.lintegral_tendsto_of_countably_generated`, `measure_theory.ae_cover.integrable_of_integral_norm_tendsto` and `measure_theory.ae_cover.integral_tendsto_of_countably_generated`. -/ structure ae_cover (φ : ι → set α) : Prop := (ae_eventually_mem : ∀ᵐ x ∂μ, ∀ᶠ i in l, x ∈ φ i) (measurable : ∀ i, measurable_set $ φ i) variables {μ} {l} section preorder_α variables [preorder α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b : ι → α} (ha : tendsto a l at_bot) (hb : tendsto b l at_top) lemma ae_cover_Icc : ae_cover μ l (λ i, Icc (a i) (b i)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha.eventually $ eventually_le_at_bot x).mp $ (hb.eventually $ eventually_ge_at_top x).mono $ λ i hbi hai, ⟨hai, hbi⟩ ), measurable := λ i, measurable_set_Icc } lemma ae_cover_Ici : ae_cover μ l (λ i, Ici $ a i) := { ae_eventually_mem := ae_of_all μ (λ x, (ha.eventually $ eventually_le_at_bot x).mono $ λ i hai, hai ), measurable := λ i, measurable_set_Ici } lemma ae_cover_Iic : ae_cover μ l (λ i, Iic $ b i) := { ae_eventually_mem := ae_of_all μ (λ x, (hb.eventually $ eventually_ge_at_top x).mono $ λ i hbi, hbi ), measurable := λ i, measurable_set_Iic } end preorder_α section linear_order_α variables [linear_order α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b : ι → α} (ha : tendsto a l at_bot) (hb : tendsto b l at_top) lemma ae_cover_Ioo [no_min_order α] [no_max_order α] : ae_cover μ l (λ i, Ioo (a i) (b i)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha.eventually $ eventually_lt_at_bot x).mp $ (hb.eventually $ eventually_gt_at_top x).mono $ λ i hbi hai, ⟨hai, hbi⟩ ), measurable := λ i, measurable_set_Ioo } lemma ae_cover_Ioc [no_min_order α] : ae_cover μ l (λ i, Ioc (a i) (b i)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha.eventually $ eventually_lt_at_bot x).mp $ (hb.eventually $ eventually_ge_at_top x).mono $ λ i hbi hai, ⟨hai, hbi⟩ ), measurable := λ i, measurable_set_Ioc } lemma ae_cover_Ico [no_max_order α] : ae_cover μ l (λ i, Ico (a i) (b i)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha.eventually $ eventually_le_at_bot x).mp $ (hb.eventually $ eventually_gt_at_top x).mono $ λ i hbi hai, ⟨hai, hbi⟩ ), measurable := λ i, measurable_set_Ico } lemma ae_cover_Ioi [no_min_order α] : ae_cover μ l (λ i, Ioi $ a i) := { ae_eventually_mem := ae_of_all μ (λ x, (ha.eventually $ eventually_lt_at_bot x).mono $ λ i hai, hai ), measurable := λ i, measurable_set_Ioi } lemma ae_cover_Iio [no_max_order α] : ae_cover μ l (λ i, Iio $ b i) := { ae_eventually_mem := ae_of_all μ (λ x, (hb.eventually $ eventually_gt_at_top x).mono $ λ i hbi, hbi ), measurable := λ i, measurable_set_Iio } end linear_order_α section finite_intervals variables [linear_order α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b : ι → α} {A B : α} (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) lemma ae_cover_Ioo_of_Icc : ae_cover (μ.restrict $ Ioo A B) l (λ i, Icc (a i) (b i)) := { ae_eventually_mem := (ae_restrict_iff' measurable_set_Ioo).mpr ( ae_of_all μ (λ x hx, (ha.eventually $ eventually_le_nhds hx.left).mp $ (hb.eventually $ eventually_ge_nhds hx.right).mono $ λ i hbi hai, ⟨hai, hbi⟩)), measurable := λ i, measurable_set_Icc, } lemma ae_cover_Ioo_of_Ico : ae_cover (μ.restrict $ Ioo A B) l (λ i, Ico (a i) (b i)) := { ae_eventually_mem := (ae_restrict_iff' measurable_set_Ioo).mpr ( ae_of_all μ (λ x hx, (ha.eventually $ eventually_le_nhds hx.left).mp $ (hb.eventually $ eventually_gt_nhds hx.right).mono $ λ i hbi hai, ⟨hai, hbi⟩)), measurable := λ i, measurable_set_Ico, } lemma ae_cover_Ioo_of_Ioc : ae_cover (μ.restrict $ Ioo A B) l (λ i, Ioc (a i) (b i)) := { ae_eventually_mem := (ae_restrict_iff' measurable_set_Ioo).mpr ( ae_of_all μ (λ x hx, (ha.eventually $ eventually_lt_nhds hx.left).mp $ (hb.eventually $ eventually_ge_nhds hx.right).mono $ λ i hbi hai, ⟨hai, hbi⟩)), measurable := λ i, measurable_set_Ioc, } lemma ae_cover_Ioo_of_Ioo : ae_cover (μ.restrict $ Ioo A B) l (λ i, Ioo (a i) (b i)) := { ae_eventually_mem := (ae_restrict_iff' measurable_set_Ioo).mpr ( ae_of_all μ (λ x hx, (ha.eventually $ eventually_lt_nhds hx.left).mp $ (hb.eventually $ eventually_gt_nhds hx.right).mono $ λ i hbi hai, ⟨hai, hbi⟩)), measurable := λ i, measurable_set_Ioo, } variables [has_no_atoms μ] lemma ae_cover_Ioc_of_Icc (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ioc A B) l (λ i, Icc (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ioc.symm, ae_cover_Ioo_of_Icc ha hb] lemma ae_cover_Ioc_of_Ico (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ioc A B) l (λ i, Ico (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ioc.symm, ae_cover_Ioo_of_Ico ha hb] lemma ae_cover_Ioc_of_Ioc (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ioc A B) l (λ i, Ioc (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ioc.symm, ae_cover_Ioo_of_Ioc ha hb] lemma ae_cover_Ioc_of_Ioo (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ioc A B) l (λ i, Ioo (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ioc.symm, ae_cover_Ioo_of_Ioo ha hb] lemma ae_cover_Ico_of_Icc (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ico A B) l (λ i, Icc (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ico.symm, ae_cover_Ioo_of_Icc ha hb] lemma ae_cover_Ico_of_Ico (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ico A B) l (λ i, Ico (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ico.symm, ae_cover_Ioo_of_Ico ha hb] lemma ae_cover_Ico_of_Ioc (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ico A B) l (λ i, Ioc (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ico.symm, ae_cover_Ioo_of_Ioc ha hb] lemma ae_cover_Ico_of_Ioo (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Ico A B) l (λ i, Ioo (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Ico.symm, ae_cover_Ioo_of_Ioo ha hb] lemma ae_cover_Icc_of_Icc (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Icc A B) l (λ i, Icc (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Icc.symm, ae_cover_Ioo_of_Icc ha hb] lemma ae_cover_Icc_of_Ico (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Icc A B) l (λ i, Ico (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Icc.symm, ae_cover_Ioo_of_Ico ha hb] lemma ae_cover_Icc_of_Ioc (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Icc A B) l (λ i, Ioc (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Icc.symm, ae_cover_Ioo_of_Ioc ha hb] lemma ae_cover_Icc_of_Ioo (ha : tendsto a l (𝓝 A)) (hb : tendsto b l (𝓝 B)) : ae_cover (μ.restrict $ Icc A B) l (λ i, Ioo (a i) (b i)) := by simp [measure.restrict_congr_set Ioo_ae_eq_Icc.symm, ae_cover_Ioo_of_Ioo ha hb] end finite_intervals lemma ae_cover.restrict {φ : ι → set α} (hφ : ae_cover μ l φ) {s : set α} : ae_cover (μ.restrict s) l φ := { ae_eventually_mem := ae_restrict_of_ae hφ.ae_eventually_mem, measurable := hφ.measurable } lemma ae_cover_restrict_of_ae_imp {s : set α} {φ : ι → set α} (hs : measurable_set s) (ae_eventually_mem : ∀ᵐ x ∂μ, x ∈ s → ∀ᶠ n in l, x ∈ φ n) (measurable : ∀ n, measurable_set $ φ n) : ae_cover (μ.restrict s) l φ := { ae_eventually_mem := by rwa ae_restrict_iff' hs, measurable := measurable } lemma ae_cover.inter_restrict {φ : ι → set α} (hφ : ae_cover μ l φ) {s : set α} (hs : measurable_set s) : ae_cover (μ.restrict s) l (λ i, φ i ∩ s) := ae_cover_restrict_of_ae_imp hs (hφ.ae_eventually_mem.mono (λ x hx hxs, hx.mono $ λ i hi, ⟨hi, hxs⟩)) (λ i, (hφ.measurable i).inter hs) lemma ae_cover.ae_tendsto_indicator {β : Type*} [has_zero β] [topological_space β] (f : α → β) {φ : ι → set α} (hφ : ae_cover μ l φ) : ∀ᵐ x ∂μ, tendsto (λ i, (φ i).indicator f x) l (𝓝 $ f x) := hφ.ae_eventually_mem.mono (λ x hx, tendsto_const_nhds.congr' $ hx.mono $ λ n hn, (indicator_of_mem hn _).symm) lemma ae_cover.ae_measurable {β : Type*} [measurable_space β] [l.is_countably_generated] [l.ne_bot] {f : α → β} {φ : ι → set α} (hφ : ae_cover μ l φ) (hfm : ∀ i, ae_measurable f (μ.restrict $ φ i)) : ae_measurable f μ := begin obtain ⟨u, hu⟩ := l.exists_seq_tendsto, have := ae_measurable_Union_iff.mpr (λ (n : ℕ), hfm (u n)), rwa measure.restrict_eq_self_of_ae_mem at this, filter_upwards [hφ.ae_eventually_mem] with x hx using let ⟨i, hi⟩ := (hu.eventually hx).exists in mem_Union.mpr ⟨i, hi⟩ end lemma ae_cover.ae_strongly_measurable {β : Type*} [topological_space β] [pseudo_metrizable_space β] [l.is_countably_generated] [l.ne_bot] {f : α → β} {φ : ι → set α} (hφ : ae_cover μ l φ) (hfm : ∀ i, ae_strongly_measurable f (μ.restrict $ φ i)) : ae_strongly_measurable f μ := begin obtain ⟨u, hu⟩ := l.exists_seq_tendsto, have := ae_strongly_measurable_Union_iff.mpr (λ (n : ℕ), hfm (u n)), rwa measure.restrict_eq_self_of_ae_mem at this, filter_upwards [hφ.ae_eventually_mem] with x hx using let ⟨i, hi⟩ := (hu.eventually hx).exists in mem_Union.mpr ⟨i, hi⟩ end end ae_cover lemma ae_cover.comp_tendsto {α ι ι' : Type*} [measurable_space α] {μ : measure α} {l : filter ι} {l' : filter ι'} {φ : ι → set α} (hφ : ae_cover μ l φ) {u : ι' → ι} (hu : tendsto u l' l) : ae_cover μ l' (φ ∘ u) := { ae_eventually_mem := hφ.ae_eventually_mem.mono (λ x hx, hu.eventually hx), measurable := λ i, hφ.measurable (u i) } section ae_cover_Union_Inter_countable variables {α ι : Type*} [countable ι] [measurable_space α] {μ : measure α} lemma ae_cover.bUnion_Iic_ae_cover [preorder ι] {φ : ι → set α} (hφ : ae_cover μ at_top φ) : ae_cover μ at_top (λ (n : ι), ⋃ k (h : k ∈ Iic n), φ k) := { ae_eventually_mem := hφ.ae_eventually_mem.mono (λ x h, h.mono (λ i hi, mem_bUnion right_mem_Iic hi)), measurable := λ i, measurable_set.bUnion (to_countable _) (λ n _, hφ.measurable n) } lemma ae_cover.bInter_Ici_ae_cover [semilattice_sup ι] [nonempty ι] {φ : ι → set α} (hφ : ae_cover μ at_top φ) : ae_cover μ at_top (λ (n : ι), ⋂ k (h : k ∈ Ici n), φ k) := { ae_eventually_mem := hφ.ae_eventually_mem.mono begin intros x h, rw eventually_at_top at *, rcases h with ⟨i, hi⟩, use i, intros j hj, exact mem_bInter (λ k hk, hi k (le_trans hj hk)), end, measurable := λ i, measurable_set.bInter (to_countable _) (λ n _, hφ.measurable n) } end ae_cover_Union_Inter_countable section lintegral variables {α ι : Type*} [measurable_space α] {μ : measure α} {l : filter ι} private lemma lintegral_tendsto_of_monotone_of_nat {φ : ℕ → set α} (hφ : ae_cover μ at_top φ) (hmono : monotone φ) {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) : tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) at_top (𝓝 $ ∫⁻ x, f x ∂μ) := let F := λ n, (φ n).indicator f in have key₁ : ∀ n, ae_measurable (F n) μ, from λ n, hfm.indicator (hφ.measurable n), have key₂ : ∀ᵐ (x : α) ∂μ, monotone (λ n, F n x), from ae_of_all _ (λ x i j hij, indicator_le_indicator_of_subset (hmono hij) (λ x, zero_le $ f x) x), have key₃ : ∀ᵐ (x : α) ∂μ, tendsto (λ n, F n x) at_top (𝓝 (f x)), from hφ.ae_tendsto_indicator f, (lintegral_tendsto_of_tendsto_of_monotone key₁ key₂ key₃).congr (λ n, lintegral_indicator f (hφ.measurable n)) lemma ae_cover.lintegral_tendsto_of_nat {φ : ℕ → set α} (hφ : ae_cover μ at_top φ) {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) : tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) at_top (𝓝 $ ∫⁻ x, f x ∂μ) := begin have lim₁ := lintegral_tendsto_of_monotone_of_nat (hφ.bInter_Ici_ae_cover) (λ i j hij, bInter_subset_bInter_left (Ici_subset_Ici.mpr hij)) hfm, have lim₂ := lintegral_tendsto_of_monotone_of_nat (hφ.bUnion_Iic_ae_cover) (λ i j hij, bUnion_subset_bUnion_left (Iic_subset_Iic.mpr hij)) hfm, have le₁ := λ n, lintegral_mono_set (bInter_subset_of_mem left_mem_Ici), have le₂ := λ n, lintegral_mono_set (subset_bUnion_of_mem right_mem_Iic), exact tendsto_of_tendsto_of_tendsto_of_le_of_le lim₁ lim₂ le₁ le₂ end lemma ae_cover.lintegral_tendsto_of_countably_generated [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) : tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) l (𝓝 $ ∫⁻ x, f x ∂μ) := tendsto_of_seq_tendsto (λ u hu, (hφ.comp_tendsto hu).lintegral_tendsto_of_nat hfm) lemma ae_cover.lintegral_eq_of_tendsto [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ≥0∞} (I : ℝ≥0∞) (hfm : ae_measurable f μ) (htendsto : tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) l (𝓝 I)) : ∫⁻ x, f x ∂μ = I := tendsto_nhds_unique (hφ.lintegral_tendsto_of_countably_generated hfm) htendsto lemma ae_cover.supr_lintegral_eq_of_countably_generated [nonempty ι] [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) : (⨆ (i : ι), ∫⁻ x in φ i, f x ∂μ) = ∫⁻ x, f x ∂μ := begin have := hφ.lintegral_tendsto_of_countably_generated hfm, refine csupr_eq_of_forall_le_of_forall_lt_exists_gt (λ i, lintegral_mono' measure.restrict_le_self le_rfl) (λ w hw, _), rcases exists_between hw with ⟨m, hm₁, hm₂⟩, rcases (eventually_ge_of_tendsto_gt hm₂ this).exists with ⟨i, hi⟩, exact ⟨i, lt_of_lt_of_le hm₁ hi⟩, end end lintegral section integrable variables {α ι E : Type*} [measurable_space α] {μ : measure α} {l : filter ι} [normed_add_comm_group E] lemma ae_cover.integrable_of_lintegral_nnnorm_bounded [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ) (hfm : ae_strongly_measurable f μ) (hbounded : ∀ᶠ i in l, ∫⁻ x in φ i, ‖f x‖₊ ∂μ ≤ ennreal.of_real I) : integrable f μ := begin refine ⟨hfm, (le_of_tendsto _ hbounded).trans_lt ennreal.of_real_lt_top⟩, exact hφ.lintegral_tendsto_of_countably_generated hfm.ennnorm end lemma ae_cover.integrable_of_lintegral_nnnorm_tendsto [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ) (hfm : ae_strongly_measurable f μ) (htendsto : tendsto (λ i, ∫⁻ x in φ i, ‖f x‖₊ ∂μ) l (𝓝 $ ennreal.of_real I)) : integrable f μ := begin refine hφ.integrable_of_lintegral_nnnorm_bounded (max 1 (I + 1)) hfm _, refine htendsto.eventually (ge_mem_nhds _), refine (ennreal.of_real_lt_of_real_iff (lt_max_of_lt_left zero_lt_one)).2 _, exact lt_max_of_lt_right (lt_add_one I), end lemma ae_cover.integrable_of_lintegral_nnnorm_bounded' [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ≥0) (hfm : ae_strongly_measurable f μ) (hbounded : ∀ᶠ i in l, ∫⁻ x in φ i, ‖f x‖₊ ∂μ ≤ I) : integrable f μ := hφ.integrable_of_lintegral_nnnorm_bounded I hfm (by simpa only [ennreal.of_real_coe_nnreal] using hbounded) lemma ae_cover.integrable_of_lintegral_nnnorm_tendsto' [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ≥0) (hfm : ae_strongly_measurable f μ) (htendsto : tendsto (λ i, ∫⁻ x in φ i, ‖f x‖₊ ∂μ) l (𝓝 I)) : integrable f μ := hφ.integrable_of_lintegral_nnnorm_tendsto I hfm (by simpa only [ennreal.of_real_coe_nnreal] using htendsto) lemma ae_cover.integrable_of_integral_norm_bounded [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ) (hfi : ∀ i, integrable_on f (φ i) μ) (hbounded : ∀ᶠ i in l, ∫ x in φ i, ‖f x‖ ∂μ ≤ I) : integrable f μ := begin have hfm : ae_strongly_measurable f μ := hφ.ae_strongly_measurable (λ i, (hfi i).ae_strongly_measurable), refine hφ.integrable_of_lintegral_nnnorm_bounded I hfm _, conv at hbounded in (integral _ _) { rw integral_eq_lintegral_of_nonneg_ae (ae_of_all _ (λ x, @norm_nonneg E _ (f x))) hfm.norm.restrict }, conv at hbounded in (ennreal.of_real _) { dsimp, rw ← coe_nnnorm, rw ennreal.of_real_coe_nnreal }, refine hbounded.mono (λ i hi, _), rw ←ennreal.of_real_to_real (ne_top_of_lt (hfi i).2), apply ennreal.of_real_le_of_real hi, end lemma ae_cover.integrable_of_integral_norm_tendsto [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ) (hfi : ∀ i, integrable_on f (φ i) μ) (htendsto : tendsto (λ i, ∫ x in φ i, ‖f x‖ ∂μ) l (𝓝 I)) : integrable f μ := let ⟨I', hI'⟩ := htendsto.is_bounded_under_le in hφ.integrable_of_integral_norm_bounded I' hfi hI' lemma ae_cover.integrable_of_integral_bounded_of_nonneg_ae [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ} (I : ℝ) (hfi : ∀ i, integrable_on f (φ i) μ) (hnng : ∀ᵐ x ∂μ, 0 ≤ f x) (hbounded : ∀ᶠ i in l, ∫ x in φ i, f x ∂μ ≤ I) : integrable f μ := hφ.integrable_of_integral_norm_bounded I hfi $ hbounded.mono $ λ i hi, (integral_congr_ae $ ae_restrict_of_ae $ hnng.mono $ λ x, real.norm_of_nonneg).le.trans hi lemma ae_cover.integrable_of_integral_tendsto_of_nonneg_ae [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ} (I : ℝ) (hfi : ∀ i, integrable_on f (φ i) μ) (hnng : ∀ᵐ x ∂μ, 0 ≤ f x) (htendsto : tendsto (λ i, ∫ x in φ i, f x ∂μ) l (𝓝 I)) : integrable f μ := let ⟨I', hI'⟩ := htendsto.is_bounded_under_le in hφ.integrable_of_integral_bounded_of_nonneg_ae I' hfi hnng hI' end integrable section integral variables {α ι E : Type*} [measurable_space α] {μ : measure α} {l : filter ι} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] lemma ae_cover.integral_tendsto_of_countably_generated [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (hfi : integrable f μ) : tendsto (λ i, ∫ x in φ i, f x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := suffices h : tendsto (λ i, ∫ (x : α), (φ i).indicator f x ∂μ) l (𝓝 (∫ (x : α), f x ∂μ)), by { convert h, ext n, rw integral_indicator (hφ.measurable n) }, tendsto_integral_filter_of_dominated_convergence (λ x, ‖f x‖) (eventually_of_forall $ λ i, hfi.ae_strongly_measurable.indicator $ hφ.measurable i) (eventually_of_forall $ λ i, ae_of_all _ $ λ x, norm_indicator_le_norm_self _ _) hfi.norm (hφ.ae_tendsto_indicator f) /-- Slight reformulation of `measure_theory.ae_cover.integral_tendsto_of_countably_generated`. -/ lemma ae_cover.integral_eq_of_tendsto [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : E) (hfi : integrable f μ) (h : tendsto (λ n, ∫ x in φ n, f x ∂μ) l (𝓝 I)) : ∫ x, f x ∂μ = I := tendsto_nhds_unique (hφ.integral_tendsto_of_countably_generated hfi) h lemma ae_cover.integral_eq_of_tendsto_of_nonneg_ae [l.ne_bot] [l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ} (I : ℝ) (hnng : 0 ≤ᵐ[μ] f) (hfi : ∀ n, integrable_on f (φ n) μ) (htendsto : tendsto (λ n, ∫ x in φ n, f x ∂μ) l (𝓝 I)) : ∫ x, f x ∂μ = I := have hfi' : integrable f μ, from hφ.integrable_of_integral_tendsto_of_nonneg_ae I hfi hnng htendsto, hφ.integral_eq_of_tendsto I hfi' htendsto end integral section integrable_of_interval_integral variables {ι E : Type*} {μ : measure ℝ} {l : filter ι} [filter.ne_bot l] [is_countably_generated l] [normed_add_comm_group E] {a b : ι → ℝ} {f : ℝ → E} lemma integrable_of_interval_integral_norm_bounded (I : ℝ) (hfi : ∀ i, integrable_on f (Ioc (a i) (b i)) μ) (ha : tendsto a l at_bot) (hb : tendsto b l at_top) (h : ∀ᶠ i in l, ∫ x in a i .. b i, ‖f x‖ ∂μ ≤ I) : integrable f μ := begin have hφ : ae_cover μ l _ := ae_cover_Ioc ha hb, refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp _), filter_upwards [ha.eventually (eventually_le_at_bot 0), hb.eventually (eventually_ge_at_top 0)] with i hai hbi ht, rwa ←interval_integral.integral_of_le (hai.trans hbi) end /-- If `f` is integrable on intervals `Ioc (a i) (b i)`, where `a i` tends to -∞ and `b i` tends to ∞, and `∫ x in a i .. b i, ‖f x‖ ∂μ` converges to `I : ℝ` along a filter `l`, then `f` is integrable on the interval (-∞, ∞) -/ lemma integrable_of_interval_integral_norm_tendsto (I : ℝ) (hfi : ∀ i, integrable_on f (Ioc (a i) (b i)) μ) (ha : tendsto a l at_bot) (hb : tendsto b l at_top) (h : tendsto (λ i, ∫ x in a i .. b i, ‖f x‖ ∂μ) l (𝓝 I)) : integrable f μ := let ⟨I', hI'⟩ := h.is_bounded_under_le in integrable_of_interval_integral_norm_bounded I' hfi ha hb hI' lemma integrable_on_Iic_of_interval_integral_norm_bounded (I b : ℝ) (hfi : ∀ i, integrable_on f (Ioc (a i) b) μ) (ha : tendsto a l at_bot) (h : ∀ᶠ i in l, (∫ x in a i .. b, ‖f x‖ ∂μ) ≤ I) : integrable_on f (Iic b) μ := begin have hφ : ae_cover (μ.restrict $ Iic b) l _ := ae_cover_Ioi ha, have hfi : ∀ i, integrable_on f (Ioi (a i)) (μ.restrict $ Iic b), { intro i, rw [integrable_on, measure.restrict_restrict (hφ.measurable i)], exact hfi i }, refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp _), filter_upwards [ha.eventually (eventually_le_at_bot b)] with i hai, rw [interval_integral.integral_of_le hai, measure.restrict_restrict (hφ.measurable i)], exact id end /-- If `f` is integrable on intervals `Ioc (a i) b`, where `a i` tends to -∞, and `∫ x in a i .. b, ‖f x‖ ∂μ` converges to `I : ℝ` along a filter `l`, then `f` is integrable on the interval (-∞, b) -/ lemma integrable_on_Iic_of_interval_integral_norm_tendsto (I b : ℝ) (hfi : ∀ i, integrable_on f (Ioc (a i) b) μ) (ha : tendsto a l at_bot) (h : tendsto (λ i, ∫ x in a i .. b, ‖f x‖ ∂μ) l (𝓝 I)) : integrable_on f (Iic b) μ := let ⟨I', hI'⟩ := h.is_bounded_under_le in integrable_on_Iic_of_interval_integral_norm_bounded I' b hfi ha hI' lemma integrable_on_Ioi_of_interval_integral_norm_bounded (I a : ℝ) (hfi : ∀ i, integrable_on f (Ioc a (b i)) μ) (hb : tendsto b l at_top) (h : ∀ᶠ i in l, (∫ x in a .. b i, ‖f x‖ ∂μ) ≤ I) : integrable_on f (Ioi a) μ := begin have hφ : ae_cover (μ.restrict $ Ioi a) l _ := ae_cover_Iic hb, have hfi : ∀ i, integrable_on f (Iic (b i)) (μ.restrict $ Ioi a), { intro i, rw [integrable_on, measure.restrict_restrict (hφ.measurable i), inter_comm], exact hfi i }, refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp _), filter_upwards [hb.eventually (eventually_ge_at_top a)] with i hbi, rw [interval_integral.integral_of_le hbi, measure.restrict_restrict (hφ.measurable i), inter_comm], exact id end /-- If `f` is integrable on intervals `Ioc a (b i)`, where `b i` tends to ∞, and `∫ x in a .. b i, ‖f x‖ ∂μ` converges to `I : ℝ` along a filter `l`, then `f` is integrable on the interval (a, ∞) -/ lemma integrable_on_Ioi_of_interval_integral_norm_tendsto (I a : ℝ) (hfi : ∀ i, integrable_on f (Ioc a (b i)) μ) (hb : tendsto b l at_top) (h : tendsto (λ i, ∫ x in a .. b i, ‖f x‖ ∂μ) l (𝓝 $ I)) : integrable_on f (Ioi a) μ := let ⟨I', hI'⟩ := h.is_bounded_under_le in integrable_on_Ioi_of_interval_integral_norm_bounded I' a hfi hb hI' lemma integrable_on_Ioc_of_interval_integral_norm_bounded {I a₀ b₀ : ℝ} (hfi : ∀ i, integrable_on f $ Ioc (a i) (b i)) (ha : tendsto a l $ 𝓝 a₀) (hb : tendsto b l $ 𝓝 b₀) (h : ∀ᶠ i in l, (∫ x in Ioc (a i) (b i), ‖f x‖) ≤ I) : integrable_on f (Ioc a₀ b₀) := begin refine (ae_cover_Ioc_of_Ioc ha hb).integrable_of_integral_norm_bounded I (λ i, (hfi i).restrict measurable_set_Ioc) (eventually.mono h _), intros i hi, simp only [measure.restrict_restrict measurable_set_Ioc], refine le_trans (set_integral_mono_set (hfi i).norm _ _) hi, { apply ae_of_all, simp only [pi.zero_apply, norm_nonneg, forall_const] }, { apply ae_of_all, intros c hc, exact hc.1 }, end lemma integrable_on_Ioc_of_interval_integral_norm_bounded_left {I a₀ b : ℝ} (hfi : ∀ i, integrable_on f $ Ioc (a i) b) (ha : tendsto a l $ 𝓝 a₀) (h : ∀ᶠ i in l, (∫ x in Ioc (a i) b, ‖f x‖) ≤ I) : integrable_on f (Ioc a₀ b) := integrable_on_Ioc_of_interval_integral_norm_bounded hfi ha tendsto_const_nhds h lemma integrable_on_Ioc_of_interval_integral_norm_bounded_right {I a b₀ : ℝ} (hfi : ∀ i, integrable_on f $ Ioc a (b i)) (hb : tendsto b l $ 𝓝 b₀) (h : ∀ᶠ i in l, (∫ x in Ioc a (b i), ‖f x‖ ) ≤ I) : integrable_on f (Ioc a b₀) := integrable_on_Ioc_of_interval_integral_norm_bounded hfi tendsto_const_nhds hb h end integrable_of_interval_integral section integral_of_interval_integral variables {ι E : Type*} {μ : measure ℝ} {l : filter ι} [is_countably_generated l] [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {a b : ι → ℝ} {f : ℝ → E} lemma interval_integral_tendsto_integral (hfi : integrable f μ) (ha : tendsto a l at_bot) (hb : tendsto b l at_top) : tendsto (λ i, ∫ x in a i .. b i, f x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := begin let φ := λ i, Ioc (a i) (b i), have hφ : ae_cover μ l φ := ae_cover_Ioc ha hb, refine (hφ.integral_tendsto_of_countably_generated hfi).congr' _, filter_upwards [ha.eventually (eventually_le_at_bot 0), hb.eventually (eventually_ge_at_top 0)] with i hai hbi, exact (interval_integral.integral_of_le (hai.trans hbi)).symm end lemma interval_integral_tendsto_integral_Iic (b : ℝ) (hfi : integrable_on f (Iic b) μ) (ha : tendsto a l at_bot) : tendsto (λ i, ∫ x in a i .. b, f x ∂μ) l (𝓝 $ ∫ x in Iic b, f x ∂μ) := begin let φ := λ i, Ioi (a i), have hφ : ae_cover (μ.restrict $ Iic b) l φ := ae_cover_Ioi ha, refine (hφ.integral_tendsto_of_countably_generated hfi).congr' _, filter_upwards [ha.eventually (eventually_le_at_bot $ b)] with i hai, rw [interval_integral.integral_of_le hai, measure.restrict_restrict (hφ.measurable i)], refl, end lemma interval_integral_tendsto_integral_Ioi (a : ℝ) (hfi : integrable_on f (Ioi a) μ) (hb : tendsto b l at_top) : tendsto (λ i, ∫ x in a .. b i, f x ∂μ) l (𝓝 $ ∫ x in Ioi a, f x ∂μ) := begin let φ := λ i, Iic (b i), have hφ : ae_cover (μ.restrict $ Ioi a) l φ := ae_cover_Iic hb, refine (hφ.integral_tendsto_of_countably_generated hfi).congr' _, filter_upwards [hb.eventually (eventually_ge_at_top $ a)] with i hbi, rw [interval_integral.integral_of_le hbi, measure.restrict_restrict (hφ.measurable i), inter_comm], refl, end end integral_of_interval_integral open real open_locale interval section Ioi_FTC variables {E : Type*} {f f' : ℝ → E} {g g' : ℝ → ℝ} {a b l : ℝ} {m : E} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] /-- **Fundamental theorem of calculus-2**, on semi-infinite intervals `(a, +∞)`. When a function has a limit at infinity `m`, and its derivative is integrable, then the integral of the derivative on `(a, +∞)` is `m - f a`. Version assuming differentiability on `(a, +∞)` and continuity on `[a, +∞)`.-/ lemma integral_Ioi_of_has_deriv_at_of_tendsto (hcont : continuous_on f (Ici a)) (hderiv : ∀ x ∈ Ioi a, has_deriv_at f (f' x) x) (f'int : integrable_on f' (Ioi a)) (hf : tendsto f at_top (𝓝 m)) : ∫ x in Ioi a, f' x = m - f a := begin refine tendsto_nhds_unique (interval_integral_tendsto_integral_Ioi a f'int tendsto_id) _, apply tendsto.congr' _ (hf.sub_const _), filter_upwards [Ioi_mem_at_top a] with x hx, have h'x : a ≤ id x := le_of_lt hx, symmetry, apply interval_integral.integral_eq_sub_of_has_deriv_at_of_le h'x (hcont.mono Icc_subset_Ici_self) (λ y hy, hderiv y hy.1), rw interval_integrable_iff_integrable_Ioc_of_le h'x, exact f'int.mono (λ y hy, hy.1) le_rfl, end /-- **Fundamental theorem of calculus-2**, on semi-infinite intervals `(a, +∞)`. When a function has a limit at infinity `m`, and its derivative is integrable, then the integral of the derivative on `(a, +∞)` is `m - f a`. Version assuming differentiability on `[a, +∞)`. -/ lemma integral_Ioi_of_has_deriv_at_of_tendsto' (hderiv : ∀ x ∈ Ici a, has_deriv_at f (f' x) x) (f'int : integrable_on f' (Ioi a)) (hf : tendsto f at_top (𝓝 m)) : ∫ x in Ioi a, f' x = m - f a := begin apply integral_Ioi_of_has_deriv_at_of_tendsto _ (λ x hx, hderiv x (le_of_lt hx)) f'int hf, assume x hx, exact (hderiv x hx).continuous_at.continuous_within_at, end /-- When a function has a limit at infinity, and its derivative is nonnegative, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `(a, +∞)` and continuity on `[a, +∞)`. -/ lemma integrable_on_Ioi_deriv_of_nonneg (hcont : continuous_on g (Ici a)) (hderiv : ∀ x ∈ Ioi a, has_deriv_at g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : tendsto g at_top (𝓝 l)) : integrable_on g' (Ioi a) := begin apply integrable_on_Ioi_of_interval_integral_norm_tendsto (l - g a) a (λ x, _) tendsto_id, swap, { exact interval_integral.integrable_on_deriv_of_nonneg (hcont.mono Icc_subset_Ici_self) (λ y hy, hderiv y hy.1) (λ y hy, g'pos y hy.1) }, apply tendsto.congr' _ (hg.sub_const _), filter_upwards [Ioi_mem_at_top a] with x hx, have h'x : a ≤ id x := le_of_lt hx, calc g x - g a = ∫ y in a..id x, g' y : begin symmetry, apply interval_integral.integral_eq_sub_of_has_deriv_at_of_le h'x (hcont.mono Icc_subset_Ici_self) (λ y hy, hderiv y hy.1), rw interval_integrable_iff_integrable_Ioc_of_le h'x, exact interval_integral.integrable_on_deriv_of_nonneg (hcont.mono Icc_subset_Ici_self) (λ y hy, hderiv y hy.1) (λ y hy, g'pos y hy.1) end ... = ∫ y in a..id x, ‖g' y‖ : begin simp_rw interval_integral.integral_of_le h'x, refine set_integral_congr (measurable_set_Ioc) (λ y hy, _), dsimp, rw abs_of_nonneg, exact g'pos _ hy.1, end end /-- When a function has a limit at infinity, and its derivative is nonnegative, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `[a, +∞)`. -/ lemma integrable_on_Ioi_deriv_of_nonneg' (hderiv : ∀ x ∈ Ici a, has_deriv_at g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : tendsto g at_top (𝓝 l)) : integrable_on g' (Ioi a) := begin apply integrable_on_Ioi_deriv_of_nonneg _ (λ x hx, hderiv x (le_of_lt hx)) g'pos hg, assume x hx, exact (hderiv x hx).continuous_at.continuous_within_at, end /-- When a function has a limit at infinity `l`, and its derivative is nonnegative, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg`). Version assuming differentiability on `(a, +∞)` and continuity on `[a, +∞)`. -/ lemma integral_Ioi_of_has_deriv_at_of_nonneg (hcont : continuous_on g (Ici a)) (hderiv : ∀ x ∈ Ioi a, has_deriv_at g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : tendsto g at_top (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_has_deriv_at_of_tendsto hcont hderiv (integrable_on_Ioi_deriv_of_nonneg hcont hderiv g'pos hg) hg /-- When a function has a limit at infinity `l`, and its derivative is nonnegative, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg'`). Version assuming differentiability on `[a, +∞)`. -/ lemma integral_Ioi_of_has_deriv_at_of_nonneg' (hderiv : ∀ x ∈ Ici a, has_deriv_at g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : tendsto g at_top (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_has_deriv_at_of_tendsto' hderiv (integrable_on_Ioi_deriv_of_nonneg' hderiv g'pos hg) hg /-- When a function has a limit at infinity, and its derivative is nonpositive, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `(a, +∞)` and continuity on `[a, +∞)`. -/ lemma integrable_on_Ioi_deriv_of_nonpos (hcont : continuous_on g (Ici a)) (hderiv : ∀ x ∈ Ioi a, has_deriv_at g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : tendsto g at_top (𝓝 l)) : integrable_on g' (Ioi a) := begin apply integrable_neg_iff.1, exact integrable_on_Ioi_deriv_of_nonneg hcont.neg (λ x hx, (hderiv x hx).neg) (λ x hx, neg_nonneg_of_nonpos (g'neg x hx)) hg.neg, end /-- When a function has a limit at infinity, and its derivative is nonpositive, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `[a, +∞)`. -/ lemma integrable_on_Ioi_deriv_of_nonpos' (hderiv : ∀ x ∈ Ici a, has_deriv_at g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : tendsto g at_top (𝓝 l)) : integrable_on g' (Ioi a) := begin apply integrable_on_Ioi_deriv_of_nonpos _ (λ x hx, hderiv x (le_of_lt hx)) g'neg hg, assume x hx, exact (hderiv x hx).continuous_at.continuous_within_at, end /-- When a function has a limit at infinity `l`, and its derivative is nonpositive, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg`). Version assuming differentiability on `(a, +∞)` and continuity on `[a, +∞)`. -/ lemma integral_Ioi_of_has_deriv_at_of_nonpos (hcont : continuous_on g (Ici a)) (hderiv : ∀ x ∈ Ioi a, has_deriv_at g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : tendsto g at_top (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_has_deriv_at_of_tendsto hcont hderiv (integrable_on_Ioi_deriv_of_nonpos hcont hderiv g'neg hg) hg /-- When a function has a limit at infinity `l`, and its derivative is nonpositive, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg'`). Version assuming differentiability on `[a, +∞)`. -/ lemma integral_Ioi_of_has_deriv_at_of_nonpos' (hderiv : ∀ x ∈ Ici a, has_deriv_at g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : tendsto g at_top (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_has_deriv_at_of_tendsto' hderiv (integrable_on_Ioi_deriv_of_nonpos' hderiv g'neg hg) hg end Ioi_FTC section Ioi_change_variables open real open_locale interval variables {E : Type*} {f : ℝ → E} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] /-- Change-of-variables formula for `Ioi` integrals of vector-valued functions, proved by taking limits from the result for finite intervals. -/ lemma integral_comp_smul_deriv_Ioi {f f' : ℝ → ℝ} {g : ℝ → E} {a : ℝ} (hf : continuous_on f $ Ici a) (hft : tendsto f at_top at_top) (hff' : ∀ x ∈ Ioi a, has_deriv_within_at f (f' x) (Ioi x) x) (hg_cont : continuous_on g $ f '' Ioi a) (hg1 : integrable_on g $ f '' Ici a) (hg2 : integrable_on (λ x, f' x • (g ∘ f) x) (Ici a)) : ∫ x in Ioi a, f' x • (g ∘ f) x = ∫ u in Ioi (f a), g u := begin have eq : ∀ b : ℝ, a < b → ∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a .. f b, g u, { intros b hb, have i1 : Ioo (min a b) (max a b) ⊆ Ioi a, { rw min_eq_left hb.le, exact Ioo_subset_Ioi_self }, have i2 : [a, b] ⊆ Ici a, { rw uIcc_of_le hb.le, exact Icc_subset_Ici_self }, refine interval_integral.integral_comp_smul_deriv''' (hf.mono i2) (λ x hx, hff' x $ mem_of_mem_of_subset hx i1) (hg_cont.mono $ image_subset _ _) (hg1.mono_set $ image_subset _ _) (hg2.mono_set i2), { rw min_eq_left hb.le, exact Ioo_subset_Ioi_self }, { rw uIcc_of_le hb.le, exact Icc_subset_Ici_self } }, rw integrable_on_Ici_iff_integrable_on_Ioi at hg2, have t2 := interval_integral_tendsto_integral_Ioi _ hg2 tendsto_id, have : Ioi (f a) ⊆ f '' Ici a := (Ioi_subset_Ici_self.trans $ is_preconnected.intermediate_value_Ici is_preconnected_Ici left_mem_Ici (le_principal_iff.mpr $ Ici_mem_at_top _) hf hft), have t1 := (interval_integral_tendsto_integral_Ioi _ (hg1.mono_set this) tendsto_id).comp hft, exact tendsto_nhds_unique (tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top a) eq) t2) t1, end /-- Change-of-variables formula for `Ioi` integrals of scalar-valued functions -/ lemma integral_comp_mul_deriv_Ioi {f f' : ℝ → ℝ} {g : ℝ → ℝ} {a : ℝ} (hf : continuous_on f $ Ici a) (hft : tendsto f at_top at_top) (hff' : ∀ x ∈ Ioi a, has_deriv_within_at f (f' x) (Ioi x) x) (hg_cont : continuous_on g $ f '' Ioi a) (hg1 : integrable_on g $ f '' Ici a) (hg2 : integrable_on (λ x, (g ∘ f) x * f' x) (Ici a)) : ∫ x in Ioi a, (g ∘ f) x * f' x = ∫ u in Ioi (f a), g u := begin have hg2' : integrable_on (λ x, f' x • (g ∘ f) x) (Ici a) := by simpa [mul_comm] using hg2, simpa [mul_comm] using integral_comp_smul_deriv_Ioi hf hft hff' hg_cont hg1 hg2', end /-- Substitution `y = x ^ p` in integrals over `Ioi 0` -/ lemma integral_comp_rpow_Ioi (g : ℝ → E) {p : ℝ} (hp : p ≠ 0) : ∫ x in Ioi 0, (|p| * x ^ (p - 1)) • g (x ^ p) = ∫ y in Ioi 0, g y := begin let S := Ioi (0 : ℝ), have a1 : ∀ x:ℝ, x ∈ S → has_deriv_within_at (λ (t:ℝ), t ^ p) (p * x ^ (p - 1)) S x := λ x hx, (has_deriv_at_rpow_const (or.inl (mem_Ioi.mp hx).ne')).has_deriv_within_at, have a2 : inj_on (λ x:ℝ, x ^ p) S, { rcases lt_or_gt_of_ne hp, { apply strict_anti_on.inj_on, intros x hx y hy hxy, rw [←inv_lt_inv (rpow_pos_of_pos hx p) (rpow_pos_of_pos hy p), ←rpow_neg (le_of_lt hx), ←rpow_neg (le_of_lt hy)], exact rpow_lt_rpow (le_of_lt hx) hxy (neg_pos.mpr h), }, exact strict_mono_on.inj_on (λ x hx y hy hxy, rpow_lt_rpow (mem_Ioi.mp hx).le hxy h),}, have a3 : (λ (t : ℝ), t ^ p) '' S = S, { ext1, rw mem_image, split, { rintro ⟨y, hy, rfl⟩, exact rpow_pos_of_pos hy p }, { intro hx, refine ⟨x ^ (1 / p), rpow_pos_of_pos hx _, _⟩, rw [←rpow_mul (le_of_lt hx), one_div_mul_cancel hp, rpow_one], } }, have := integral_image_eq_integral_abs_deriv_smul measurable_set_Ioi a1 a2 g, rw a3 at this, rw this, refine set_integral_congr measurable_set_Ioi _, intros x hx, dsimp only, rw [abs_mul, abs_of_nonneg (rpow_nonneg_of_nonneg (le_of_lt hx) _)], end lemma integral_comp_rpow_Ioi_of_pos {g : ℝ → E} {p : ℝ} (hp : 0 < p) : ∫ x in Ioi 0, (p * x ^ (p - 1)) • g (x ^ p) = ∫ y in Ioi 0, g y := begin convert integral_comp_rpow_Ioi g hp.ne', funext, congr, rw abs_of_nonneg hp.le, end lemma integral_comp_mul_left_Ioi (g : ℝ → E) (a : ℝ) {b : ℝ} (hb : 0 < b) : ∫ x in Ioi a, g (b * x) = |b⁻¹| • ∫ x in Ioi (b * a), g x := begin have : ∀ c : ℝ, measurable_set (Ioi c) := λ c, measurable_set_Ioi, rw [←integral_indicator (this a), ←integral_indicator (this $ b * a)], convert measure.integral_comp_mul_left _ b, ext1 x, rw [←indicator_comp_right, preimage_const_mul_Ioi _ hb, mul_div_cancel_left _ hb.ne'], end lemma integral_comp_mul_right_Ioi (g : ℝ → E) (a : ℝ) {b : ℝ} (hb : 0 < b) : ∫ x in Ioi a, g (x * b) = |b⁻¹| • ∫ x in Ioi (a * b), g x := by simpa only [mul_comm] using integral_comp_mul_left_Ioi g a hb end Ioi_change_variables section Ioi_integrability open real open_locale interval variables {E : Type*} [normed_add_comm_group E] /-- The substitution `y = x ^ p` in integrals over `Ioi 0` preserves integrability. -/ lemma integrable_on_Ioi_comp_rpow_iff [normed_space ℝ E] (f : ℝ → E) {p : ℝ} (hp : p ≠ 0) : integrable_on (λ x, (|p| * x ^ (p - 1)) • f (x ^ p)) (Ioi 0) ↔ integrable_on f (Ioi 0) := begin let S := Ioi (0 : ℝ), have a1 : ∀ x:ℝ, x ∈ S → has_deriv_within_at (λ (t:ℝ), t ^ p) (p * x ^ (p - 1)) S x := λ x hx, (has_deriv_at_rpow_const (or.inl (mem_Ioi.mp hx).ne')).has_deriv_within_at, have a2 : inj_on (λ x:ℝ, x ^ p) S, { rcases lt_or_gt_of_ne hp, { apply strict_anti_on.inj_on, intros x hx y hy hxy, rw [←inv_lt_inv (rpow_pos_of_pos hx p) (rpow_pos_of_pos hy p), ←rpow_neg (le_of_lt hx), ←rpow_neg (le_of_lt hy)], exact rpow_lt_rpow (le_of_lt hx) hxy (neg_pos.mpr h), }, exact strict_mono_on.inj_on (λ x hx y hy hxy, rpow_lt_rpow (mem_Ioi.mp hx).le hxy h) }, have a3 : (λ (t : ℝ), t ^ p) '' S = S, { ext1, rw mem_image, split, { rintro ⟨y, hy, rfl⟩, exact rpow_pos_of_pos hy p }, { intro hx, refine ⟨x ^ (1 / p), rpow_pos_of_pos hx _, _⟩, rw [←rpow_mul (le_of_lt hx), one_div_mul_cancel hp, rpow_one], } }, have := integrable_on_image_iff_integrable_on_abs_deriv_smul measurable_set_Ioi a1 a2 f, rw a3 at this, rw this, refine integrable_on_congr_fun (λ x hx, _) measurable_set_Ioi, simp_rw [abs_mul, abs_of_nonneg (rpow_nonneg_of_nonneg (le_of_lt hx) _)], end /-- The substitution `y = x ^ p` in integrals over `Ioi 0` preserves integrability (version without `|p|` factor) -/ lemma integrable_on_Ioi_comp_rpow_iff' [normed_space ℝ E] (f : ℝ → E) {p : ℝ} (hp : p ≠ 0) : integrable_on (λ x, x ^ (p - 1) • f (x ^ p)) (Ioi 0) ↔ integrable_on f (Ioi 0) := by simpa only [←integrable_on_Ioi_comp_rpow_iff f hp, mul_smul] using (integrable_smul_iff (abs_pos.mpr hp).ne' _).symm lemma integrable_on_Ioi_comp_mul_left_iff (f : ℝ → E) (c : ℝ) {a : ℝ} (ha : 0 < a) : integrable_on (λ x, f (a * x)) (Ioi c) ↔ integrable_on f (Ioi $ a * c) := begin rw [←integrable_indicator_iff (measurable_set_Ioi : measurable_set $ Ioi c)], rw [←integrable_indicator_iff (measurable_set_Ioi : measurable_set $ Ioi $ a * c)], convert integrable_comp_mul_left_iff ((Ioi (a * c)).indicator f) ha.ne' using 2, ext1 x, rw [←indicator_comp_right, preimage_const_mul_Ioi _ ha, mul_comm a c, mul_div_cancel _ ha.ne'], end lemma integrable_on_Ioi_comp_mul_right_iff (f : ℝ → E) (c : ℝ) {a : ℝ} (ha : 0 < a) : integrable_on (λ x, f (x * a)) (Ioi c) ↔ integrable_on f (Ioi $ c * a) := by simpa only [mul_comm, mul_zero] using integrable_on_Ioi_comp_mul_left_iff f c ha end Ioi_integrability end measure_theory
60f362482b3fcaafa5d9bfc61c9dcb2e2b352b8f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/nat/choose/basic.lean
f2b2422bf65bd5558f767d3519cb8d4fbff6a604
[ "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
10,317
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Bhavik Mehta -/ import data.nat.factorial /-! # Binomial coefficients This file defines binomial coefficients and proves simple lemmas (i.e. those not requiring more imports). ## Main definition and results * `nat.choose`: binomial coefficients, defined inductively * `nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)` * `nat.choose_symm`: symmetry of binomial coefficients * `nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k` * `nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2` * `nat.desc_factorial_eq_factorial_mul_choose`: Relates binomial coefficients to the descending factorial. This is used to prove `nat.choose_le_pow` and variants. We provide similar statements for the ascending factorial. -/ open_locale nat namespace nat /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (k + 1) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose, add_comm] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, nat.add_sub_cancel, mul_comm], cases n; refl, apply zero_lt_succ end /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := begin induction n with n ih, simp, {rw triangle_succ n, simp [choose, ih], rw add_comm}, end lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_factorial_mul_factorial : ∀ {n k}, k ≤ n → choose n k * k! * (n - k)! = n! | 0 _ hk := by simp [eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * k.succ! * (n-k)! = k.succ * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_succ_le_succ hk); simp [factorial_succ, mul_comm, mul_left_comm], have h₁ : (n - k)! = (n - k) * (n - k.succ)! := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), factorial_succ], have h₂ : choose n (succ k) * k.succ! * ((n - k) * (n - k.succ)!) = (n - k) * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_lt_succ hk₁); simp [factorial_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * n! ≤ n * n! := mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib, factorial_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, nat.sub_self] } end theorem choose_eq_factorial_div_factorial {n k : ℕ} (hk : k ≤ n) : choose n k = n! / (k! * (n - k)!) := begin rw [← choose_mul_factorial_mul_factorial hk, mul_assoc], exact (mul_div_left _ (mul_pos (factorial_pos _) (factorial_pos _))).symm end lemma add_choose (i j : ℕ) : (i + j).choose j = (i + j)! / (i! * j!) := by rw [choose_eq_factorial_div_factorial (le_add_left j i), nat.add_sub_cancel, mul_comm] lemma add_choose_mul_factorial_mul_factorial (i j : ℕ) : (i + j).choose j * i! * j! = (i + j)! := by rw [← choose_mul_factorial_mul_factorial (le_add_left _ _), nat.add_sub_cancel, mul_right_comm] theorem factorial_mul_factorial_dvd_factorial {n k : ℕ} (hk : k ≤ n) : k! * (n - k)! ∣ n! := by rw [←choose_mul_factorial_mul_factorial hk, mul_assoc]; exact dvd_mul_left _ _ lemma factorial_mul_factorial_dvd_factorial_add (i j : ℕ) : i! * j! ∣ (i + j)! := begin convert factorial_mul_factorial_dvd_factorial (le.intro rfl), rw nat.add_sub_cancel_left end @[simp] lemma choose_symm {n k : ℕ} (hk : k ≤ n) : choose n (n-k) = choose n k := by rw [choose_eq_factorial_div_factorial hk, choose_eq_factorial_div_factorial (sub_le _ _), nat.sub_sub_self hk, mul_comm] lemma choose_symm_of_eq_add {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := by { convert nat.choose_symm (nat.le_add_left _ _), rw nat.add_sub_cancel} lemma choose_symm_add {a b : ℕ} : choose (a+b) a = choose (a+b) b := choose_symm_of_eq_add rfl lemma choose_symm_half (m : ℕ) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by { apply choose_symm_of_eq_add, rw [add_comm m 1, add_assoc 1 m m, add_comm (2 * m) 1, two_mul m] } lemma choose_succ_right_eq (n k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := begin have e : (n+1) * choose n k = choose n k * (k+1) + choose n (k+1) * (k+1), rw [← right_distrib, ← choose_succ_succ, succ_mul_choose_eq], rw [← nat.sub_eq_of_eq_add e, mul_comm, ← nat.mul_sub_left_distrib, nat.add_sub_add_right] end @[simp] lemma choose_succ_self_right : ∀ (n:ℕ), (n+1).choose n = n+1 | 0 := rfl | (n+1) := by rw [choose_succ_succ, choose_succ_self_right, choose_self] lemma choose_mul_succ_eq (n k : ℕ) : (n.choose k) * (n + 1) = ((n+1).choose k) * (n + 1 - k) := begin induction k with k ih, { simp }, obtain hk | hk := le_or_lt (k + 1) (n + 1), { rw [choose_succ_succ, add_mul, succ_sub_succ, ←choose_succ_right_eq, ←succ_sub_succ, nat.mul_sub_left_distrib, nat.add_sub_cancel' (mul_le_mul_left _ hk)] }, rw [choose_eq_zero_of_lt hk, choose_eq_zero_of_lt (n.lt_succ_self.trans hk), zero_mul, zero_mul], end lemma asc_factorial_eq_factorial_mul_choose (n k : ℕ) : n.asc_factorial k = k! * (n + k).choose k := begin rw mul_comm, apply mul_right_cancel' (factorial_ne_zero (n + k - k)), rw [choose_mul_factorial_mul_factorial, nat.add_sub_cancel, ←factorial_mul_asc_factorial, mul_comm], exact le_add_left k n, end lemma factorial_dvd_asc_factorial (n k : ℕ) : k! ∣ n.asc_factorial k := ⟨(n+k).choose k, asc_factorial_eq_factorial_mul_choose _ _⟩ lemma choose_eq_asc_factorial_div_factorial (n k : ℕ) : (n + k).choose k = n.asc_factorial k / k! := begin apply mul_left_cancel' (factorial_ne_zero k), rw ←asc_factorial_eq_factorial_mul_choose, exact (nat.mul_div_cancel' $ factorial_dvd_asc_factorial _ _).symm, end lemma desc_factorial_eq_factorial_mul_choose (n k : ℕ) : n.desc_factorial k = k! * n.choose k := begin obtain h | h := nat.lt_or_ge n k, { rw [desc_factorial_eq_zero_iff_lt.2 h, choose_eq_zero_of_lt h, mul_zero] }, rw mul_comm, apply mul_right_cancel' (factorial_ne_zero (n - k)), rw [choose_mul_factorial_mul_factorial h, ←factorial_mul_desc_factorial h, mul_comm], end lemma factorial_dvd_desc_factorial (n k : ℕ) : k! ∣ n.desc_factorial k := ⟨n.choose k, desc_factorial_eq_factorial_mul_choose _ _⟩ lemma choose_eq_desc_factorial_div_factorial (n k : ℕ) : n.choose k = n.desc_factorial k / k! := begin apply mul_left_cancel' (factorial_ne_zero k), rw ←desc_factorial_eq_factorial_mul_choose, exact (nat.mul_div_cancel' $ factorial_dvd_desc_factorial _ _).symm, end /-! ### Inequalities -/ /-- Show that `nat.choose` is increasing for small values of the right argument. -/ lemma choose_le_succ_of_lt_half_left {r n : ℕ} (h : r < n/2) : choose n r ≤ choose n (r+1) := begin refine le_of_mul_le_mul_right _ (nat.lt_sub_left_of_add_lt (lt_of_lt_of_le h (n.div_le_self 2))), rw ← choose_succ_right_eq, apply nat.mul_le_mul_left, rw [← nat.lt_iff_add_one_le, nat.lt_sub_left_iff_add_lt, ← mul_two], exact lt_of_lt_of_le (mul_lt_mul_of_pos_right h zero_lt_two) (n.div_mul_le_self 2), end /-- Show that for small values of the right argument, the middle value is largest. -/ private lemma choose_le_middle_of_le_half_left {n r : ℕ} (hr : r ≤ n/2) : choose n r ≤ choose n (n/2) := decreasing_induction (λ _ k a, (eq_or_lt_of_le a).elim (λ t, t.symm ▸ le_refl _) (λ h, (choose_le_succ_of_lt_half_left h).trans (k h))) hr (λ _, le_rfl) hr /-- `choose n r` is maximised when `r` is `n/2`. -/ lemma choose_le_middle (r n : ℕ) : choose n r ≤ choose n (n/2) := begin cases le_or_gt r n with b b, { cases le_or_lt r (n/2) with a h, { apply choose_le_middle_of_le_half_left a }, { rw ← choose_symm b, apply choose_le_middle_of_le_half_left, rw [div_lt_iff_lt_mul' zero_lt_two] at h, rw [le_div_iff_mul_le' zero_lt_two, nat.mul_sub_right_distrib, nat.sub_le_iff, mul_two, nat.add_sub_cancel], exact le_of_lt h } }, { rw choose_eq_zero_of_lt b, apply zero_le } end end nat
1ae88036fc43564960c793babf6d7a5376e3429a
df561f413cfe0a88b1056655515399c546ff32a5
/4-proposition-world/l1.lean
d8cfc1ab44c438a9316eaa7d7cffe58c4cfa3f0a
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
70
lean
example (P Q : Prop) (p : P) (h : P → Q) : Q := begin exact h p, end
962191077243756ddc9ac353549196892104718e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Meta.lean
1e16e2aa49c5de712ef079080da42c996c746b51
[ "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
35,302
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private constant version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private constant version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private constant version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () @[extern "lean_get_githash"] constant getGithash (u : Unit) : String def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] constant version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] constant version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () def versionStringCore := toString version.major ++ "." ++ toString version.minor ++ "." ++ toString version.patch def versionString := if version.specialDesc ≠ "" then versionStringCore ++ "-" ++ version.specialDesc else if version.isRelease then versionStringCore else versionStringCore ++ ", commit " ++ githash def origin := "leanprover/lean4" def toolchain := if version.specialDesc ≠ "" then if version.isRelease then origin ++ ":" ++ versionStringCore ++ "-" ++ version.specialDesc else origin ++ ":" ++ version.specialDesc else if version.isRelease then origin ++ ":" ++ versionStringCore else "" /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _ _) => n | n@(num anonymous _ _) => n | str n _ _ => getRoot n | num n _ _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s _ => s.contains '✝' || s == "_inaccessible" | Name.num p idx _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst s[0] && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s _ => maybeEscape s | num anonymous v _ => toString v | str n s _ => toStringWithSep n ++ sep ++ maybeEscape s | num n v _ => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let Name.str _ s _ := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString private def hasNum : Name → Bool | anonymous => false | num .. => true | str p .. => hasNum p protected def reprPrec (n : Name) (prec : Nat) : Std.Format := match n with | anonymous => Std.Format.text "Lean.Name.anonymous" | num p i _ => Repr.addAppParen ("Lean.Name.mkNum " ++ Name.reprPrec p max_prec ++ " " ++ repr i) prec | str p s _ => if p.hasNum then Repr.addAppParen ("Lean.Name.mkStr " ++ Name.reprPrec p max_prec ++ " " ++ repr s) prec else Std.Format.text "`" ++ n.toString instance : Repr Name where reprPrec := Name.reprPrec deriving instance Repr for Syntax def capitalize : Name → Name | Name.str p s _ => Name.mkStr p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s _), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s _), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s _ => Name.mkStr p (pre ++ s) | num p n _ => Name.mkNum (Name.mkStr p pre) n end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node _ k args, Syntax.node _ k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node SourceInfo.none _ args => args.findSomeRev? getTailInfo? | node info _ args => info | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 /-- Return substring of original input covering `stx`. Result is meaningful only if all involved `SourceInfo.original`s refer to the same string (as is the case after parsing). -/ def getSubstring? (stx : Syntax) (withLeading := true) (withTrailing := true) : Option Substring := match stx.getHeadInfo, stx.getTailInfo with | SourceInfo.original lead startPos _ _, SourceInfo.original _ _ trail stopPos => some { str := lead.str startPos := if withLeading then lead.startPos else startPos stopPos := if withTrailing then trail.stopPos else stopPos } | _, _ => none @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i] match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node info k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node info k args | none => none | stx => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos trail endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a.get ⟨i, h⟩; match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node i k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node i k args | noxne => none | stx => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | node _ kind args => node info kind args | missing => missing /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node SourceInfo.none _ args => args.findSome? getHead? | stx@(node info _ _) => stx | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : Syntax := Syntax.node SourceInfo.none k args /- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand all macros in the given syntax -/ partial def expandMacros : Syntax → MacroM Syntax | stx@(Syntax.node info k args) => do match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros pure <| Syntax.node info k args | stx => pure stx /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := Syntax.ident (SourceInfo.fromRef src) (toString val).toSubstring val [] def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) : m Syntax := do return mkIdentFrom (← getRef) val /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope Syntax.ident (SourceInfo.fromRef src) (toString id).toSubstring id [(c, [])] def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) : m Syntax := do return mkCIdentFrom (← getRef) c def mkCIdent (c : Name) : Syntax := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident SourceInfo.none (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := mkNode nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := mkNode groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := Id.run <| do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => mkNullNode #[arg] | none => mkNullNode #[] def mkHole (ref : Syntax) : Syntax := mkNode `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (mkAtomFrom ref sep)⟩ instance (sep) : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Syntax) : (args : Array Syntax) → Syntax | #[] => fn | args => mkNode `Lean.Parser.Term.app #[fn, mkNullNode args] def mkCApp (fn : Name) (args : Array Syntax) : Syntax := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : Syntax := let atom : Syntax := Syntax.atom info val mkNode kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : Syntax := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : Syntax := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : Syntax := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : Syntax := mkLit nameLitKind val info /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get 1 if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node _ k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := OptionM.run do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := OptionM.run do let c := s.get 1 if c == '\\' then do let (c, _) ← decodeQuotedChar s 2 pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def splitNameLitAux (ss : Substring) (acc : List Substring) : List Substring := let splitRest (ss : Substring) (acc : List Substring) : List Substring := if ss.front == '.' then splitNameLitAux (ss.drop 1) acc else if ss.isEmpty then acc else [] if ss.isEmpty then [] else let curr := ss.front if isIdBeginEscape curr then let escapedPart := ss.takeWhile (!isIdEndEscape ·) let escapedPart := { escapedPart with stopPos := ss.stopPos.min (escapedPart.str.next escapedPart.stopPos) } if !isIdEndEscape (escapedPart.get <| escapedPart.prev escapedPart.bsize) then [] else splitRest (ss.extract escapedPart.bsize ss.bsize) (escapedPart :: acc) else if isIdFirst curr then let idPart := ss.takeWhile isIdRest splitRest (ss.extract idPart.bsize ss.bsize) (idPart :: acc) else if curr.isDigit then let idPart := ss.takeWhile Char.isDigit splitRest (ss.extract idPart.bsize ss.bsize) (idPart :: acc) else [] /-- Split a name literal (without the backtick) into its dot-separated components. For example, `foo.bla.«bo.o»` ↦ `["foo", "bla", "«bo.o»"]`. If the literal cannot be parsed, return `[]`. -/ def splitNameLit (ss : Substring) : List Substring := splitNameLitAux ss [] |>.reverse def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then match splitNameLitAux (s.toSubstring.drop 1) [] with | [] => none | comps => some <| comps.foldr (init := Name.anonymous) fun comp n => let comp := comp.toString if isIdBeginEscape comp.front then Name.mkStr n (comp.drop 1 |>.dropRight 1) else if comp.front.isDigit then if let some k := decodeNatLitVal? comp then Name.mkNum n k else unreachable! else Name.mkStr n comp else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node _ k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node _ k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) where quote : α → Syntax export Quote (quote) instance : Quote Syntax := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String := ⟨Syntax.mkStrLit⟩ instance : Quote Nat := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → OptionM (List String) | Name.anonymous => acc | Name.str n s _ => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num n i _ => none private def quoteNameMk : Name → Syntax | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s _ => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | Name.num n i _ => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name where quote n := match getEscapedNameParts? [] n with | some ss => mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)] | none => quoteNameMk n instance {α β : Type} [Quote α] [Quote β] : Quote (α × β) where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList {α : Type} [Quote α] : List α → Syntax | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance {α : Type} [Quote α] : Quote (List α) where quote := quoteList instance {α : Type} [Quote α] : Quote (Array α) where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] private def quoteOption {α : Type} [Quote α] : Option α → Syntax | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] instance Option.hasQuote {α : Type} [Quote α] : Quote (Option α) where quote := quoteOption /- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):numLit) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):numLit) macro "eval_prec " p:prec:max : term => return quote (← evalPrec p) /- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):numLit) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):numLit) macro "eval_prio " p:prio:max : term => return quote (← evalPrio p) def evalOptPrio : Option Syntax → MacroM Nat | some prio => evalPrio prio | none => return eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.pred_lt hz let sepStx := a.get ⟨i.pred, Nat.lt_trans this h⟩ filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax.SepArray def getElems {sep} (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance (sep) : CoeTail (SepArray sep) (Array Syntax) where coe := getElems end Lean.Syntax.SepArray /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /- Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : OptionM String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop 1 "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result def expandInterpolatedStr (interpStr : Syntax) (type : Syntax) (toTypeFn : Syntax) : MacroM Syntax := do let ref := interpStr let r ← expandInterpolatedStrChunks interpStr.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr namespace Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : Bool := true iota : Bool := true proj : Bool := true decide : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true end Simp namespace Rewrite structure Config where transparency : TransparencyMode := TransparencyMode.reducible offsetCnstrs : Bool := true end Rewrite end Meta namespace Parser.Tactic macro "erw " s:rwRuleSeq loc:(location)? : tactic => `(rw (config := { transparency := Lean.Meta.TransparencyMode.default }) $s:rwRuleSeq $[$(loc.getOptional?):location]?) end Parser.Tactic end Lean
65611a9a56d9daaad0ae66b6d1083386c1cf5d5d
367134ba5a65885e863bdc4507601606690974c1
/src/data/polynomial/mirror.lean
a7546d3cd0226bf50e313b02902eda933e2a0987
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,375
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import data.polynomial.ring_division import algebra.big_operators.nat_antidiagonal /-! # "Mirror" of a univariate polynomial In this file we define `polynomial.mirror`, a variant of `polynomial.reverse`. The difference between `reverse` and `mirror` is that `reverse` will decrease the degree if the polynomial is divisible by `X`. We also define `polynomial.norm2`, which is the sum of the squares of the coefficients of a polynomial. It is also a coefficient of `p * p.mirror`. ## Main definitions - `polynomial.mirror` - `polynomial.norm2` ## Main results - `polynomial.mirror_mul_of_domain`: `mirror` preserves multiplication. - `polynomial.irreducible_of_mirror`: an irreducibility criterion involving `mirror` - `polynomial.norm2_eq_mul_reverse_coeff`: `norm2` is a coefficient of `p * p.mirror` -/ namespace polynomial variables {R : Type*} [semiring R] (p : polynomial R) section mirror /-- mirror of a polynomial: reverses the coefficients while preserving `polynomial.nat_degree` -/ noncomputable def mirror := p.reverse * X ^ p.nat_trailing_degree lemma mirror_zero : (0 : polynomial R).mirror = 0 := rfl lemma mirror_monomial (n : ℕ) (a : R) : (monomial n a).mirror = (monomial n a) := begin by_cases ha : a = 0, { rw [ha, monomial_zero_right, mirror_zero] }, { rw [mirror, reverse, nat_degree_monomial n a ha, nat_trailing_degree_monomial ha, ←C_mul_X_pow_eq_monomial, reflect_C_mul_X_pow, rev_at_le (le_refl n), nat.sub_self, pow_zero, mul_one] }, end lemma mirror_C (a : R) : (C a).mirror = C a := mirror_monomial 0 a lemma mirror_X : X.mirror = (X : polynomial R) := mirror_monomial 1 (1 : R) lemma mirror_nat_degree : p.mirror.nat_degree = p.nat_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, by_cases hR : nontrivial R, { haveI := hR, rw [mirror, nat_degree_mul', reverse_nat_degree, nat_degree_X_pow, nat.sub_add_cancel p.nat_trailing_degree_le_nat_degree], rwa [leading_coeff_X_pow, mul_one, reverse_leading_coeff, ne, trailing_coeff_eq_zero] }, { haveI := not_nontrivial_iff_subsingleton.mp hR, exact congr_arg nat_degree (subsingleton.elim p.mirror p) }, end lemma mirror_nat_trailing_degree : p.mirror.nat_trailing_degree = p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, { rw [mirror, nat_trailing_degree_mul_X_pow ((mt reverse_eq_zero.mp) hp), reverse_nat_trailing_degree, zero_add] }, end lemma coeff_mirror (n : ℕ) : p.mirror.coeff n = p.coeff (rev_at (p.nat_degree + p.nat_trailing_degree) n) := begin by_cases h2 : p.nat_degree < n, { rw [coeff_eq_zero_of_nat_degree_lt (by rwa mirror_nat_degree)], by_cases h1 : n ≤ p.nat_degree + p.nat_trailing_degree, { rw [rev_at_le h1, coeff_eq_zero_of_lt_nat_trailing_degree], exact (nat.sub_lt_left_iff_lt_add h1).mpr (nat.add_lt_add_right h2 _) }, { rw [←rev_at_fun_eq, rev_at_fun, if_neg h1, coeff_eq_zero_of_nat_degree_lt h2] } }, rw not_lt at h2, rw [rev_at_le (h2.trans (nat.le_add_right _ _))], by_cases h3 : p.nat_trailing_degree ≤ n, { rw [←nat.sub_add_eq_add_sub h2, ←nat.sub_sub_assoc h2 h3, mirror, coeff_mul_X_pow', if_pos h3, coeff_reverse, rev_at_le ((nat.sub_le_self _ _).trans h2)] }, rw not_le at h3, rw coeff_eq_zero_of_nat_degree_lt (nat.lt_sub_right_iff_add_lt.mpr (nat.add_lt_add_left h3 _)), exact coeff_eq_zero_of_lt_nat_trailing_degree (by rwa mirror_nat_trailing_degree), end --TODO: Extract `finset.sum_range_rev_at` lemma. lemma mirror_eval_one : p.mirror.eval 1 = p.eval 1 := begin simp_rw [eval_eq_finset_sum, one_pow, mul_one, mirror_nat_degree], refine finset.sum_bij_ne_zero _ _ _ _ _, { exact λ n hn hp, rev_at (p.nat_degree + p.nat_trailing_degree) n }, { intros n hn hp, rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [nat.sub_le_iff, add_comm, nat.add_sub_cancel, ←mirror_nat_trailing_degree], exact nat_trailing_degree_le_of_ne_zero hp }, { exact λ n₁ n₂ hn₁ hp₁ hn₂ hp₂ h, by rw [←@rev_at_invol _ n₁, h, rev_at_invol] }, { intros n hn hp, use rev_at (p.nat_degree + p.nat_trailing_degree) n, refine ⟨_, _, rev_at_invol.symm⟩, { rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [nat.sub_le_iff, add_comm, nat.add_sub_cancel], exact nat_trailing_degree_le_of_ne_zero hp }, { change p.mirror.coeff _ ≠ 0, rwa [coeff_mirror, rev_at_invol] } }, { exact λ n hn hp, p.coeff_mirror n }, end lemma mirror_mirror : p.mirror.mirror = p := polynomial.ext (λ n, by rw [coeff_mirror, coeff_mirror, mirror_nat_degree, mirror_nat_trailing_degree, rev_at_invol]) lemma mirror_eq_zero : p.mirror = 0 ↔ p = 0 := ⟨λ h, by rw [←p.mirror_mirror, h, mirror_zero], λ h, by rw [h, mirror_zero]⟩ lemma mirror_trailing_coeff : p.mirror.trailing_coeff = p.leading_coeff := by rw [leading_coeff, trailing_coeff, mirror_nat_trailing_degree, coeff_mirror, rev_at_le (nat.le_add_left _ _), nat.add_sub_cancel] lemma mirror_leading_coeff : p.mirror.leading_coeff = p.trailing_coeff := by rw [←p.mirror_mirror, mirror_trailing_coeff, p.mirror_mirror] lemma mirror_mul_of_domain {R : Type*} [integral_domain R] (p q : polynomial R) : (p * q).mirror = p.mirror * q.mirror := begin by_cases hp : p = 0, { rw [hp, zero_mul, mirror_zero, zero_mul] }, by_cases hq : q = 0, { rw [hq, mul_zero, mirror_zero, mul_zero] }, rw [mirror, mirror, mirror, reverse_mul_of_domain, nat_trailing_degree_mul hp hq, pow_add], ring, end lemma mirror_smul {R : Type*} [integral_domain R] (p : polynomial R) (a : R) : (a • p).mirror = a • p.mirror := by rw [←C_mul', ←C_mul', mirror_mul_of_domain, mirror_C] lemma mirror_neg {R : Type*} [ring R] (p : polynomial R) : (-p).mirror = -(p.mirror) := by rw [mirror, mirror, reverse_neg, nat_trailing_degree_neg, neg_mul_eq_neg_mul] lemma irreducible_of_mirror {R : Type*} [integral_domain R] {f : polynomial R} (h1 : ¬ is_unit f) (h2 : ∀ k, f * f.mirror = k * k.mirror → k = f ∨ k = -f ∨ k = f.mirror ∨ k = -f.mirror) (h3 : ∀ g, g ∣ f → g ∣ f.mirror → is_unit g) : irreducible f := begin split, { exact h1 }, { intros g h fgh, let k := g * h.mirror, have key : f * f.mirror = k * k.mirror, { rw [fgh, mirror_mul_of_domain, mirror_mul_of_domain, mirror_mirror, mul_assoc, mul_comm h, mul_comm g.mirror, mul_assoc, ←mul_assoc] }, have g_dvd_f : g ∣ f, { rw fgh, exact dvd_mul_right g h }, have h_dvd_f : h ∣ f, { rw fgh, exact dvd_mul_left h g }, have g_dvd_k : g ∣ k, { exact dvd_mul_right g h.mirror }, have h_dvd_k_rev : h ∣ k.mirror, { rw [mirror_mul_of_domain, mirror_mirror], exact dvd_mul_left h g.mirror }, have hk := h2 k key, rcases hk with hk | hk | hk | hk, { exact or.inr (h3 h h_dvd_f (by rwa ← hk)) }, { exact or.inr (h3 h h_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, mirror_neg, dvd_neg])) }, { exact or.inl (h3 g g_dvd_f (by rwa ← hk)) }, { exact or.inl (h3 g g_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, dvd_neg])) } }, end end mirror end polynomial
4ce3f099ada7b1268b291cd80d9c390296e152a0
46125763b4dbf50619e8846a1371029346f4c3db
/src/meta/expr.lean
666a9cd2b15deba769ea369efa94222f66f103aa
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
26,277
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) namespace expr /-- Turns an expression into a positive natural number, assuming it is only built up from `has_one.one`, `bit0` and `bit1`. -/ protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1` and `has_zero.zero`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es library_note "open expressions" "Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x)." /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param end declaration
822cb51bfac2687f3b41cc8da50fc74a3905fc26
a332e4934ff49f6c0a1af6799591f6694d9ccda6
/sphinx/6_12.lean
38bfafb6b0c8bab68f494fe2be60af1c9917b204
[ "CC-BY-4.0" ]
permissive
khanhdt/formalabstracts
295624d43b15275bf1acd03e6835b35d496bde42
c25503700d85df0a592d681c8fdf3b8af6b9a759
refs/heads/master
1,584,616,983,167
1,528,963,872,000
1,528,963,872,000
136,273,754
0
0
null
1,528,260,960,000
1,528,260,960,000
null
UTF-8
Lean
false
false
1,441
lean
def symn_group (α: Type): Type := {f: α → α // function.bijective f} instance (α: Type): has_one (symn_group α):= ((id, function.bijective_id)) instance (α: Type): has_mul (symn_group α):= (λ(f, f_is_bij) (g, g_is_bij), (f ∘ g, function.bijective_comp f_is_bij g_is_bij) instance (α: Type): group (symn_group α):= { inv:=_, one:= (1), mul:=(*), mul_assoc := sorry, one_mul:= sorry, mul_one:=sorry, mul_left_inv:=sorry, } set_option pp.numerals false set_option pp.implicit true example (n: ℕ) (c: cyclic_group n): c =1 := _ namespace hn example (x y :ℕ): x + y = y+ x:= nat.add_comm _ _ example (x y :ℕ): x + y = y+ x:= begin exact nat.add_comm _ _ end example (x y :ℕ): x+ y = y+ x:= by exact nat.add_comm _ _ example (x y :ℕ) (h: y+x =0): x+ y = 0:= eq.trans (nat.add_comm _ _) h example (x y :ℕ) (h: y+x =0): x+ y = 0:= begin refine eq.trans _ _, {exact (y + x),}, {exact nat.add_comm x y}, {exact h}, end example (x y :ℕ) (h: y+x =0): x+ y = 0:= begin refine eq.trans _ h, exact nat.add_comm x y, end example (x y :ℕ) (h: y+x =0): x+ y = 0:= begin rw [nat.add_comm], exact h end end hn /-K - a field --> define a vector space V over K Give instance Kn V: comm-group need define KxV -> V (λ, v) -> λv (λ β) V = λ (β V) λ (v+ w) = -/ variable [field K] class vector_sp (α: Type uvw)
b03013c87c8bb508885acbfaf391ef31de19d634
4e0c49ab645d61b5c3e486a1b460db14552914ae
/library/init/meta/interactive.lean
51d400ecff46ca309a9941e38ee943e7b8fdf0b9
[ "Apache-2.0" ]
permissive
saik2121/lean
0c733955a9a33270a86d17f4139054c8bd09cff5
13007ebb4de63859d9866c19f6e753bbf1852f41
refs/heads/master
1,676,215,937,507
1,609,762,908,000
1,609,762,908,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
72,018
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jannis Limperg -/ prelude import init.meta.tactic init.meta.type_context init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.control.combinators import init.meta.interactive_base init.meta.derive init.meta.match_tactic import init.meta.congr_tactic init.meta.case_tag open lean open lean.parser open native local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /- allows metavars -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- allow metavars and no subgoals -/ meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr := to_expr q tt ff /- doesn't allows metavars -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ meta def i_to_expr_for_apply (q : pexpr) : tactic expr := let aux (n : name) : tactic expr := do p ← resolve_name n, match p with | (expr.const c []) := do r ← mk_const c, save_type_info r q, return r | _ := i_to_expr p end in match q with | (expr.const c []) := aux c | (expr.local_const c _ _ _) := aux c | _ := i_to_expr q end namespace interactive open interactive interactive.types expr /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit meta def propagate_tags (tac : tactic unit) : tactic unit := do tag ← get_main_tag, if tag = [] then tac else focus1 $ do tac, gs ← get_goals, when (bnot gs.empty) $ do new_tag ← get_main_tag, when new_tag.empty $ with_enable_tags (set_main_tag tag) meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit := mcond tags_enabled (do in_tag ← get_main_tag, r ← tac, /- remove assigned metavars -/ r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m, match r with | [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/ | _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag)) end) (tac >> skip) /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. -/ meta def intro : parse ident_? → tactic unit | none := propagate_tags (intro1 >> skip) | (some h) := propagate_tags (tactic.intro h >> skip) /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := propagate_tags (tactic.intros >> skip) | hs := propagate_tags (intro_lst hs >> skip) /-- The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ meta def introv (ns : parse ident_*) : tactic unit := propagate_tags (tactic.introv ns >> return ()) /-- Parse a current name and new name for `rename`. -/ private meta def rename_arg_parser : parser (name × name) := prod.mk <$> ident <*> (optional (tk "->") *> ident) /-- Parse the arguments of `rename`. -/ private meta def rename_args_parser : parser (list (name × name)) := (functor.map (λ x, [x]) rename_arg_parser) <|> (tk "[" *> sep_by (tk ",") rename_arg_parser <* tk "]") /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename x y -- rename x to y rename x → y -- ditto rename [x y, a b] -- rename x to y and a to b rename [x → y, a → b] -- ditto ``` Note that if there are multiple hypotheses called `x` in the context, then `rename x y` will rename *all* of them. If you want to rename only one, use `dedup` first. -/ meta def rename (renames : parse rename_args_parser) : tactic unit := propagate_tags $ tactic.rename_many $ native.rb_map.of_list renames /-- The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h) /-- Similar to the `apply` tactic, but does not reorder goals. -/ meta def fapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply) /-- Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply) /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg) /-- Similar to the `apply` tactic, but uses matching instead of unification. `apply_match t` is equivalent to `apply_with t {unify := ff}` -/ meta def mapply (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff}) /-- This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes. Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`. -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- Try to apply `assumption` to all goals. -/ meta def assumption' : tactic unit := tactic.any_goals' tactic.assumption private meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal. `change u at h` will change a local hypothesis to `u`. `change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal. -/ meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do u ← mk_meta_univ, ty ← mk_meta_var (sort u), eq ← i_to_expr ``(%%q : %%ty), ew ← i_to_expr ``(%%w : %%ty), let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none), l.try_apply (λh, do e ← infer_type h, change_core (repl e) (some h)) (do g ← target, change_core (repl g) none) /-- This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse pexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts /-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode. -/ meta def «from» := exact /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip) private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ meta def to_expr' (p : pexpr) : tactic expr := match p with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | _ := i_to_expr p end @[derive has_reflect] meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) := let aux (n : name) : tactic (list name) := do { p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := get_eqn_lemmas_for tt n | _ := return [] end } <|> return [] in match r.rule with | const n _ := aux n | local_const n _ _ _ := aux n | _ := return [] end private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || to_bool (t = h) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.empty) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep @[derive has_reflect] meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) /-- `rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rewrite [e₁, ..., eₙ]` applies the given rules sequentially. `rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. -/ meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `rewrite`. -/ meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- `rewrite` followed by `assumption`. -/ meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rewrite q l cfg >> try assumption /-- A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions. -/ meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `erewrite`. -/ meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- Returns the unique names of all hypotheses (local constants) in the context. -/ private meta def hyp_unique_names : tactic name_set := do ctx ← local_context, pure $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set /-- Returns all hypotheses (local constants) from the context except those whose unique names are in `hyp_uids`. -/ private meta def hyps_except (hyp_uids : name_set) : tactic (list expr) := do ctx ← local_context, pure $ ctx.filter (λ (h : expr), ¬ hyp_uids.contains h.local_uniq_name) /-- Apply `t` to the main goal and revert any new hypothesis in the generated goals. If `t` is a supported tactic or chain of supported tactics (e.g. `induction`, `cases`, `apply`, `constructor`), the generated goals are also tagged with case tags. You can then use `case` to focus such tagged goals. Two typical uses of `with_cases`: 1. Applying a custom eliminator: ``` lemma my_nat_rec : ∀ n {P : ℕ → Prop} (zero : P 0) (succ : ∀ n, P n → P (n + 1)), P n := ... example (n : ℕ) : n = n := begin with_cases { apply my_nat_rec n }, case zero { refl }, case succ : m ih { refl } end ``` 2. Enabling the use of `case` after a chain of case-splitting tactics: ``` example (n m : ℕ) : unit := begin with_cases { cases n; induction m }, case nat.zero nat.zero { exact () }, case nat.zero nat.succ : k { exact () }, case nat.succ nat.zero : i { exact () }, case nat.succ nat.succ : k i ih_i { exact () } end ``` -/ meta def with_cases (t : itactic) : tactic unit := with_enable_tags $ focus1 $ do input_hyp_uids ← hyp_unique_names, t, all_goals' $ do in_tag ← get_main_tag, new_hyps ← hyps_except input_hyp_uids, n ← revert_lst new_hyps, set_main_tag (case_tag.from_tag_pi in_tag n).render private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ meta def generalize (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize e x >> intro1 >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h meta def cases_arg_p : parser (option name × pexpr) := with_desc "(id :)? expr" $ do t ← texpr, match t with | (local_const x _ _ _) := (tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t) | _ := pure (none, t) end /-- Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag` is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was applied. `rs` should contain, for each subgoal, the constructor name associated with that goal and the hypotheses that were introduced. -/ private meta def set_cases_tags (in_tag : tag) (rs : list (name × list expr)) : tactic unit := do gs ← get_goals, match gs with -- if only one goal was produced, we should not make the tag longer | [g] := set_tag g in_tag | _ := let tgs : list (name × list expr × expr) := rs.map₂ (λ ⟨n, new_hyps⟩ g, ⟨n, new_hyps, g⟩) gs in tgs.mmap' $ λ ⟨n, new_hyps, g⟩, with_enable_tags $ set_tag g $ (case_tag.from_tag_hyps (n :: in_tag) (new_hyps.map expr.local_uniq_name)).render end precedence `generalizing` : 0 /-- Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically. `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable. `induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism. `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized. `induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context. -/ meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do in_tag ← get_main_tag, focus1 $ do { -- process `h : t` case e ← match hp with | (some h, p) := do x ← get_unused_name, generalize h () (p, x), get_local x | (none, p) := i_to_expr p end, -- generalize major premise e ← if e.is_local_constant then pure e else tactic.generalize e >> intro1, -- generalize major premise args (e, newvars, locals) ← do { none ← pure rec_name | pure (e, [], []), t ← infer_type e, t ← whnf_ginductive t, const n _ ← pure t.get_app_fn | pure (e, [], []), env ← get_env, tt ← pure $ env.is_inductive n | pure (e, [], []), let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition (λ arg : expr, arg.is_local_constant), _ :: _ ← pure nonlocals | pure (e, [], []), n ← tactic.revert e, newvars ← nonlocals.mmap $ λ arg, do { n ← revert_kdeps arg, tactic.generalize arg, h ← intro1, intron n, -- now try to clear hypotheses that may have been abstracted away let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc), locals.mmap' (try ∘ clear), pure h }, intron (n-1), e ← intro1, pure (e, newvars, locals) }, -- revert `generalizing` params (and their dependencies, if any) to_generalize ← (revert.get_or_else []).mmap tactic.get_local, num_generalized ← revert_lst to_generalize, -- perform the induction rs ← tactic.induction e ids rec_name, -- re-introduce the generalized hypotheses gen_hyps ← all_goals $ do { new_hyps ← intron' num_generalized, clear_lst (newvars.map local_pp_name), (e::locals).mmap' (try ∘ clear), pure new_hyps }, set_cases_tags in_tag $ @list.map₂ (name × list expr × list (name × expr)) _ (name × list expr) (λ ⟨n, hyps, _⟩ gen_hyps, ⟨n, hyps ++ gen_hyps⟩) rs gen_hyps } open case_tag.match_result private meta def goals_with_matching_tag (ns : list name) : tactic (list (expr × case_tag) × list (expr × case_tag)) := do gs ← get_goals, (gs : list (expr × tag)) ← gs.mmap (λ g, do t ← get_tag g, pure (g, t)), pure $ gs.foldr (λ ⟨g, t⟩ ⟨exact_matches, suffix_matches⟩, match case_tag.parse t with | none := ⟨exact_matches, suffix_matches⟩ | some t := match case_tag.match_tag ns t with | exact_match := ⟨⟨g, t⟩ :: exact_matches, suffix_matches⟩ | fuzzy_match := ⟨exact_matches, ⟨g, t⟩ :: suffix_matches⟩ | no_match := ⟨exact_matches, suffix_matches⟩ end end) ([], []) private meta def goal_with_matching_tag (ns : list name) : tactic (expr × case_tag) := do ⟨exact_matches, suffix_matches⟩ ← goals_with_matching_tag ns, match exact_matches, suffix_matches with | [] , [] := fail format! "Invalid `case`: there is no goal tagged with suffix {ns}." | [] , [g] := pure g | [] , _ := let tags : list (list name) := suffix_matches.map (λ ⟨_, t⟩, t.case_names.reverse) in fail format! "Invalid `case`: there is more than one goal tagged with suffix {ns}.\nMatching tags: {tags}" | [g], _ := pure g | _ , _ := fail format! "Invalid `case`: there is more than one goal tagged with tag {ns}." end /-- Focuses on a goal ('case') generated by `induction`, `cases` or `with_cases`. The goal is selected by giving one or more names which must match exactly one goal. A goal is matched if the given names are a suffix of its goal tag. Additionally, each name in the sequence can be abbreviated to a suffix of the corresponding name in the goal tag. Thus, a goal with tag ``` nat.zero, list.nil ``` can be selected with any of these invocations (among others): ``` case nat.zero list.nil {...} case nat.zero nil {...} case zero nil {...} case nil {...} ``` Additionally, the form ``` case C : N₀ ... Nₙ {...} ``` can be used to rename hypotheses introduced by the preceding `cases`/`induction`/`with_cases`, using the names `Nᵢ`. For example: ``` example (xs : list ℕ) : xs = xs := begin induction xs, case nil { reflexivity }, case cons : x xs ih { -- x : ℕ, xs : list ℕ, ih : xs = xs reflexivity } end ``` Note that this renaming functionality only work reliably *directly after* an `induction`/`cases`/`with_cases`. If you need to perform additional work after an `induction` or `cases` (e.g. introduce hypotheses in all goals), use `with_cases`. -/ /- TODO `case` could be generalised to work with zero names as well. The form case : x y z { ... } would select the first goal (or the first goal with a case tag), renaming hypotheses to `x, y, z`. The renaming functionality would be available only if the goal has a case tag. -/ meta def case (ns : parse ident_*) (ids : parse $ (tk ":" *> ident_*)?) (tac : itactic) : tactic unit := do ⟨goal, tag⟩ ← goal_with_matching_tag ns, let ids := ids.get_or_else [], let num_ids := ids.length, goals ← get_goals, set_goals $ goal :: goals.filter (≠ goal), match tag with | (case_tag.pi _ num_args) := do intro_lst ids, when (num_ids < num_args) $ intron (num_args - num_ids) | (case_tag.hyps _ new_hyp_names) := do let num_new_hyps := new_hyp_names.length, when (num_ids > num_new_hyps) $ fail format! "Invalid `case`: You gave {num_ids} names, but the case introduces {num_new_hyps} new hypotheses.", let renamings := rb_map.of_list (new_hyp_names.zip ids), propagate_tags $ tactic.rename_many renamings tt tt end, solve1 tac /-- Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically. -/ meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct meta def cases_core (e : expr) (ids : list name := []) : tactic unit := do in_tag ← get_main_tag, focus1 $ do rs ← tactic.cases e ids, set_cases_tags in_tag rs /-- Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically. `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. `cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case. -/ meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit | (none, p) ids := do e ← i_to_expr p, cases_core e ids | (some h, p) ids := do x ← get_unused_name, generalize h () (p, x), hx ← get_local x, cases_core hx ids private meta def find_matching_hyp (ps : list pattern) : tactic expr := any_hyp $ λ h, do type ← infer_type h, ps.mfirst $ λ p, do match_pattern p type, return h /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then find_matching_hyp ps >>= cases_core else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core /-- Shorthand for `cases_matching` -/ meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := cases_matching rec ps private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit := any_hyp $ λ h, do I ← expr.get_app_fn <$> (infer_type h >>= head_beta), guard I.is_constant, guard (I.const_name ∈ type_names), tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip) /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_type* or and ``` -/ meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit := do type_names ← type_names.mmap resolve_constant, if rec.is_none then try_cases_for_types type_names (bnot one.is_none) else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none) /-- Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic. -/ meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using `sorry`. -/ meta def admit : tactic unit := tactic.admit /-- Closes the main goal using `sorry`. -/ meta def «sorry» : tactic unit := tactic.admit /-- The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction /-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds. `iterate n { t }` applies `t` `n` times. -/ meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit := match n with | none := tactic.iterate' t | some n := iterate_exactly' n t end /-- `repeat { t }` applies `t` to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat { t }` never fails. -/ meta def repeat : itactic → tactic unit := tactic.repeat /-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds. -/ meta def try : itactic → tactic unit := tactic.try /-- A do-nothing tactic that always succeeds. -/ meta def skip : tactic unit := tactic.skip /-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved. -/ meta def solve1 : itactic → tactic unit := tactic.solve1 /-- `abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically. -/ meta def abstract (id : parse ident?) (tac : itactic) : tactic unit := tactic.abstract tac id /-- `all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds. -/ meta def all_goals : itactic → tactic unit := tactic.all_goals' /-- `any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds. -/ meta def any_goals : itactic → tactic unit := tactic.any_goals' /-- `focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals. -/ meta def focus (tac : itactic) : tactic unit := tactic.focus1 tac private meta def assume_core (n : name) (ty : pexpr) := do t ← target, when (not $ t.is_pi ∨ t.is_let) whnf_target, t ← target, when (not $ t.is_pi ∨ t.is_let) $ fail "assume tactic failed, Pi/let expression expected", ty ← i_to_expr ty, unify ty t.binding_domain, intro_core n >> skip /-- Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred. `assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present. -/ meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit | (sum.inl ty) := assume_core `this ty | (sum.inr binders) := binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type /-- `have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.assertv h t v | none, some p := do p ← i_to_expr p, tactic.note h none p | some e, none := i_to_expr e >>= tactic.assert h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.assert h e end >> skip /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.definev h t v | none, some p := do p ← i_to_expr p, tactic.pose h none p | some e, none := i_to_expr e >>= tactic.define h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.define h e end >> skip /-- `suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. -/ meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit := «have» h t none >> tactic.swap /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. -/ meta def existsi : parse pexpr_list_or_texpr → tactic unit | [] := return () | (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := concat_tags tactic.constructor /-- Similar to `constructor`, but only non-dependent premises are added as new goals. -/ meta def econstructor : tactic unit := concat_tags tactic.econstructor /-- Applies the first constructor when the type of the target is an inductive data type with two constructors. -/ meta def left : tactic unit := concat_tags tactic.left /-- Applies the second constructor when the type of the target is an inductive data type with two constructors. -/ meta def right : tactic unit := concat_tags tactic.right /-- Applies the constructor when the type of the target is an inductive data type with one constructor. -/ meta def split : tactic unit := concat_tags tactic.split private meta def constructor_matching_aux (ps : list pattern) : tactic unit := do t ← target, ps.mfirst (λ p, match_pattern p t), constructor meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then constructor_matching_aux ps else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps /-- Replaces the target of the main goal by `false`. -/ meta def exfalso : tactic unit := tactic.exfalso /-- The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs, try assumption /-- `injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`. -/ meta def injections (hs : parse with_ident_list) : tactic unit := do tactic.injections_with hs, try assumption end interactive meta structure simp_config_ext extends simp_config := (discharger : tactic unit := failed) section mk_simp_set open expr interactive.types @[derive has_reflect] meta inductive simp_arg_type : Type | all_hyps : simp_arg_type | except : name → simp_arg_type | expr : pexpr → simp_arg_type | symm_expr : pexpr → simp_arg_type meta instance simp_arg_type_to_tactic_format : has_to_tactic_format simp_arg_type := ⟨λ a, match a with | simp_arg_type.all_hyps := pure "*" | (simp_arg_type.except n) := pure format!"-{n}" | (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp | (simp_arg_type.symm_expr e) := ((++) "←") <$> (i_to_expr_no_subgoals e >>= pp) end⟩ meta def simp_arg : parser simp_arg_type := (tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (tk "<-" *> simp_arg_type.symm_expr <$> texpr) <|> (simp_arg_type.expr <$> texpr) meta def simp_arg_list : parser (list simp_arg_type) := (tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return [] private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name) | [] gex hex := return (gex.reverse, hex.reverse) | (id::ids) gex hex := do p ← resolve_name id, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := resolve_exception_ids ids (n::gex) hex | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >> resolve_exception_ids ids gex (n::hex) | _ := fail $ sformat! "invalid exception {id}, unknown identifier" end /-- Decode a list of `simp_arg_type` into lists for each type. This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`. This version fails when an argument of the form `simp_arg_type.symm_expr` is included, so that `simp`-like tactics that do not (yet) support backwards rewriting should properly report an error but function normally on other inputs. -/ meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool := do (hs, ex, all) ← hs.mfoldl (λ (r : (list pexpr × list name × bool)) h, do let (es, ex, all) := r, match h with | simp_arg_type.all_hyps := pure (es, ex, tt) | simp_arg_type.except id := pure (es, id::ex, all) | simp_arg_type.expr e := pure (e::es, ex, all) | simp_arg_type.symm_expr _ := fail "arguments of the form '←...' are not supported" end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) /-- Decode a list of `simp_arg_type` into lists for each type. This is the newer version of `decode_simp_arg_list`, and has a new name for backwards compatibility. This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`. -/ meta def decode_simp_arg_list_with_symm (hs : list simp_arg_type) : tactic $ list (pexpr × bool) × list name × list name × bool := do let (hs, ex, all) := hs.foldl (λ r h, match r, h with | (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt) | (es, ex, all), simp_arg_type.except id := (es, id::ex, all) | (es, ex, all), simp_arg_type.expr e := ((e, ff)::es, ex, all) | (es, ex, all), simp_arg_type.symm_expr e := ((e, tt)::es, ex, all) end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) private meta def add_simps : simp_lemmas → list (name × bool) → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n.fst n.snd, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)" private meta def check_no_overload (p : pexpr) : tactic unit := when p.is_choice_macro $ match p with | macro _ ps := fail $ to_fmt "ambiguous overload, possible interpretations" ++ format.join (ps.map (λ p, (to_fmt p).indent 4)) | _ := failed end private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) (symm : bool) : tactic (simp_lemmas × list name) := do p ← resolve_name n, check_no_overload p, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n symm, return (s, u)) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s (eqns.map (λ e, (e, ff))), return (s, u)) <|> (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u)) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e symm, return (s, u)) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) (symm : bool) : tactic (simp_lemmas × list name) := match p with | (const c []) := simp_lemmas.resolve_and_add s u c p symm | (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p symm | _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e symm, return (s, u) end private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list (pexpr × bool) → tactic (simp_lemmas × list name) | s u [] := return (s, u) | s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l.fst l.snd, simp_lemmas.append_pexprs s u ls meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool) : tactic (bool × simp_lemmas × list name) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list_with_symm hs, when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported", s ← join_user_simp_lemmas no_dflt attr_names, -- Erase `h` from the default simp set for calls of the form `simp [←h]`. let to_erase := hs.foldl (λ l h, match h with | (const id _, tt) := id :: l | (local_const id _ _ _, tt) := id :: l | _ := l end ) [], let s := s.erase to_erase, (s, u) ← simp_lemmas.append_pexprs s [] hs, s ← if not at_star ∧ all_hyps then do ctx ← collect_ctx_simps, let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions s.append ctx else return s, -- add equational lemmas, if any gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return (all_hyps, simp_lemmas.erase s $ gex.join, u) meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) := prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff) end mk_simp_set namespace interactive open interactive interactive.types expr meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff, guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.mmap' (λ h, try (clear h)) meta def simp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic unit := match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then tactic.simp_all s u cfg discharger else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, simp_core_aux cfg discharger s u ns locat.include_goal end >> try tactic.triv >> try (tactic.reflexivity reducible) /-- The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. `simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If `hᵢ` is preceded by left arrow (`←` or `<-`), the simplification is performed in the reverse direction. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`. `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. `simp *` is a shorthand for `simp [*]`. `simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`. `simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target. `simp at *` simplifies all the hypotheses and the target. `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. `simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`. -/ meta def simp (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := let cfg := if use_iota_eqn.is_none then cfg else {iota_eqn := tt, ..cfg} in propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat) /-- Just construct the simp set and trace it. Used for debugging. -/ meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit := do (s, _) ← mk_simp_set no_dflt attr_names hs, s.pp >>= trace /-- `simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target. As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`. -/ meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_intros_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names hs, when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")), tactic.simp_intros s u ids cfg, try triv >> try (reflexivity reducible) private meta def to_simp_arg_list (symms : list bool) (es : list pexpr) : list simp_arg_type := (symms.zip es).map (λ ⟨s, e⟩, if s then simp_arg_type.symm_expr e else simp_arg_type.expr e) /-- `dsimp` is similar to `simp`, except that it only uses definitional equalities. -/ meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) (l : parse location) (cfg : dsimp_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names es, match l with | loc.wildcard := /- Remark: we cannot revert frozen local instances. We disable zeta expansion because to prevent `intron n` from failing. Another option is to put a "marker" at the current target, and implement `intro_upto_marker`. -/ do n ← revert_all, dsimp_target s u {zeta := ff ..cfg}, intron n | _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg) end /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`. -/ meta def symmetry : tactic unit := tactic.symmetry /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`. `transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead. -/ meta def transitivity (q : parse texpr?) : tactic unit := tactic.transitivity >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, i_to_expr q >>= unify rhs end /-- Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations. -/ meta def ac_reflexivity : tactic unit := tactic.ac_refl /-- An abbreviation for `ac_reflexivity`. -/ meta def ac_refl : tactic unit := tactic.ac_refl /-- Tries to prove the main goal using congruence closure. -/ meta def cc : tactic unit := tactic.cc /-- Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. -/ meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) /-- Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`. -/ meta def subst_vars : tactic unit := tactic.subst_vars /-- `clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context. -/ meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) /-- Similar to `unfold`, but only uses definitional equalities. -/ meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit := match l with | (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, dunfold_target new_cs cfg, intron n | _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg) end private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs /-- Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants. -/ meta def delta : parse ident* → parse location → tactic unit | cs (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, delta_target new_cs, intron n | cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs) private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool := hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff /-- This tactic unfolds all structure projections. -/ meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit := match l with | loc.wildcard := do ls ← local_context, b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name), b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff, when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify") | _ := l.try_apply (λ h, unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify" end end interactive meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) := cs.mmap $ λ c, do n ← resolve_name c, hs ← get_eqn_lemmas_for ff n.const_name, env ← get_env, let p := env.is_projection n.const_name, when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")), return $ simp_arg_type.expr (expr.const c []) structure unfold_config extends simp_config := (zeta := ff) (proj := ff) (eta := ff) (canonize_instances := ff) (constructor_eq := ff) namespace interactive open interactive interactive.types expr /-- Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions. As with `simp`, the `at` modifier can be used to specify locations for the unfolding. -/ meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit := do es ← ids_to_simp_arg_list "unfold" cs, let no_dflt := tt, simp_core cfg.to_simp_config failed no_dflt es [] locat /-- Similar to `unfold`, but does not iterate the unfolding. -/ meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit := unfold cs locat cfg /-- If the target of the main goal is an `opt_param`, assigns the default value. -/ meta def apply_opt_param : tactic unit := tactic.apply_opt_param /-- If the target of the main goal is an `auto_param`, executes the associated tactic. -/ meta def apply_auto_param : tactic unit := tactic.apply_auto_param /-- Fails if the given tactic succeeds. -/ meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac /-- Succeeds if the given tactic fails. -/ meta def success_if_fail (tac : itactic) : tactic unit := tactic.success_if_fail tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv t e) /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq t p /-- `guard_hyp h : t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. -/ meta def guard_hyp (n : parse ident) (ty : parse (tk ":" *> texpr)?) (val : parse (tk ":=" *> texpr)?) : tactic unit := do h ← get_local n, ldecl ← tactic.unsafe.type_context.run (do lctx ← unsafe.type_context.get_local_context, pure $ lctx.get_local_decl h.local_uniq_name), ldecl ← ldecl | fail format!"hypothesis {h} not found", match ty with | some p := guard_expr_eq ldecl.type p | none := skip end, match ldecl.value, val with | none, some _ := fail format!"{h} is not a let binding" | some _, none := fail format!"{h} is a let binding" | some hval, some val := guard_expr_eq hval val | none, none := skip end /-- `match_target t` fails if target does not match pattern `t`. -/ meta def match_target (t : parse texpr) (m := reducible) : tactic unit := tactic.match_target t m >> skip /-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`. -/ meta def by_cases : parse cases_arg_p → tactic unit | (n, q) := concat_tags $ do p ← tactic.to_expr_strict q, tactic.by_cases p (n.get_or_else `h), pos_g :: neg_g :: rest ← get_goals, return [(`pos, pos_g), (`neg, neg_g)] /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. -/ meta def funext : parse ident_* → tactic unit | [] := tactic.funext >> skip | hs := funext_lst hs >> skip /-- If the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contradiction h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ meta def by_contradiction (n : parse ident?) : tactic unit := tactic.by_contradiction (n.get_or_else `h) $> () /-- If the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contra h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ meta def by_contra (n : parse ident?) : tactic unit := by_contradiction n /-- Type check the given expression, and trace its type. -/ meta def type_check (p : parse texpr) : tactic unit := do e ← to_expr p, tactic.type_check e, infer_type e >>= trace /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := tactic.done private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit | [] r := fail "show tactic failed" | (g::gs) r := do do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty} <|> show_aux gs (g::r) /-- `show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`. -/ meta def «show» (q : parse texpr) : tactic unit := do gs ← get_goals, show_aux q gs [] /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ meta def specialize (p : parse texpr) : tactic unit := do e ← i_to_expr p, let h := expr.get_app_fn e, if h.is_local_constant then tactic.note h.local_pp_name none e >> try (tactic.clear h) else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" meta def congr := tactic.congr end interactive end tactic section add_interactive open tactic /- See add_interactive -/ private meta def add_interactive_aux (new_namespace : name) : list name → command | [] := return () | (n::ns) := do env ← get_env, d_name ← resolve_constant n, (declaration.defn _ ls ty val hints trusted) ← env.get d_name, (name.mk_string h _) ← return d_name, let new_name := new_namespace <.> h, add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted), do { doc ← doc_string d_name, add_doc_string new_name doc } <|> skip, add_interactive_aux ns /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command := add_interactive_aux p ns meta def has_dup : tactic bool := do ctx ← local_context, let p : name_set × bool := ctx.foldl (λ ⟨s, r⟩ h, if r then (s, r) else if s.contains h.local_pp_name then (s, tt) else (s.insert h.local_pp_name, ff)) (mk_name_set, ff), return p.2 /-- Renames hypotheses with the same name. -/ meta def dedup : tactic unit := mwhen has_dup $ do ctx ← local_context, n ← revert_lst ctx, intron n end add_interactive namespace tactic /- Helper tactic for `mk_inj_eq -/ protected meta def apply_inj_lemma : tactic unit := do h ← intro `h, some (lhs, rhs) ← expr.is_eq <$> infer_type h, (expr.const C _) ← return lhs.get_app_fn, -- We disable auto_param and opt_param support to address issue #1943 applyc (name.mk_string "inj" C) {auto_param := ff, opt_param := ff}, assumption /- Auxiliary tactic for proving `I.C.inj_eq` lemmas. These lemmas are automatically generated by the equation compiler. Example: ``` list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) := by mk_inj_eq ``` -/ meta def mk_inj_eq : tactic unit := `[ intros, /- We use `_root_.*` in the following tactics because names are resolved at tactic execution time in interactive mode. See PR #1913 TODO(Leo): This is probably not the only instance of this problem. `[ ... ] blocks are convenient to use because they allow us to use the interactive mode to write non interactive tactics. One potential fix for this issue is to resolve names in `[ ... ] at tactic compilation time. After this issue is fixed, we should remove the `_root_.*` workaround. -/ apply _root_.propext, apply _root_.iff.intro, { tactic.apply_inj_lemma }, { intro _, try { cases_matching* _ ∧ _ }, refl <|> { congr; { assumption <|> subst_vars } } } ] end tactic /- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/ universes u v lemma sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ a₂ : α) : (@sum.inl α β a₁ = sum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ b₂ : β) : (@sum.inr α β b₁ = sum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ a₂ : α) : (@psum.inl α β a₁ = psum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ b₂ : β) : (@psum.inr α β b₁ = psum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (sigma.mk a₁ b₁ = sigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (psigma.mk a₁ b₁ = psigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : (subtype.mk a₁ h₁ = subtype.mk a₂ h₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma option.some.inj_eq {α : Type u} (a₁ a₂ : α) : (some a₁ = some a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : list α) (h₂ : α) (t₂ : list α) : (list.cons h₁ t₁ = list.cons h₂ t₂) = (h₁ = h₂ ∧ t₁ = t₂) := by tactic.mk_inj_eq lemma nat.succ.inj_eq (n₁ n₂ : nat) : (nat.succ n₁ = nat.succ n₂) = (n₁ = n₂) := by tactic.mk_inj_eq
c94ed9b78d5520b9ba721f2185f938f8e525fbb7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/polynomial/chebyshev/default_auto.lean
08ec1a30ea16e6b1c441e6e4b9dd0d1de821faf4
[]
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
169
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.polynomial.chebyshev.basic import Mathlib.PostPort namespace Mathlib end Mathlib
f46ab04853e5b3e21558a1d259e7bf5cf7e1515d
47c6e122a73eb61594f0426d74d9c1897ac5668e
/src/sylowthree.lean
b272d1be736572c3352e5bf69d0cebcd7a07b142
[]
no_license
ineswright/Lean-Sylow
19ec5d964be8a66e25e227621fbac79c88a83ddf
74b99544ab1ca96dc28fbe152125f565763a893b
refs/heads/main
1,688,108,643,799
1,627,664,383,000
1,627,664,383,000
382,315,172
1
0
null
null
null
null
UTF-8
Lean
false
false
1,153
lean
-- import group_theory.sylow import tactic import sylowtwo open equiv fintype finset mul_action function nat sylow open subgroup quotient_group universe u variables {G : Type u} [group G] open_locale classical /- * Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow `p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow `p`-subgroup in `G`. -/ -- def set_of_conjug_subgroups [fintype G] (L : subgroup G) : set (subgroup G) := -- { J | subgroups_are_conj L J ∧ ∃ p : ℕ, is_sylow_subgroup J p } def set_of_sylow_subgroups [fintype G] {p m n : ℕ} (hp : p.prime) (hG : card G = p ^ n * m) (hndiv: ¬ p ∣ m) : finset (subgroup G) := { L | is_sylow_subgroup L hp hG hndiv } def num_p_subgroups [fintype G] {p m n: ℕ} (hp : p.prime) (hG : card G = p ^ n * m) (hndiv: ¬ p ∣ m) : ℕ := card (set_of_sylow_subgroups hp hG hndiv) theorem sylow_three [fintype G] {p m n nₚ : ℕ} (hp : p.prime) (hG : card G = p ^ n * m) (hndiv: ¬ p ∣ m) (h₁ : nₚ = num_p_subgroups hp hG hndiv) : nₚ ≡ 1 [MOD p] := begin sorry, end
db3023b94925ac0ca39275b0b84bce0053c860d9
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/simp_omega.lean
14bda7377e446de65a505840f1d7c697dec2c0c9
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
844
lean
import logic.basic data.list.basic variables {α : Type} {p q : Prop} run_cmd mk_simp_attr `omega attribute [omega] list.map list.length_map zero_mul mul_zero zero_add add_zero neg_zero zero_sub sub_zero false_and and_false true_or or_true list.forall_mem_nil sub_self open lean open lean.parser open interactive open tactic meta def tactic.interactive.simp_omega (use_iota_eqn : parse $ optional (tk "!")) --(no_dflt : parse types.only_flag) (hs : parse simp_arg_list) (attr_names : parse types.with_ident_list) (locat : parse types.location) (cfg : simp_config_ext := {}) : tactic unit := let cfg := if use_iota_eqn.is_none then cfg else {iota_eqn := tt, ..cfg} in tactic.interactive.propagate_tags (tactic.interactive.simp_core cfg.to_simp_config cfg.discharger tt hs [`omega] locat)
3c816d031f60007f3b4722412e4b4cd27ae60e64
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/mv_polynomial/variables.lean
75bc64f2f31bc103f1169db281f000aeaa1fc927
[ "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
29,340
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, Johan Commelin, Mario Carneiro -/ import algebra.big_operators.order import data.mv_polynomial.monad /-! # Degrees and variables of polynomials This file establishes many results about the degree and variable sets of a multivariate polynomial. The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$ that appears in a monomial in $P$. The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a monomial of $P$. ## Main declarations * `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `mv_polynomial.degree_of n p : ℕ` : the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `mv_polynomial.total_degree p : ℕ` : the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Notation As in other polynomial files, we typically use the notation: + `σ τ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `r : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} section degrees /-! ### `degrees` -/ /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees (p : mv_polynomial σ R) : multiset σ := p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset := finset.sup_le $ assume t h, begin have := finsupp.support_single_subset h, rw [finset.mem_singleton] at this, rw this end lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) : degrees (monomial s a) = s.to_multiset := le_antisymm (degrees_monomial s a) $ finset.le_sup $ by rw [support_monomial, if_neg ha, finset.mem_singleton] lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 := multiset.le_zero.1 $ degrees_monomial _ _ lemma degrees_X' (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} := le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _ @[simp] lemma degrees_X [nontrivial R] (n : σ) : degrees (X n : mv_polynomial σ R) = {n} := (degrees_monomial_eq _ (1 : R) one_ne_zero).trans (to_multiset_single _ _) @[simp] lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 := by { rw ← C_0, exact degrees_C 0 } @[simp] lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1 lemma degrees_add (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin refine finset.sup_le (assume b hb, _), have := finsupp.support_add hb, rw finset.mem_union at this, cases this, { exact le_sup_of_le_left (finset.le_sup this) }, { exact le_sup_of_le_right (finset.le_sup this) }, end lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) := begin refine s.induction _ _, { simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_rfl }, { assume i s his ih, rw [finset.sup_insert, finset.sum_insert his], exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) } end lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees := begin refine finset.sup_le (assume b hb, _), have := support_mul p q hb, simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.to_multiset_add], exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) end lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees := begin refine s.induction _ _, { simp only [finset.prod_empty, finset.sum_empty, degrees_one] }, { assume i s his ih, rw [finset.prod_insert his, finset.sum_insert his], exact le_trans (degrees_mul _ _) (add_le_add_left ih _) } end lemma degrees_pow (p : mv_polynomial σ R) : ∀(n : ℕ), (p^n).degrees ≤ n • p.degrees | 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end | (n + 1) := by { rw [pow_succ, add_smul, add_comm, one_smul], exact le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) } lemma mem_degrees {p : mv_polynomial σ R} {i : σ} : i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support := by simp only [degrees, multiset.mem_sup, ← mem_support_iff, finsupp.mem_to_multiset, exists_prop] lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) : p.degrees ≤ (p + q).degrees := begin apply finset.sup_le, intros d hd, rw multiset.disjoint_iff_ne at h, rw multiset.le_iff_count, intros i, rw [degrees, multiset.count_finset_sup], simp only [finsupp.count_to_multiset], by_cases h0 : d = 0, { simp only [h0, zero_le, finsupp.zero_apply], }, { refine @finset.le_sup _ _ _ _ (p + q).support _ d _, rw [mem_support_iff, coeff_add], suffices : q.coeff d = 0, { rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], }, rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0, obtain ⟨j, hj⟩ := h0, contrapose! h, rw mem_support_iff at hd, refine ⟨j, _, j, _, rfl⟩, all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } } end lemma degrees_add_of_disjoint {p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) : (p + q).degrees = p.degrees ∪ q.degrees := begin apply le_antisymm, { apply degrees_add }, { apply multiset.union_le, { apply le_degrees_add h }, { rw add_comm, apply le_degrees_add h.symm } } end lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) : (map f p).degrees ⊆ p.degrees := begin dsimp only [degrees], apply multiset.subset_of_le, apply finset.sup_mono, apply mv_polynomial.support_map_subset end lemma degrees_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).degrees ⊆ (φ.degrees.map f) := begin intros i, rw [mem_degrees, multiset.mem_map], rintro ⟨d, hd, hi⟩, obtain ⟨x, rfl, hx⟩ := coeff_rename_ne_zero _ _ _ hd, simp only [map_domain, finsupp.mem_support_iff] at hi, rw [sum_apply, finsupp.sum] at hi, contrapose! hi, rw [finset.sum_eq_zero], intros j hj, simp only [exists_prop, mem_degrees] at hi, specialize hi j ⟨x, hx, hj⟩, rw [single_apply, if_neg hi], end lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R) {f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees := by simp only [degrees, mv_polynomial.support_map_of_injective _ hf] lemma degrees_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) : degrees (rename f p) = (degrees p).map f := begin simp only [degrees, multiset.map_finset_sup p.support finsupp.to_multiset f h, support_rename_of_injective h, finset.sup_image], refine finset.sup_congr rfl (λ x hx, _), exact (finsupp.to_multiset_map _ _).symm, end end degrees section vars /-! ### `vars` -/ /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ R) : finset σ := p.degrees.to_finset @[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support := by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_C, multiset.to_finset_zero] @[simp] lemma vars_X [nontrivial R] : (X n : mv_polynomial σ R).vars = {n} := by rw [X, vars_monomial (@one_ne_zero R _ _), finsupp.support_single_ne_zero _ (one_ne_zero : 1 ≠ 0)] lemma mem_vars (i : σ) : i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support := by simp only [vars, multiset.mem_to_finset, mem_degrees, mem_support_iff, exists_prop] lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) : x v = 0 := begin rw [vars, multiset.mem_to_finset] at h, rw ← finsupp.not_mem_support_iff, contrapose! h, unfold degrees, rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H), rw finset.sup_insert, simp only [multiset.mem_union, multiset.sup_eq_union], left, rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h, end lemma vars_add_subset (p q : mv_polynomial σ R) : (p + q).vars ⊆ p.vars ∪ q.vars := begin intros x hx, simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢, simpa using multiset.mem_of_le (degrees_add _ _) hx, end lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) : (p + q).vars = p.vars ∪ q.vars := begin apply finset.subset.antisymm (vars_add_subset p q), intros x hx, simp only [vars, multiset.disjoint_to_finset] at h hx ⊢, rw [degrees_add_of_disjoint h, multiset.to_finset_union], exact hx end section mul lemma vars_mul (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars := begin intro i, simp only [mem_vars, finset.mem_union], rintro ⟨d, hd, hi⟩, rw [mem_support_iff, coeff_mul] at hd, contrapose! hd, cases hd, rw finset.sum_eq_zero, rintro ⟨d₁, d₂⟩ H, rw finsupp.mem_antidiagonal at H, subst H, obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support, { simpa only [finset.mem_union] using finsupp.support_add hi, }, { suffices : coeff d₁ φ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, { suffices : coeff d₂ ψ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, end @[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ := vars_C lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars := begin induction n with n ih, { simp }, { rw pow_succ, apply finset.subset.trans (vars_mul _ _), exact finset.union_subset (finset.subset.refl _) ih } end /-- The variables of the product of a family of polynomials are a subset of the union of the sets of variables of each polynomial. -/ lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ R) : (∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) := begin apply s.induction_on, { simp }, { intros a s hs hsub, simp only [hs, finset.bUnion_insert, finset.prod_insert, not_false_iff], apply finset.subset.trans (vars_mul _ _), exact finset.union_subset_union (finset.subset.refl _) hsub } end section is_domain variables {A : Type*} [comm_ring A] [is_domain A] lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars := begin ext1 i, simp only [mem_vars, exists_prop, mem_support_iff], apply exists_congr, intro d, apply and_congr _ iff.rfl, rw [coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and], end end is_domain end mul section sum variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R) lemma vars_sum_subset : (∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has], refine finset.subset.trans (vars_add_subset _ _) (finset.union_subset_union (finset.subset.refl _) _), assumption } end lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) : (∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has, vars_add_of_disjoint, hsum], unfold pairwise on_fun at h, rw hsum, simp only [finset.disjoint_iff_ne] at h ⊢, intros v hv v2 hv2, rw finset.mem_bUnion at hv2, rcases hv2 with ⟨i, his, hi⟩, refine h a i _ _ hv _ hi, rintro rfl, contradiction } end end sum section map variables [comm_semiring S] (f : R →+* S) variable (p) lemma vars_map : (map f p).vars ⊆ p.vars := by simp [vars, degrees_map] variable {f} lemma vars_map_of_injective (hf : injective f) : (map f p).vars = p.vars := by simp [vars, degrees_map_of_injective _ hf] lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) : (monomial (finsupp.single i e) r).vars = {i} := by rw [vars_monomial hr, finsupp.support_single_ne_zero _ he] lemma vars_eq_support_bUnion_support : p.vars = p.support.bUnion finsupp.support := by { ext i, rw [mem_vars, finset.mem_bUnion] } end map end vars section degree_of /-! ### `degree_of` -/ /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := p.degrees.count n lemma degree_of_eq_sup (n : σ) (f : mv_polynomial σ R) : degree_of n f = f.support.sup (λ m, m n) := begin rw [degree_of, degrees, multiset.count_finset_sup], congr, ext, simp, end lemma degree_of_lt_iff {n : σ} {f : mv_polynomial σ R} {d : ℕ} (h : 0 < d) : degree_of n f < d ↔ ∀ m : σ →₀ ℕ, m ∈ f.support → m n < d := by rwa [degree_of_eq_sup n f, finset.sup_lt_iff] @[simp] lemma degree_of_zero (n : σ) : degree_of n (0 : mv_polynomial σ R) = 0 := by simp only [degree_of, degrees_zero, multiset.count_zero] @[simp] lemma degree_of_C (a : R) (x : σ): degree_of x (C a : mv_polynomial σ R) = 0 := by simp [degree_of, degrees_C] lemma degree_of_X (i j : σ) [nontrivial R] : degree_of i (X j : mv_polynomial σ R) = if i = j then 1 else 0 := begin by_cases c : i = j, { simp only [c, if_true, eq_self_iff_true, degree_of, degrees_X, multiset.count_singleton] }, simp [c, if_false, degree_of, degrees_X], end lemma degree_of_add_le (n : σ) (f g : mv_polynomial σ R) : degree_of n (f + g) ≤ max (degree_of n f) (degree_of n g) := begin repeat {rw degree_of}, apply (multiset.count_le_of_le n (degrees_add f g)).trans, dsimp, rw multiset.count_union, end lemma monomial_le_degree_of (i : σ) {f : mv_polynomial σ R} {m : σ →₀ ℕ} (h_m : m ∈ f.support) : m i ≤ degree_of i f := begin rw degree_of_eq_sup i, apply finset.le_sup h_m, end -- TODO we can prove equality here if R is a domain lemma degree_of_mul_le (i : σ) (f g: mv_polynomial σ R) : degree_of i (f * g) ≤ degree_of i f + degree_of i g := begin repeat {rw degree_of}, convert multiset.count_le_of_le i (degrees_mul f g), rw multiset.count_add, end lemma degree_of_mul_X_ne {i j : σ} (f : mv_polynomial σ R) (h : i ≠ j) : degree_of i (f * X j) = degree_of i f := begin repeat {rw degree_of_eq_sup i}, rw support_mul_X, simp only [finset.sup_map], congr, ext, simp only [ single, nat.one_ne_zero, add_right_eq_self, add_right_embedding_apply, coe_mk, pi.add_apply, comp_app, ite_eq_right_iff, coe_add ], cc, end /- TODO in the following we have equality iff f ≠ 0 -/ lemma degree_of_mul_X_eq (j : σ) (f : mv_polynomial σ R) : degree_of j (f * X j) ≤ degree_of j f + 1 := begin repeat {rw degree_of}, apply (multiset.count_le_of_le j (degrees_mul f (X j))).trans, simp only [multiset.count_add, add_le_add_iff_left], convert multiset.count_le_of_le j (degrees_X' j), rw multiset.count_singleton_self, end lemma degree_of_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) (i : σ) : degree_of (f i) (rename f p) = degree_of i p := by simp only [degree_of, degrees_rename_of_injective h, multiset.count_map_eq_count' f (p.degrees) h] end degree_of section total_degree /-! ### `total_degree` -/ /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e) lemma total_degree_eq (p : mv_polynomial σ R) : p.total_degree = p.support.sup (λm, m.to_multiset.card) := begin rw [total_degree], congr, funext m, exact (finsupp.card_to_multiset _).symm end lemma total_degree_le_degrees_card (p : mv_polynomial σ R) : p.total_degree ≤ p.degrees.card := begin rw [total_degree_eq], exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs) end @[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 := nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn, have _ := finsupp.support_single_subset hn, begin rw [finset.mem_singleton] at this, subst this, exact le_rfl end @[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : R) @[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 := total_degree_C (1 : R) @[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) : (X s : mv_polynomial σ R).total_degree = 1 := begin rw [total_degree, support_X], simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq], end lemma total_degree_add (a b : mv_polynomial σ R) : (a + b).total_degree ≤ max a.total_degree b.total_degree := finset.sup_le $ assume n hn, have _ := finsupp.support_add hn, begin rw finset.mem_union at this, cases this, { exact le_max_of_le_left (finset.le_sup this) }, { exact le_max_of_le_right (finset.le_sup this) } end lemma total_degree_add_eq_left_of_total_degree_lt {p q : mv_polynomial σ R} (h : q.total_degree < p.total_degree) : (p + q).total_degree = p.total_degree := begin classical, apply le_antisymm, { rw ← max_eq_left_of_lt h, exact total_degree_add p q, }, by_cases hp : p = 0, { simp [hp], }, obtain ⟨b, hb₁, hb₂⟩ := p.support.exists_mem_eq_sup (finsupp.support_nonempty_iff.mpr hp) (λ (m : σ →₀ ℕ), m.to_multiset.card), have hb : ¬ b ∈ q.support, { contrapose! h, rw [total_degree_eq p, hb₂, total_degree_eq], apply finset.le_sup h, }, have hbb : b ∈ (p + q).support, { apply support_sdiff_support_subset_support_add, rw finset.mem_sdiff, exact ⟨hb₁, hb⟩, }, rw [total_degree_eq, hb₂, total_degree_eq], exact finset.le_sup hbb, end lemma total_degree_add_eq_right_of_total_degree_lt {p q : mv_polynomial σ R} (h : q.total_degree < p.total_degree) : (q + p).total_degree = p.total_degree := by rw [add_comm, total_degree_add_eq_left_of_total_degree_lt h] lemma total_degree_mul (a b : mv_polynomial σ R) : (a * b).total_degree ≤ a.total_degree + b.total_degree := finset.sup_le $ assume n hn, have _ := add_monoid_algebra.support_mul a b hn, begin simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.sum_add_index'], { exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) }, { assume a, refl }, { assume a b₁ b₂, refl } end lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) : (a ^ n).total_degree ≤ n * a.total_degree := begin induction n with n ih, { simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] }, rw pow_succ, calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _ ... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _ ... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm] end @[simp] lemma total_degree_monomial (s : σ →₀ ℕ) {c : R} (hc : c ≠ 0) : (monomial s c : mv_polynomial σ R).total_degree = s.sum (λ _ e, e) := by simp [total_degree, support_monomial, if_neg hc] @[simp] lemma total_degree_X_pow [nontrivial R] (s : σ) (n : ℕ) : (X s ^ n : mv_polynomial σ R).total_degree = n := by simp [X_pow_eq_monomial, one_ne_zero] lemma total_degree_list_prod : ∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum | [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl | (p :: ps) := begin rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons], exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _) end lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) : s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum := begin refine quotient.induction_on s (assume l, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum], exact total_degree_list_prod l end lemma total_degree_finset_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end lemma total_degree_finset_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.sum f).total_degree ≤ finset.sup s (λ i, (f i).total_degree) := begin induction s using finset.cons_induction with a s has hind, { exact zero_le _ }, { rw [finset.sum_cons, finset.sup_cons, sup_eq_max], exact (mv_polynomial.total_degree_add _ _).trans (max_le_max le_rfl hind), } end lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ) (h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) : ∃ i, d i < n := begin contrapose! h, calc n * fintype.card σ = ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ] ... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s) ... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl } ... ≤ f.total_degree : finset.le_sup hd, end lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ} (h : f.total_degree < ∑ i in d.support, d i) : coeff d f = 0 := begin classical, rw [total_degree, finset.sup_lt_iff] at h, { specialize h d, rw mem_support_iff at h, refine not_not.mp (mt h _), exact lt_irrefl _, }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma total_degree_rename_le (f : σ → τ) (p : mv_polynomial σ R) : (rename f p).total_degree ≤ p.total_degree := finset.sup_le $ assume b, begin assume h, rw rename_eq at h, have h' := finsupp.map_domain_support h, rw finset.mem_image at h', rcases h' with ⟨s, hs, rfl⟩, rw finsupp.sum_map_domain_index, exact le_trans le_rfl (finset.le_sup hs), exact assume _, rfl, exact assume _ _ _, rfl end end total_degree section eval_vars /-! ### `vars` and `eval` -/ variables [comm_semiring S] lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : eval₂_hom f g p = f (constant_coeff p) := begin conv_lhs { rw p.as_sum }, simp only [ring_hom.map_sum, eval₂_hom_monomial], by_cases h0 : constant_coeff p = 0, work_on_goal 1 { rw [h0, f.map_zero, finset.sum_eq_zero], intros d hd }, work_on_goal 2 { rw [finset.sum_eq_single (0 : σ →₀ ℕ)], { rw [finsupp.prod_zero_index, mul_one], refl }, intros d hd hd0, }, repeat { obtain ⟨i, hi⟩ : d.support.nonempty, { rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0, rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty], rintro rfl, contradiction }, rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)], rw [mem_vars], exact ⟨d, hd, hi⟩ }, { rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0, intro, contradiction } end lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : aeval g p = algebra_map _ _ (constant_coeff p) := eval₂_hom_eq_constant_coeff_of_vars _ hp lemma eval₂_hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → (∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := begin rintro rfl h rfl, rename [p₁ p, f₁ f], rw p.as_sum, simp only [ring_hom.map_sum, eval₂_hom_monomial], apply finset.sum_congr rfl, intros d hd, congr' 1, simp only [finsupp.prod], apply finset.prod_congr rfl, intros i hi, have : i ∈ p.vars, { rw mem_vars, exact ⟨d, hd, hi⟩ }, rw h i this this, end /-- If `f₁` and `f₂` are ring homs out of the polynomial ring and `p₁` and `p₂` are polynomials, then `f₁ p₁ = f₂ p₂` if `p₁ = p₂` and `f₁` and `f₂` are equal on `R` and on the variables of `p₁`. -/ lemma hom_congr_vars {f₁ f₂ : mv_polynomial σ R →+* S} {p₁ p₂ : mv_polynomial σ R} (hC : f₁.comp C = f₂.comp C) (hv : ∀ i, i ∈ p₁.vars → i ∈ p₂.vars → f₁ (X i) = f₂ (X i)) (hp : p₁ = p₂) : f₁ p₁ = f₂ p₂ := calc f₁ p₁ = eval₂_hom (f₁.comp C) (f₁ ∘ X) p₁ : ring_hom.congr_fun (by ext; simp) _ ... = eval₂_hom (f₂.comp C) (f₂ ∘ X) p₂ : eval₂_hom_congr' hC hv hp ... = f₂ p₂ : ring_hom.congr_fun (by ext; simp) _ lemma exists_rename_eq_of_vars_subset_range (p : mv_polynomial σ R) (f : τ → σ) (hfi : injective f) (hf : ↑p.vars ⊆ set.range f) : ∃ q : mv_polynomial τ R, rename f q = p := ⟨bind₁ (λ i : σ, option.elim 0 X $ partial_inv f i) p, begin show (rename f).to_ring_hom.comp _ p = ring_hom.id _ p, refine hom_congr_vars _ _ _, { ext1, simp [algebra_map_eq] }, { intros i hip _, rcases hf hip with ⟨i, rfl⟩, simp [partial_inv_left hfi] }, { refl } end⟩ lemma vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : (bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) := begin calc (bind₁ f φ).vars = (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars : by { rw [← alg_hom.map_sum, ← φ.as_sum], } ... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) : vars_sum_subset _ _ ... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) : by simp only [bind₁_monomial] ... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below ... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below { apply finset.bUnion_mono, intros d hd, calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars ≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _ ... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars : by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl] ... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _ ... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _, apply finset.bUnion_mono, intros i hi, apply vars_pow, }, { intro j, simp_rw finset.mem_bUnion, rintro ⟨d, hd, ⟨i, hi, hj⟩⟩, exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ } end lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (bind₁ f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars := by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h lemma vars_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).vars ⊆ (φ.vars.image f) := begin intros i hi, simp only [vars, exists_prop, multiset.mem_to_finset, finset.mem_image] at hi ⊢, simpa only [multiset.mem_map] using degrees_rename _ _ hi end lemma mem_vars_rename (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ f i = j := by simpa only [exists_prop, finset.mem_image] using vars_rename f φ h end eval_vars end comm_semiring end mv_polynomial
867b919c8128b6a033d3d38ce16a261df3540770
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/category/pairwise.lean
a8a0a7e9d07ffe8cec76e9b959a8e58c91d190c0
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
4,201
lean
import topology.sheaves.sheaf import category_theory.limits.preserves.basic /-! # The category of "pairwise intersections". Given `ι : Type v`, we build the diagram category `pairwise ι` with objects `single i` and `pair i j`, for `i j : ι`, whose only non-identity morphisms are `left : single i ⟶ pair i j` and `right : single j ⟶ pair i j`. We use this later in describing the sheaf condition. Given any function `U : ι → α`, where `α` is some complete lattice (e.g. `opens X`), we produce a functor `pairwise ι ⥤ αᵒᵖ` in the obvious way, and show that `supr U` provides a limit cone over this functor. -/ noncomputable theory universes v u open topological_space open Top open opposite open category_theory open category_theory.limits namespace category_theory /-- An inductive type representing either a single term of a type `ι`, or a pair of terms. We use this as the objects of a category to describe the sheaf condition. -/ inductive pairwise (ι : Type v) | single : ι → pairwise | pair : ι → ι → pairwise variables {ι : Type v} namespace pairwise instance pairwise_inhabited [inhabited ι] : inhabited (pairwise ι) := ⟨single (default ι)⟩ /-- Morphisms in the category `pairwise ι`. The only non-identity morphisms are `left i j : single i ⟶ pair i j` and `right i j : single j ⟶ pair i j`. -/ inductive hom : pairwise ι → pairwise ι → Type v | id_single : Π i, hom (single i) (single i) | id_pair : Π i j, hom (pair i j) (pair i j) | left : Π i j, hom (single i) (pair i j) | right : Π i j, hom (single j) (pair i j) open hom instance hom_inhabited [inhabited ι] : inhabited (hom (single (default ι)) (single (default ι))) := ⟨id_single (default ι)⟩ /-- The identity morphism in `pairwise ι`. -/ def id : Π (o : pairwise ι), hom o o | (single i) := id_single i | (pair i j) := id_pair i j /-- Composition of morphisms in `pairwise ι`. -/ def comp : Π {o₁ o₂ o₃ : pairwise ι} (f : hom o₁ o₂) (g : hom o₂ o₃), hom o₁ o₃ | _ _ _ (id_single i) g := g | _ _ _ (id_pair i j) g := g | _ _ _ (left i j) (id_pair _ _) := left i j | _ _ _ (right i j) (id_pair _ _) := right i j section local attribute [tidy] tactic.case_bash instance : category (pairwise ι) := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, } end variables {α : Type v} (U : ι → α) section variables [semilattice_inf α] /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_obj : pairwise ι → αᵒᵖ | (single i) := op (U i) | (pair i j) := op (U i ⊓ U j) /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_map : Π {o₁ o₂ : pairwise ι} (f : o₁ ⟶ o₂), diagram_obj U o₁ ⟶ diagram_obj U o₂ | _ _ (id_single i) := 𝟙 _ | _ _ (id_pair i j) := 𝟙 _ | _ _ (left i j) := (hom_of_le inf_le_left).op | _ _ (right i j) := (hom_of_le inf_le_right).op /-- Given a function `U : ι → α` for `[semilattice_inf α]`, we obtain a functor `pairwise ι ⥤ αᵒᵖ`, sending `single i` to `op (U i)` and `pair i j` to `op (U i ⊓ U j)`, and the morphisms to the obvious inequalities. -/ @[simps] def diagram : pairwise ι ⥤ αᵒᵖ := { obj := diagram_obj U, map := λ X Y f, diagram_map U f, } end section -- `complete_lattice` is not really needed, as we only ever use `inf`, -- but the appropriate structure has not been defined. variables [complete_lattice α] /-- Auxilliary definition for `cone`. -/ def cone_π_app : Π (o : pairwise ι), op (supr U) ⟶ diagram_obj U o | (single i) := (hom_of_le (le_supr _ _)).op | (pair i j) := (hom_of_le inf_le_left ≫ hom_of_le (le_supr U i)).op /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a cone over `diagram U`. -/ @[simps] def cone : cone (diagram U) := { X := op (supr U), π := { app := cone_π_app U, } } /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a limit cone over `diagram U`. -/ def cone_is_limit : is_limit (cone U) := { lift := λ s, op_hom_of_le begin apply complete_lattice.Sup_le, rintros _ ⟨j, rfl⟩, exact le_of_op_hom (s.π.app (single j)) end } end end pairwise end category_theory
8e5aca21deb0799b03261437c834ad1bc429e1ca
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/ordered_ring.lean
4dc591c6e69ac045c4ad8732422c7548d1dc07a3
[ "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
42,604
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.ring import algebra.ordered_group set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true universe u variable {α : Type u} class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} lemma ordered_semiring.mul_le_mul_of_nonneg_left (a b c : α) (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin cases classical.em (b ≤ a), { simp [le_antisymm h h₁] }, cases classical.em (c ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_semiring.mul_lt_mul_of_pos_left a b c (lt_of_le_not_le h₁ h) (lt_of_le_not_le h₂ h_1))).left, end lemma ordered_semiring.mul_le_mul_of_nonneg_right (a b c : α) (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin cases classical.em (b ≤ a), { simp [le_antisymm h h₁] }, cases classical.em (c ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_semiring.mul_lt_mul_of_pos_right a b c (lt_of_le_not_le h₁ h) (lt_of_le_not_le h₂ h_1))).left, end lemma mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := ordered_semiring.mul_le_mul_of_nonneg_left a b c h₁ h₂ lemma mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := ordered_semiring.mul_le_mul_of_nonneg_right a b c h₁ h₂ lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ -- TODO: there are four variations, depending on which variables we assume to be nonneg lemma mul_le_mul (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_nonneg (ha : a ≥ 0) (hb : b ≥ 0) : a * b ≥ 0 := have h : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h -- `mul_nonneg` and `mul_pos` in core are stated in terms of `≥` and `>`, so we restate them here -- for use in syntactic tactics (e.g. `simp` and `rw`). lemma mul_nonneg' : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := mul_nonneg lemma mul_nonpos_of_nonneg_of_nonpos (ha : a ≥ 0) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : b ≥ 0) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_lt_mul (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul' (h1 : a ≤ c) (h2 : b < d) (h3 : b ≥ 0) (h4 : c > 0) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_pos (ha : a > 0) (hb : b > 0) : a * b > 0 := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_pos' (ha : 0 < a) (hb : 0 < b) : 0 < a * b := mul_pos ha hb lemma mul_neg_of_pos_of_neg (ha : a > 0) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : b > 0) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 (le_trans h1 h2) lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' (le_of_lt h2) h2 h1 (lt_of_le_of_lt h1 h2) end ordered_semiring class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_order α := (zero_lt_one : zero < one) section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} lemma zero_lt_one : 0 < (1:α) := linear_ordered_semiring.zero_lt_one lemma zero_le_one : 0 ≤ (1:α) := le_of_lt zero_lt_one lemma two_pos : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt two_pos) lemma two_gt_one : (2:α) > 1 := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma two_ge_one : (2:α) ≥ 1 := le_of_lt two_gt_one lemma four_pos : (4:α) > 0 := add_pos two_pos two_pos lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : c ≥ 0) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left h1 hc, not_lt_of_ge h2 h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : c ≥ 0) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right h1 hc, not_lt_of_ge h2 h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : c > 0) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, not_le_of_gt h2 h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : c > 0) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, not_le_of_gt h2 h) lemma pos_of_mul_pos_left (h : 0 < a * b) (h1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume h2 : b ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos h1 h2, not_lt_of_ge h3 h) lemma pos_of_mul_pos_right (h : 0 < a * b) (h1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume h2 : a ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg h2 h1, not_lt_of_ge h3 h) lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg h1 h2) h) lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos h2 h1) h) lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume h2 : b ≥ 0, not_lt_of_ge (mul_nonneg h1 h2) h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume h2 : a ≥ 0, not_lt_of_ge (mul_nonneg h2 h1) h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, not_le_of_gt (mul_pos h1 h2) h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, not_le_of_gt (mul_pos h2 h1) h) /-- `0 < 2`: an alternative version of `two_pos` that only assumes `linear_ordered_semiring`. -/ lemma zero_lt_two : (0:α) < 2 := by { rw [← zero_add (0:α), bit0], exact add_lt_add zero_lt_one zero_lt_one } @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h), λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h), λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left zero_lt_two] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left zero_lt_two] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left zero_lt_two] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left zero_lt_two] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left zero_lt_two] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left zero_lt_two] lemma mul_lt_mul'' (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := (lt_or_eq_of_le h4).elim (λ b0, mul_lt_mul h1 (le_of_lt h2) b0 (le_trans h3 (le_of_lt h1))) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (lt_of_le_of_lt h3 h1) (lt_of_le_of_lt h4 h2)) lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb lemma lt_mul_of_one_lt_right' (hb : 0 < b) : 1 < a → b < b * a := (lt_mul_iff_one_lt_right hb).2 lemma le_mul_of_one_le_right' (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_left' (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, mul_le_mul_of_nonneg_right h hb theorem mul_nonneg_iff_right_nonneg_of_pos (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := ⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩ lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := bit1_pos (le_of_lt h) lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos (le_refl _) zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } lemma one_lt_two : 1 < (2 : α) := lt_add_one _ lemma one_lt_mul (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := (one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha) lemma mul_le_one (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end lemma one_lt_mul_of_le_of_lt (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha) lemma one_lt_mul_of_lt_of_le (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul ha hb zero_lt_one (le_trans zero_le_one (le_of_lt ha)) lemma mul_le_of_le_one_right (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_left (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : mul_le_mul ha1 (le_refl b) hb zero_le_one ... = b : one_mul b lemma mul_lt_one_of_nonneg_of_lt_one_left (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_right (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 (not_le_of_gt h)) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 (not_le_of_gt h)) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_neg_of_pos_of_neg ha hb))) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_neg_of_neg_of_pos ha hb))) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonpos_of_nonneg_of_nonpos ha hb))) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonpos_of_nonpos_of_nonneg ha hb))) instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul (hf h) (hg $ le_of_lt h) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul' (hf $ le_of_lt h) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono class decidable_linear_ordered_semiring (α : Type u) extends linear_ordered_semiring α, decidable_linear_order α section decidable_linear_ordered_semiring variables [decidable_linear_ordered_semiring α] {a b c : α} @[simp] lemma decidable.mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h @[simp] lemma decidable.mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h end decidable_linear_ordered_semiring class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α, zero_ne_one_class α := (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) section ordered_ring variables [ordered_ring α] {a b c : α} lemma ordered_ring.mul_nonneg (a b : α) (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin cases classical.em (a ≤ 0), { simp [le_antisymm h h₁] }, cases classical.em (b ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (lt_of_le_not_le h₁ h) (lt_of_le_not_le h₂ h_1))).left, end lemma ordered_ring.mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ c * (b - a), from ordered_ring.mul_nonneg c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply lt_of_sub_pos this end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply lt_of_sub_pos this end instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } lemma mul_le_mul_of_nonpos_left {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this end ordered_ring class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α := (zero_lt_one : zero < one) section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } lemma mul_self_nonneg (a : α) : a * a ≥ 0 := or.elim (le_total 0 a) (assume h : a ≥ 0, mul_nonneg h h) (assume h : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos h h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := or.inl ⟨hlt₁, hlt₂⟩ | or.inr (or.inl heq₂) := begin rw [← heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := absurd hab (lt_asymm (mul_neg_of_pos_of_neg hlt₁ hgt₂)) end | or.inr (or.inl heq₁) := begin rw [← heq₁, zero_mul] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := absurd hab (lt_asymm (mul_neg_of_neg_of_pos hgt₁ hlt₂)) | or.inr (or.inl heq₂) := begin rw [← heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := or.inr ⟨hgt₁, hgt₂⟩ end end lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma zero_gt_neg_one : -1 < (0:α) := begin have this := neg_lt_neg (@zero_lt_one α _), rwa neg_zero at this end lemma le_of_mul_le_of_ge_one {a b c : α} (h : a * c ≤ b) (hb : b ≥ 0) (hc : c ≥ 1) : a ≤ b := have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (lt_of_lt_of_le zero_lt_one hc) lemma nonneg_le_nonneg_of_squares_le {a b : α} (hb : b ≥ 0) (h : a * a ≤ b * b) : a ≤ b := le_of_not_gt (λhab, not_le_of_gt (mul_self_lt_mul_self hb hab) h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := ⟨mul_self_le_mul_self h1, nonneg_le_nonneg_of_squares_le h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff $ mul_self_le_mul_self_iff h2 h1) $ iff.symm (lt_iff_not_ge _ _) lemma linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 < a * b, from mul_pos hlt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 > a * b, from mul_neg_of_pos_of_neg hlt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end | or.inr (or.inl heq₁) := or.inl heq₁.symm | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 > a * b, from mul_neg_of_neg_of_pos hgt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 < a * b, from mul_pos_of_neg_of_neg hgt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end end instance linear_ordered_ring.to_no_bot_order : no_bot_order α := ⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α _, ..‹linear_ordered_ring α› } @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin cases le_total 0 x, { exact mul_self_le_mul_self h h₁ }, { rw ← neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) h₂ } end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb))) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb))) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb))) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb))) /- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split; intro h, swap, { rcases h with ⟨rfl, rfl⟩, simp }, have : y * y ≤ 0, { rw [← h], apply le_add_of_nonneg_left (mul_self_nonneg x) }, have : y * y = 0 := le_antisymm this (mul_self_nonneg y), have hx : x = 0, { rwa [this, add_zero, mul_self_eq_zero] at h }, rw mul_self_eq_zero at this, split; assumption end end linear_ordered_ring class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α instance linear_ordered_comm_ring.to_integral_domain [s: linear_ordered_comm_ring α] : integral_domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α _, ..s } class decidable_linear_ordered_comm_ring (α : Type u) extends linear_ordered_comm_ring α, decidable_linear_ordered_add_comm_group α instance decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [d : decidable_linear_ordered_comm_ring α] : decidable_linear_ordered_semiring α := let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, add_right_cancel := @linear_ordered_semiring.add_right_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } section decidable_linear_ordered_comm_ring variables [decidable_linear_ordered_comm_ring α] {a b c : α} lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b := or.elim (le_total 0 a) (assume h1 : 0 ≤ a, or.elim (le_total 0 b) (assume h2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg h1 h2) ... = abs a * b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos h1 h2) ... = a * -b : by rw neg_mul_eq_mul_neg ... = abs a * -b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) (assume h1 : a ≤ 0, or.elim (le_total 0 b) (assume h2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg h1 h2) ... = -a * b : by rw neg_mul_eq_neg_mul ... = abs a * b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos h1 h2) ... = -a * -b : by rw neg_mul_neg ... = abs a * -b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) lemma abs_mul_self (a : α) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... ≥ b - c : sub_le_self _ (le_trans (abs_nonneg _) h)) else have habs : b - a ≤ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b ≤ c + a, from le_add_of_sub_right_le habs, sub_left_le_of_le_add habs' lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... > b - c : sub_lt_self _ (lt_of_le_of_lt (abs_nonneg _) h)) else have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b < c + a, from lt_add_of_sub_right_lt habs, sub_left_lt_of_lt_add habs' lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h) lemma abs_sub_square (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm, sub_eq_add_neg] end lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := have a * a ≤ (0 : α), from calc a * a ≤ a * a + b * b : le_add_of_nonneg_right (mul_self_nonneg b) ... = 0 : h, eq_zero_of_mul_self_eq_zero (le_antisymm this (mul_self_nonneg a)) lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, apply abs_nonneg, iterate {rw abs_sub_square}, iterate {rw abs_mul_abs_self}, apply sub_le_sub_left, iterate {rw mul_assoc}, apply mul_le_mul_of_nonneg_left, rw [← abs_mul], apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end -- The proof doesn't need commutativity but we have no `decidable_linear_ordered_ring` @[simp] lemma abs_two : abs (2:α) = 2 := abs_of_pos $ by refine zero_lt_two end decidable_linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, zero_ne_one_class α, nonneg_add_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring α] instance to_ordered_ring : ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, add_le_add_left := @add_le_add_left _ _, mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos, ..‹nonneg_ring α› } def to_linear_nonneg_ring (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, classical.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, classical.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..‹nonneg_ring α› } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring α] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring α := { mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..‹linear_nonneg_ring α› } @[priority 100] -- see Note [lower instance priority] instance to_linear_order : linear_order α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, ..‹linear_nonneg_ring α› } @[priority 100] -- see Note [lower instance priority] instance to_linear_ordered_ring : linear_ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := @le_total _ _, add_le_add_left := @add_le_add_left _ _, mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..‹linear_nonneg_ring α› } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `decidable_linear_ordered_comm_ring` -/ def to_decidable_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : decidable_linear_ordered_comm_ring α := { decidable_le := by apply_instance, decidable_lt := by apply_instance, mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ } end linear_nonneg_ring class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α, zero_ne_one_class α := (mul_eq_zero_iff (a b : α) : a * b = 0 ↔ a = 0 ∨ b = 0) namespace canonically_ordered_semiring variables [canonically_ordered_comm_semiring α] {a b : α} open canonically_ordered_add_monoid (le_iff_exists_add) lemma mul_le_mul {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a * c ≤ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul, _root_.add_assoc], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one : (0:α) < 1 := lt_of_le_of_ne (zero_le 1) zero_ne_one lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [zero_lt_iff_ne_zero, ne.def, canonically_ordered_comm_semiring.mul_eq_zero_iff, not_or_distrib] end canonically_ordered_semiring namespace with_top variables [canonically_ordered_comm_semiring α] [decidable_eq α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } instance : has_one (with_top α) := ⟨↑(1:α)⟩ lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] theorem top_ne_zero [partial_order α] : ⊤ ≠ (0 : with_top α) . @[simp] theorem zero_ne_top [partial_order α] : (0 : with_top α) ≠ ⊤ . @[simp] theorem coe_eq_zero [partial_order α] {a : α} : (a : with_top α) = 0 ↔ a = 0 := iff.intro (assume h, match a, h with _, rfl := rfl end) (assume h, h.symm ▸ rfl) @[simp] theorem zero_eq_coe [partial_order α] {a : α} : 0 = (a : with_top α) ↔ a = 0 := by rw [eq_comm, coe_eq_zero] @[simp] theorem coe_zero [partial_order α] : ↑(0 : α) = (0 : with_top α) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by simp [*, mul_def]; refl lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm private lemma comm (a b : with_top α) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin have H : ∀x:α, (¬x = 0) ↔ (⊤ : with_top α) * ↑x = ⊤ := λx, ⟨λhx, by simp [top_mul, hx], λhx f, by simpa [f] using hx⟩, cases a; cases b; simp [none_eq_top, top_mul, coe_ne_top, some_eq_coe, coe_mul.symm], { rw [H b] }, { rw [H a, comm] } end private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma mul_eq_zero (a b : with_top α) : a * b = 0 ↔ a = 0 ∨ b = 0 := by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, canonically_ordered_comm_semiring.mul_eq_zero_iff] at * private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top, mul_eq_zero b c] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a c] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a ↑b] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end private lemma one_mul' : ∀a : with_top α, 1 * a = a | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_bot.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_bot.coe_one] instance [canonically_ordered_comm_semiring α] [decidable_eq α] : canonically_ordered_comm_semiring (with_top α) := { one := (1 : α), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, mul_eq_zero_iff := mul_eq_zero, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], zero_ne_one := assume h, @zero_ne_one α _ $ option.some.inj h, .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_add_monoid } end with_top
e00b13b6ae6a7091214eda0206e60f00a5b6b473
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/exam_2/satisfiability/exam2.lean
77546cfd3c51eadb68cf16c4f8732e657dd1bbbb
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
10,140
lean
/- Justin Ngo jmn4fms 4/12/20 Sullivan 2102-001 -/ import .satisfiability import .rules_of_reasoning /- CS2102 Exam #2: Propositional Logic -/ /- #1. Define a predicate function, is_satisfiable: pExp → bool that returns true iff the given proposition is satisfiable. Hint: Model your answer on our definition of is_valid. You may need to define one or more helper functions. You should test your solution, but we will only grade your definition. Please write test cases in a separate file. Do not submit that file. -/ -- Answer here open pExp def foldr_or' : list bool → bool | [] := ff | (h::t) := bor h (foldr_or' t) def is_satisfiable (e : pExp) : bool := let n := number_of_variables_in_expression e in let is := interpretations_for_n_vars n in let rs := map_pEval_over_interps e is in foldr_or' rs /- #2. Clearly the propositions in rules_of_reasoning.lean that are valid are also satisfiable. But what about the following? Apply your satisfiability predicate function to decide whether or not each of the following formulae is satisfiable or not. Write an "#eval is_satisfiable e" command for each expression. A. The "fallacies" in that file (the ones that aren't valid). B. The proposition, pFalse. C. The following propositions: 1. P ∧ ¬ P 2. P ∨ ¬ P 3. = (¬x1 ∨ x2) ∧ (¬x2 ∨ x3 ∨ ¬x4) ∧ (x1 ∨ x2 ∨ x3 ∨ ¬x4) Note that for 3. you will have to define four new variables. Call them x1, x2, x3, and x4. -/ -- Answers here -- A. #eval is_satisfiable true_imp #eval is_satisfiable affirm_consequence #eval is_satisfiable affirm_disjunct #eval is_satisfiable deny_antecedent --B. #eval is_satisfiable pFalse --C. #eval is_satisfiable (P ∧ ¬ P) #eval is_satisfiable (P ∨ ¬ P) def x1 := pVar (var.mk 0) def x2 := pVar (var.mk 1) def x3 := pVar (var.mk 2) def x4 := pVar (var.mk 3) #eval is_satisfiable ((¬x1 ∨ x2) ∧ (¬x2 ∨ x3 ∨ ¬x4) ∧ (x1 ∨ x2 ∨ x3 ∨ ¬x4)) /- 3. In the previous problems, you defined a satisfiability predicate function that returns true or false depending on whether a given formula is satisfiable or not. Often we will want to know not only whether there exists a solution but an actual example of a solution, if there is one. Define a function called sat_solver : pExp → option (var → bool) that returns a satisfying interpretation (as "some interpretation") if there is one, or "none" otherwise. Hint: Model your solution on our validity checker. 1. First compute the list of interpretations for a given expression, e, 2. then reduce that list to a value of type option (var → bool). 3. Evaluate e under each interpretation in the list until either (A) you find one, call it i, for which e evaluates to true, or until you reach the empty list, empty handed. -/ -- Answer here def i := pEval def itr_find : (list bool) → (option (var → bool)) | [] := none | (h :: t) := match h with | ff := option.some i -- option.some interp | _ := itr_find t end def sat_solver (e : pExp) : option (var → bool) := let n := number_of_variables_in_expression e in let is := interpretations_for_n_vars n in let rs := map_pEval_over_interps e is in let x := itr_find rs in foldr_and rs /- 3.4. determine if there is at least one interpretation of a proposition that makes a certain proposition true, and if so return that interpretation -/ def itr_find' : (list bool) → (option (var → bool)) | [] := none | (h :: t) := match h with | tt := option.some i -- option.some interp | _ := itr_find t end def sat_solver' (e : pExp) : option (var → bool) := let n := number_of_variables_in_expression e in let is := interpretations_for_n_vars n in let rs := map_pEval_over_interps e is in let x := itr_find' rs in foldr_and rs /- 4. Define a predicate function, is_unsatisfiable : pExp → bool, that takes a propositional logic formula, e, and returns true iff e is unsatisfiable. Hint: Easy. Build on what you have. -/ -- Answer here def foldr_or'' : list bool → bool | [] := ff | (h::t) := bor h (foldr_or'' t) def is_unsatisfiable (e : pExp) : bool := let n := number_of_variables_in_expression e in let is := interpretations_for_n_vars n in let rs := map_pEval_over_interps e is in let x := foldr_or'' rs in not x /- 5. Given a propositional logic expression, e, and an incorrect claim that it's valid, we often want to produce a counter-example to that claim. Such a counter example is an interpretation under which the expression is not true. Equivalently, a counterexample is an interpretation under which the *negation* of the expression *is* true. Define a function, counterexample : pExp → option (var → bool), that takes any expression e and returns either a counterexample (as "some interpretation") or "none" if there isn't one. Hint: given e, try to find a model for the expression, ¬ e. -/ -- Answer here -- option is a type, look at notes on polymorphism def counterexample : pExp → option (var → bool) def counter (e : pExp) : option (var → bool) := let n := number_of_variables_in_expression e in let is := interpretations_for_n_vars n in let rs := map_pEval_over_interps e is in let x := counterexample rs in foldr_and rs /- 6. Give an English language example for every valid rule of reasoning in rules_of_reasoning.lean, and also give an English language counter-example for each fallacy. For example, for the rule, P >> Q >> P ∧ Q, you could say, "If the ball is red then if (in addition to that) the box is blue, then (in this context) the ball is red AND the box is blue." It will be easiest is you re-use the same words for P, Q, and R, in all of your examples. E.g., P means "the ball is red", Q means "the box is blue", etc. Copy the contents of rules_of_reasoning.lean into this comment block and under each rule give your English language sentence. P: Ball is red Q: Box is blue R: Cake is sweet def true_intro : pExp := pTrue - The ball is a ball def false_elim := pFalse >> P - If the ball is not a ball, then the ball is red def true_imp := pTrue >> P - If there is a ball, then the ball is red - Not always true because not all balls are red def and_intro := P >> Q >> P ∧ Q - If the ball is red, then if the box is blue, then the ball is red and the box is blue def and_elim_left := P ∧ Q >> P - If the ball is red and the box is blue, then the ball is red def and_elim_right := P ∧ Q >> Q - If the ball is red and the box is blue, then the box is blue def or_intro_left := P >> P ∨ Q - If the ball is red, then the ball is red or the box is blue def or_intro_right := Q >> P ∨ Q - If the box is blue, then the ball is red or the box is blue def or_elim := P ∨ Q >> (P >> R) >> (Q >> R) >> R - If the ball is red or the box is blue, then, if the ball is red then the cake is sweet, then, if the box is blue then the cake is sweet, then the cake is sweet def iff_intro := (P >> Q) >> (Q >> P) >> (P ↔ Q) - If the ball is red then the box is blue, then, if the box is blue then the ball is red, then, the ball is red implies the box is blue (a red ball implies a blue box) def iff_intro' := (P >> Q) ∧ (Q >> P) >> (P ↔ Q) - If the ball is red then the box is blue, and if the box is blue then the ball is red, then the ball is red implies the box is blue (a red ball implies a blue box) def iff_elim_left := (P ↔ Q) >> (P >> Q) - If the ball is red implies the box is blue, then if the ball is red then the box is blue def iff_elim_right := (P ↔ Q) >> (Q >> P) - If the ball is red implies the box is blue, then if the box is blue then the ball is red def arrow_elim := (P >> Q) >> (P >> Q) - If the ball is red then the box is blue, then, if the ball is red then the box is blue def resolution := (P ∨ Q) >> (¬ Q ∨ R) >> (P ∨ R) - If the ball is red or the box is blue, then, if the box is not blue or the cake is sweet, then the ball is red or the cake is sweet def unit_resolution := (P ∨ Q) >> ((¬ Q) >> P) - If the ball is red or the box is blue, then, if the box is not blue then the ball is red def syllogism := (P >> Q) >> (Q >> R) >> (P >> R) - If the box is red then the ball is blue, then, if the ball is blue then the cake is sweet, then if the box is red then the cake is sweet def modus_tollens := (P >> Q) >> (¬ Q >> ¬ P) - If the box is red then the ball is blue, then, if the ball is not blue then the box is not red def neg_elim := (¬ ¬ P) >> P - If the box is not red and that is not true, then the box is red. def excluded_middle := P ∨ (¬ P) - The box is red or the box is not red def neg_intro := (P >> pFalse) >> (¬ P) - If the box is red then the box is not a box, then the box is not red ----- P: It is raining outside Q: The streets are wet def affirm_consequence := (P >> Q) >> (Q >> P) - If it is raining outside then the streets are wet, then, if the streets are wet it is raining outside - Not always true because the streets can be wet without it having to rain -- if it is NOT raining outside, then the streets can be wet = TRUE -- if the streets are wet, then it is NOT raining outside = FALSE -- true >> false = false def affirm_disjunct := (P ∨ Q) >> (P >> ¬ Q) - If it is raining outside or the streets are wet, then, if it is raining outside then the streets are not wet - Not always true becuase if it is raining the streets can be wet -- if it is raining outside OR the streets are wet = TRUE -- if if its raining outside, then the streets are NOT wet = FALSE -- true >> false = false def deny_antecedent := (P >> Q) >> (¬ P >> ¬ Q) - If it is raining outside then the streets are wet, then, if it is not raining outside then the streets are not wet - Not always true because the streets can be wet for other reasons besides rain -- if it is raining outside the streets are wet = TRUE -- if it is NOT raining outside, then the streets can NOT be wet = FALSE -- true >> false = false -/
51aa86a725e7c78924f0b95335054ee8315cd503
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/universal/comparisons.1.lean
223d96c5b2c70323985bcfbb440a35505c223672
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
1,214
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .comparisons open tqft.categories open tqft.categories.functor open tqft.categories.natural_transformation open tqft.categories.isomorphism open tqft.categories.equivalence open tqft.categories.examples.types open tqft.categories.universal namespace tqft.categories.universal definition ConeCategories_agree { J C : Category } ( F : Functor J C ) : Equivalence (comma.Cones F) (Cones F) := { functor := comma_Cones_to_Cones F, inverse := Cones_to_comma_Cones F, isomorphism_1 := { morphism := { components := λ cone, ⟨ begin unfold_unfoldable, unfold_unfoldable, dsimp, split, exact (C.identity cone.fst), split, split, unfold Cone_to_comma_Cone._aux_1, dsimp, end, _ ⟩, naturality := ♯ }, inverse := { components := λ cone, begin unfold_unfoldable, split, end, naturality := ♯ }, witness_1 := sorry, witness_2 := sorry }, isomorphism_2 := { morphism := sorry, inverse := sorry, witness_1 := sorry, witness_2 := sorry } } end tqft.categories.universal
0bfa6c86770f6ecddd281e56723c2e0591bd4584
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/nested_begin.lean
423d8ba0291cbe4db62d0cee0b6b07bbca33f806
[ "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,272
lean
import logic data.nat.basic open nat inductive vector (A : Type) : nat → Type := | vnil : vector A zero | vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector definition no_confusion2 {A : Type} {n : nat} {P : Type} {v₁ v₂ : vector A n} : v₁ = v₂ → vector.no_confusion_type P v₁ v₂ := assume H₁₂ : v₁ = v₂, begin show vector.no_confusion_type P v₁ v₂, from have aux : v₁ = v₁ → vector.no_confusion_type P v₁ v₁, from take H₁₁, begin apply (vector.cases_on v₁), exact (assume h : P, h), intros [n, a, v, h], apply (h rfl), repeat (apply rfl), repeat (apply heq.refl) end, eq.rec_on H₁₂ aux H₁₂ end theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ := begin intro h, apply (vector.no_confusion h), intros, assumption end theorem vcons.inj₂ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → v₁ == v₂ := begin intro h, apply (vector.no_confusion h), intros, eassumption end end vector
e787eddd304a8d5aa7945375bde47e5307137931
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/hints/thursday/afternoon/category_theory/exercise2/hint7.lean
48650e9d9f7e1c6d722e54967ebbd1180c83ab1a
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
1,446
lean
import algebra.category.CommRing.basic import data.polynomial noncomputable theory -- the default implementation of polynomials is noncomputable local attribute [irreducible] polynomial.eval₂ def Ring.polynomial : Ring ⥤ Ring := { obj := λ R, Ring.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } def CommRing.polynomial : CommRing ⥤ CommRing := { obj := λ R, CommRing.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } open category_theory def commutes : (forget₂ CommRing Ring) ⋙ Ring.polynomial ≅ CommRing.polynomial ⋙ (forget₂ CommRing Ring) := { hom := { app := begin -- Let's think about the maths for a bit... -- Given a commutative ring, we can either forget that it is commutative and then take polynomials, -- or take polynomials and then forget that those are commutative. -- The result is exactly the same either way, so let's try: intro R, exact 𝟙 _, -- this says "use the identity on whatever makes this typecheck!" -- 🎉 end, naturality' := sorry, }, inv := { app := sorry, naturality' := sorry }, hom_inv_id' := sorry, inv_hom_id' := sorry, }. -- At this point the way forward is clear: -- * golf that construction to term mode -- * do the same thing for `inv`! -- * fill in the proof terms: `by tidy` is quite useful. -- * check the solutions to see if you managed to golf completely!
bd20fbe15d8ea7c86c6a62f64e6110b8c04114d3
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/uniform_space/uniform_field.lean
5d9541d9266cdb00446eb3731fe599173d24d45b
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
13,815
lean
/- The goal of this file is to prove the main part of Proposition 7 of Bourbaki GT III 6.8 : The completion hat K of a Hausdorff topological field is a field if the image under the mapping x ↦ x⁻¹ of every Cauchy filter (with respect to the additive uniform structure) which does not have a cluster point at 0 is a Cauchy filter (with respect to the additive uniform structure). Bourbaki does *not* prove this proposition, he refers to the general discussion of extending function defined on a dense subset with values in a complete Hausdorff space. In particular the subtlety about clustering at zero is totally left to readers. The main discussion revolves around the diagram x ↦ x⁻¹ K ←———— K^x ————————→ K^x ——————⟶ K | | | | | | | | ↓ ↓ ↓ ↓ hat K ←— hat K* - - → hat K* ——⟶ hat K Where hat K* := hat K ∖ {0}, which will hopefully become the units of hat K Of course there is type theory inclusion hell everywhere. Note that, by definition of a topological field, the unit group, endowed with multiplication and the topology *induced by inclusion*, is a topological group. Once the completion becomes a topological field, then we want the map units.map : units K → units (hat K) to be a continuous group morphism which is a dense embedding. All this is very general. The application we have in mind is extension of valuations. In this application K will be equipped with a valuation and the topology on K will be the nonarchimedean topology coming from v. Checking that this topology is completable in the sense of the current file is very easy on paper. But, in valuation/field.lean I can't even state it without type class search hell. Assuming we can prove that, the remaining work revolves around the diagram units K ———→ Γ | ↗ | / ↓ / units (hat K) but constructing that diagonal arrow is ok if the vertical one is indeed a dense group embedding. -/ import for_mathlib.uniform_space.ring import for_mathlib.topological_field import for_mathlib.division_ring noncomputable theory local attribute [instance, priority 0] classical.prop_decidable open filter lemma set.mem_compl_singleton_iff {α : Type*} (a x : α) : x ∈ -({a} : set α) ↔ x ≠ a := by simp only [set.mem_singleton_iff, set.mem_compl_eq] def cauchy_of {α : Type*} {β : Type*} [U : uniform_space β] (f : α → β) (F : filter α) := @cauchy α (uniform_space.comap f U) F lemma cauchy_of_iff_map {α : Type*} {β : Type*} [U : uniform_space β] (f : α → β) (F : filter α) : cauchy_of f F ↔ cauchy (map f F):= begin split ; intro h ; cases h with ne_bot H, { refine ⟨map_ne_bot ne_bot, _⟩, rwa [prod_map_map_eq, map_le_iff_le_comap] }, { split, { exact filter.ne_bot_of_map ne_bot }, { rwa [prod_map_map_eq, map_le_iff_le_comap] at H } }, end set_option class.instance_max_depth 100 open set ring_completion filter local attribute [instance] topological_add_group.to_uniform_space topological_add_group_is_uniform local notation `𝓝` x:70 := nhds x local notation `𝓤` := uniformity variables {K : Type*} [discrete_field K] [topological_space K] [topological_ring K] /-- Zero is not adherent to F -/ def zero_not_adh (F : filter $ units K) : Prop := comap units.val 𝓝 0 ⊓ F = ⊥ variables (K) def ts_units : topological_space (units K) := topological_space.induced units.val (by apply_instance) local attribute [instance] ts_units local notation `hat` K := ring_completion K def help_tc_search : uniform_space (hat K) := ring_completion.uniform_space K local attribute [instance] help_tc_search def help_tc_search' : separated (hat K) := ring_completion.separated K local attribute [instance] help_tc_search' def help_tc_search'' : complete_space (hat K) := ring_completion.complete_space K local attribute [instance] help_tc_search'' def hat_star := {x : hat K // x ≠ 0} def ts_hat_star : topological_space (hat_star K) := subtype.topological_space local attribute [instance] ts_hat_star instance [separated K] : zero_ne_one_class (hat K) := { zero_ne_one := assume h, zero_ne_one $ (uniform_embedding_coe K).1 h, ..ring_completion.comm_ring K } variables {K} lemma hat_units_ne_zero [separated K] (x : units $ hat K) : x.val ≠ 0 := assume h, have zero_one : (0 : hat K) = 1 := zero_mul x.inv ▸ (h ▸ x.val_inv), zero_ne_one zero_one variables (K) def coe_units [separated K] : units K → hat_star K := λ x, ⟨x.val, λ h, units.ne_zero x $ (uniform_embedding_coe K).1 h⟩ @[simp] lemma mul_coe_units [separated K] (x y : units K) : (coe_units K x).val * (coe_units K y).val = (coe_units K $ x*y).val := by { simp only [coe_units], rw ← (ring_completion.coe_is_ring_hom K).map_mul, refl } @[simp] lemma coe_units_val [separated K] (x : units K): (coe_units K x).val = (x.val : hat K) := rfl @[simp] lemma coe_units_one [separated K] : (coe_units K 1).val = 1 := by simpa [coe_units] @[simp] lemma division_ring.inv_val_eq_inv {α : Type*} [division_ring α] (x : units α) :(x : α)⁻¹ = x.inv := begin rw (show x.inv = (x⁻¹ : units α), from rfl), rw ←one_div_eq_inv, symmetry, apply eq_one_div_of_mul_eq_one, exact x.mul_inv end lemma coe_units_comm_square [separated K]: subtype.val ∘ coe_units K = (coe : K → hat K) ∘ units.val := by { ext x, simp [coe_units] } lemma range_units_val (K' : Type*) [discrete_field K']: range (units.val : units K' → K') = -{0} := begin ext x, rw mem_compl_singleton_iff, split, { rintro ⟨u, hu⟩ h', simpa [hu, h'] using u.val_inv }, { intro h, refine ⟨units.mk0 _ h, _⟩, simp [units.mk0] } end lemma de_coe_units [separated K] : dense_embedding (coe_units K : units K → hat_star K) := let de := uniform_embedding_coe K in ⟨λ ⟨x, x_ne⟩, begin have dense := ring_completion.dense_coe K x, rw mem_closure_iff_nhds at *, intros U U_nhds, have : ∃ V ∈ 𝓝 x, (0 : hat K) ∉ V ∧ subtype.val ⁻¹' V ⊆ U, { haveI : t1_space (hat K) := t2_space.t1_space, -- Why is this needed?! rw [nhds_induced] at U_nhds, rcases U_nhds with ⟨W, W_nhds, hW⟩, use [W ∩ -{0}, inter_mem_sets W_nhds (compl_singleton_mem_nhds x_ne)], split, { intro h, simpa only [not_true, mem_compl_eq, mem_singleton] using h.2 }, { intros z hz, exact hW hz.1 } }, -- no idea why this line is so slow rcases this with ⟨V, V_nhds, zero_V, hVU⟩, rcases exists_mem_of_ne_empty (dense V V_nhds) with ⟨y, yV, k, hky⟩, have y_ne : y ≠ 0, { intro h, apply zero_V, rwa ← h }, have : (⟨y, y_ne⟩ : hat_star K) ∈ U ∩ range (coe_units K), { split, { apply hVU, exact yV }, { have : k ≠ 0, { intro h, rw [h] at hky, exact y_ne hky.symm }, use units.mk0 k this, rw subtype.ext, exact hky, }, }, exact ne_empty_of_mem this end, begin intros x y h, rw subtype.ext at h, ext, exact de.1 h end , begin intro x, rw [nhds_induced units.val x, ← ring_completion.comap_nhds_eq x.val, nhds_subtype, comap_comap_comp, coe_units_comm_square K, ← comap_comap_comp], refl end⟩ lemma range_units_hat_star [separated K] : range (subtype.val : hat_star K → hat K) = -{0} := by { rw subtype.val_range, ext, rw mem_compl_singleton_iff, refl } section class completable_top_field : Prop := (separated : separated K) (nice : ∀ F : filter (units K), cauchy_of units.val F → zero_not_adh F → cauchy_of units.val (map (λ x, x⁻¹) F)) local attribute [instance] completable_top_field.separated variables [completable_top_field K] def inv_hat_star_hat : hat_star K → hat K := (de_coe_units K).extend (λ x, ((x⁻¹ : K) : hat K)) @[simp] lemma inv_hat_star_coe_units [separated K] (x : units K) : inv_hat_star_hat K (coe_units K x) = ((x⁻¹ : K) : hat K) := (de_coe_units K).extend_e_eq x lemma continuous_inv_hat_star_hat : continuous (inv_hat_star_hat K : hat_star K → hat K) := begin refine (de_coe_units K).continuous_extend _, intro x, set cu := coe_units K, letI : uniform_space (units K) := uniform_space.comap units.val _, letI : uniform_space (hat_star K) := uniform_space.comap subtype.val _, have ne_bot : comap cu 𝓝 x ≠ ⊥, from (de_coe_units K).comap_nhds_neq_bot, have cauchy_fact : cauchy_of units.val (comap cu $ 𝓝 x), { refine cauchy_comap _ cauchy_nhds ne_bot, have : (λ p : hat_star K × hat_star K, (p.1.val, p.2.val)) ∘ (λ p : units K × units K, (cu p.1, cu p.2)) = (λ p : K × K, ((p.1 : hat K), (p.2 : hat K))) ∘ (λ p : units K × units K, (p.1, p.2)), { ext ; simp [cu, coe_units] ; refl }, change comap (λ p : units K × units K, (cu p.1, cu p.2)) (comap (λ p : hat_star K × hat_star K, (p.1.val, p.2.val)) (𝓤 (hat K))) ≤ comap (λ p : units K × units K, (p.1.val, p.2.val)) (𝓤 K), rw comap_comm this, apply filter.comap_mono, exact ring_completion.comap_uniformity }, have zero_not : zero_not_adh (comap cu 𝓝 x), { have eq_bot : 𝓝 ↑(0 : K) ⊓ 𝓝 x.val = ⊥, { by_contradiction h, exact x.property (eq_of_nhds_neq_bot h).symm}, unfold zero_not_adh, rw [← ring_completion.comap_nhds_eq (0 : K), comap_comm (coe_units_comm_square K).symm, nhds_induced, ← comap_inf, ← comap_inf, comap_comap_comp, eq_bot], exact comap_bot }, have := completable_top_field.nice (comap cu 𝓝 x) cauchy_fact zero_not, have : cauchy (map units.val $ map (λ (x : units K), x⁻¹) (comap cu 𝓝 x)), from cauchy_map uniform_continuous_comap this, cases complete_space.complete (cauchy_map uniform_continuous_coe this) with y hy, use y, change map ((λ (x : units K), ↑(↑x)⁻¹) : units K → hat K) (comap cu 𝓝 x) ≤ 𝓝 y, repeat {rw filter.map_map at hy }, convert hy, ext, simp, end lemma inv_hat_is_inv : ∀ x : hat_star K, x.val*(inv_hat_star_hat K x) = 1 := begin have cl : is_closed {x : hat_star K | x.val*(inv_hat_star_hat K x) = 1}, from is_closed_eq (continuous_mul continuous_subtype_val (continuous_inv_hat_star_hat K)) continuous_const, have dense : closure (range (coe_units K)) = univ, from eq_univ_of_forall (de_coe_units K).dense, apply is_closed_property dense cl, intro x, rw [inv_hat_star_coe_units, division_ring.inv_val_eq_inv, coe_units_val, ← (ring_completion.coe_is_ring_hom K).map_mul, x.val_inv, (ring_completion.coe_is_ring_hom K).map_one] end lemma inv_hat_ne_zero (x : hat_star K) : inv_hat_star_hat K x ≠ 0 := λ h, begin have := inv_hat_is_inv K x, rw [h, mul_zero] at this, exact zero_ne_one this, end def inv_hat_star : hat_star K → hat_star K := λ x, ⟨inv_hat_star_hat K x, inv_hat_ne_zero K x⟩ lemma continuous_inv_hat_star : continuous (inv_hat_star K) := continuous_induced_rng (continuous_inv_hat_star_hat K) /-- homeomorphim between non-zero elements of hat K and units of hat K -/ def hat_star_is_units : hat_star K ≃ₜ units (hat K) := { to_fun := λ x, ⟨x.val, (inv_hat_star_hat K x), inv_hat_is_inv K x, mul_comm x.val (inv_hat_star_hat K x) ▸ (inv_hat_is_inv K x)⟩ , inv_fun := λ x, ⟨x.val, hat_units_ne_zero x⟩, left_inv := λ x, by simp, right_inv := λ x, units.ext rfl, continuous_to_fun := continuous_induced_rng continuous_induced_dom, continuous_inv_fun := continuous_induced_rng continuous_induced_dom } local notation `ψ` := (hat_star_is_units K).to_equiv.to_fun local notation `ψ⁻¹` := (hat_star_is_units K).to_equiv.inv_fun def hat_inv (x : hat K) : hat K := if h : x = 0 then 0 else inv_hat_star_hat K ⟨x , h⟩ lemma invinv : (λ (a : units (hat K)), a⁻¹) = ψ ∘ (inv_hat_star K) ∘ ψ⁻¹ := begin ext x, congr, apply mul_eq_one_iff_inv_eq.1, apply units.ext, exact inv_hat_is_inv K ⟨x.val, hat_units_ne_zero x⟩, end variables (K) lemma hat_inv_zero : hat_inv _ (0 : hat K) = (0 : hat K) := by simp [hat_inv] instance hat_has_inv : has_inv (hat K) := ⟨hat_inv K⟩ lemma hat_mul_inv : ∀ a : hat K, a ≠ 0 → a * a⁻¹ = 1 := begin intros a a_ne, change a * (hat_inv K a) = 1, simp [if_neg, a_ne, hat_inv, inv_hat_is_inv K ⟨a, a_ne⟩] end instance : discrete_field (hat K) := { inv := hat_inv K, zero_ne_one := assume h, discrete_field.zero_ne_one K ((uniform_embedding_coe K).1 h), mul_inv_cancel := hat_mul_inv K, inv_mul_cancel := by {intro, rw mul_comm, apply hat_mul_inv }, inv_zero := hat_inv_zero K, has_decidable_eq := by apply_instance, ..(by apply_instance : comm_ring (hat K)) } -- Unfortunately, the above instance loose TC search when it comes to finding a topology on -- units (hat K) -- TODO: investigate this issue def help_tcs : topological_space (units $ hat K) := topological_ring.units_topological_space _ local attribute [instance] help_tcs instance : topological_division_ring (hat K) := { continuous_inv := begin rw invinv K, exact (hat_star_is_units K).continuous_inv_fun.comp ( (continuous_inv_hat_star K).comp (hat_star_is_units K).continuous_to_fun) end, ..ring_completion.topological_ring K } def ring_completion.units_coe := (units.map (coe : K → hat K) : units K → units (hat K)) instance toto : topological_group (units $ hat K) := topological_division_ring.units_top_group _ lemma dense_units_map : dense_embedding (units.map (coe : K → hat K) : units K → units (hat K)) := begin rw show units.map (coe : K → hat K) = ((hat_star_is_units K) ∘ coe_units K), { funext, apply units.ext, refl }, exact dense_embedding.comp (de_coe_units _) (dense_embedding.of_homeo $ hat_star_is_units _), end end
8935e10dc2139f6d7c226783e39ef192645d30a2
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Control/Id.lean
7bbe9f963cc058deaf62da944c0d36f8d64be148
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
678
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich The identity Monad. -/ prelude import Init.Control.Lift universe u def Id (type : Type u) : Type u := type @[inline] def Id.pure {α : Type u} (x : α) : Id α := x @[inline] def Id.bind {α β : Type u} (x : Id α) (f : α → Id β) : Id β := f x @[inline] def Id.map {α β : Type u} (f : α → β) (x : Id α) : Id β := f x instance : Monad Id := { pure := @Id.pure, bind := @Id.bind, map := @Id.map } @[inline] def Id.run {α : Type u} (x : Id α) : α := x instance : MonadRun id Id := ⟨@Id.run⟩
2ae7613776d57aeb210532037d652efd6d846754
df561f413cfe0a88b1056655515399c546ff32a5
/8-inequality-world/l17.lean
232f261dd4942dbe2191c9413895dac93ab34979
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
123
lean
lemma lt_iff_succ_le (a b : mynat) : a < b ↔ succ a ≤ b := begin split, exact lt_aux_one a b, exact lt_aux_two a b, end
93a6b09f0328c06d15e9a2fccbf2288703dcd919
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/box_integral/partition/basic.lean
ce849353626fcd07ccb5dcf11f7fb32903d9ec05
[ "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
29,402
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 algebra.big_operators.option import analysis.box_integral.box.basic /-! # Partitions of rectangular boxes in `ℝⁿ` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define (pre)partitions of rectangular boxes in `ℝⁿ`. A partition of a box `I` in `ℝⁿ` (see `box_integral.prepartition` and `box_integral.prepartition.is_partition`) is a finite set of pairwise disjoint boxes such that their union is exactly `I`. We use `boxes : finset (box ι)` to store the set of boxes. Many lemmas about box integrals deal with pairwise disjoint collections of subboxes, so we define a structure `box_integral.prepartition (I : box_integral.box ι)` that stores a collection of boxes such that * each box `J ∈ boxes` is a subbox of `I`; * the boxes are pairwise disjoint as sets in `ℝⁿ`. Then we define a predicate `box_integral.prepartition.is_partition`; `π.is_partition` means that the boxes of `π` actually cover the whole `I`. We also define some operations on prepartitions: * `box_integral.partition.bUnion`: split each box of a partition into smaller boxes; * `box_integral.partition.restrict`: restrict a partition to a smaller box. We also define a `semilattice_inf` structure on `box_integral.partition I` for all `I : box_integral.box ι`. ## Tags rectangular box, partition -/ open set finset function open_locale classical nnreal big_operators noncomputable theory namespace box_integral variables {ι : Type*} /-- A prepartition of `I : box_integral.box ι` is a finite set of pairwise disjoint subboxes of `I`. -/ structure prepartition (I : box ι) := (boxes : finset (box ι)) (le_of_mem' : ∀ J ∈ boxes, J ≤ I) (pairwise_disjoint : set.pairwise ↑boxes (disjoint on (coe : box ι → set (ι → ℝ)))) namespace prepartition variables {I J J₁ J₂ : box ι} (π : prepartition I) {π₁ π₂ : prepartition I} {x : ι → ℝ} instance : has_mem (box ι) (prepartition I) := ⟨λ J π, J ∈ π.boxes⟩ @[simp] lemma mem_boxes : J ∈ π.boxes ↔ J ∈ π := iff.rfl @[simp] lemma mem_mk {s h₁ h₂} : J ∈ (mk s h₁ h₂ : prepartition I) ↔ J ∈ s := iff.rfl lemma disjoint_coe_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (h : J₁ ≠ J₂) : disjoint (J₁ : set (ι → ℝ)) J₂ := π.pairwise_disjoint h₁ h₂ h lemma eq_of_mem_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hx₁ : x ∈ J₁) (hx₂ : x ∈ J₂) : J₁ = J₂ := by_contra $ λ H, (π.disjoint_coe_of_mem h₁ h₂ H).le_bot ⟨hx₁, hx₂⟩ lemma eq_of_le_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle₁ : J ≤ J₁) (hle₂ : J ≤ J₂) : J₁ = J₂ := π.eq_of_mem_of_mem h₁ h₂ (hle₁ J.upper_mem) (hle₂ J.upper_mem) lemma eq_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle : J₁ ≤ J₂) : J₁ = J₂ := π.eq_of_le_of_le h₁ h₂ le_rfl hle lemma le_of_mem (hJ : J ∈ π) : J ≤ I := π.le_of_mem' J hJ lemma lower_le_lower (hJ : J ∈ π) : I.lower ≤ J.lower := box.antitone_lower (π.le_of_mem hJ) lemma upper_le_upper (hJ : J ∈ π) : J.upper ≤ I.upper := box.monotone_upper (π.le_of_mem hJ) lemma injective_boxes : function.injective (boxes : prepartition I → finset (box ι)) := by { rintro ⟨s₁, h₁, h₁'⟩ ⟨s₂, h₂, h₂'⟩ (rfl : s₁ = s₂), refl } @[ext] lemma ext (h : ∀ J, J ∈ π₁ ↔ J ∈ π₂) : π₁ = π₂ := injective_boxes $ finset.ext h /-- The singleton prepartition `{J}`, `J ≤ I`. -/ @[simps] def single (I J : box ι) (h : J ≤ I) : prepartition I := ⟨{J}, by simpa, by simp⟩ @[simp] lemma mem_single {J'} (h : J ≤ I) : J' ∈ single I J h ↔ J' = J := mem_singleton /-- We say that `π ≤ π'` if each box of `π` is a subbox of some box of `π'`. -/ instance : has_le (prepartition I) := ⟨λ π π', ∀ ⦃I⦄, I ∈ π → ∃ I' ∈ π', I ≤ I'⟩ instance : partial_order (prepartition I) := { le := (≤), le_refl := λ π I hI, ⟨I, hI, le_rfl⟩, le_trans := λ π₁ π₂ π₃ h₁₂ h₂₃ I₁ hI₁, let ⟨I₂, hI₂, hI₁₂⟩ := h₁₂ hI₁, ⟨I₃, hI₃, hI₂₃⟩ := h₂₃ hI₂ in ⟨I₃, hI₃, hI₁₂.trans hI₂₃⟩, le_antisymm := begin suffices : ∀ {π₁ π₂ : prepartition I}, π₁ ≤ π₂ → π₂ ≤ π₁ → π₁.boxes ⊆ π₂.boxes, from λ π₁ π₂ h₁ h₂, injective_boxes (subset.antisymm (this h₁ h₂) (this h₂ h₁)), intros π₁ π₂ h₁ h₂ J hJ, rcases h₁ hJ with ⟨J', hJ', hle⟩, rcases h₂ hJ' with ⟨J'', hJ'', hle'⟩, obtain rfl : J = J'', from π₁.eq_of_le hJ hJ'' (hle.trans hle'), obtain rfl : J' = J, from le_antisymm ‹_› ‹_›, assumption end } instance : order_top (prepartition I) := { top := single I I le_rfl, le_top := λ π J hJ, ⟨I, by simp, π.le_of_mem hJ⟩ } instance : order_bot (prepartition I) := { bot := ⟨∅, λ J hJ, false.elim hJ, λ J hJ, false.elim hJ⟩, bot_le := λ π J hJ, false.elim hJ } instance : inhabited (prepartition I) := ⟨⊤⟩ lemma le_def : π₁ ≤ π₂ ↔ ∀ J ∈ π₁, ∃ J' ∈ π₂, J ≤ J' := iff.rfl @[simp] lemma mem_top : J ∈ (⊤ : prepartition I) ↔ J = I := mem_singleton @[simp] lemma top_boxes : (⊤ : prepartition I).boxes = {I} := rfl @[simp] lemma not_mem_bot : J ∉ (⊥ : prepartition I) := id @[simp] lemma bot_boxes : (⊥ : prepartition I).boxes = ∅ := rfl /-- An auxiliary lemma used to prove that the same point can't belong to more than `2 ^ fintype.card ι` closed boxes of a prepartition. -/ lemma inj_on_set_of_mem_Icc_set_of_lower_eq (x : ι → ℝ) : inj_on (λ J : box ι, {i | J.lower i = x i}) {J | J ∈ π ∧ x ∈ J.Icc} := begin rintros J₁ ⟨h₁, hx₁⟩ J₂ ⟨h₂, hx₂⟩ (H : {i | J₁.lower i = x i} = {i | J₂.lower i = x i}), suffices : ∀ i, (Ioc (J₁.lower i) (J₁.upper i) ∩ Ioc (J₂.lower i) (J₂.upper i)).nonempty, { choose y hy₁ hy₂, exact π.eq_of_mem_of_mem h₁ h₂ hy₁ hy₂ }, intro i, simp only [set.ext_iff, mem_set_of_eq] at H, cases (hx₁.1 i).eq_or_lt with hi₁ hi₁, { have hi₂ : J₂.lower i = x i, from (H _).1 hi₁, have H₁ : x i < J₁.upper i, by simpa only [hi₁] using J₁.lower_lt_upper i, have H₂ : x i < J₂.upper i, by simpa only [hi₂] using J₂.lower_lt_upper i, rw [Ioc_inter_Ioc, hi₁, hi₂, sup_idem, set.nonempty_Ioc], exact lt_min H₁ H₂ }, { have hi₂ : J₂.lower i < x i, from (hx₂.1 i).lt_of_ne (mt (H _).2 hi₁.ne), exact ⟨x i, ⟨hi₁, hx₁.2 i⟩, ⟨hi₂, hx₂.2 i⟩⟩ } end /-- The set of boxes of a prepartition that contain `x` in their closures has cardinality at most `2 ^ fintype.card ι`. -/ lemma card_filter_mem_Icc_le [fintype ι] (x : ι → ℝ) : (π.boxes.filter (λ J : box ι, x ∈ J.Icc)).card ≤ 2 ^ fintype.card ι := begin rw [← fintype.card_set], refine finset.card_le_card_of_inj_on (λ J : box ι, {i | J.lower i = x i}) (λ _ _, finset.mem_univ _) _, simpa only [finset.mem_filter] using π.inj_on_set_of_mem_Icc_set_of_lower_eq x end /-- Given a prepartition `π : box_integral.prepartition I`, `π.Union` is the part of `I` covered by the boxes of `π`. -/ protected def Union : set (ι → ℝ) := ⋃ J ∈ π, ↑J lemma Union_def : π.Union = ⋃ J ∈ π, ↑J := rfl lemma Union_def' : π.Union = ⋃ J ∈ π.boxes, ↑J := rfl @[simp] lemma mem_Union : x ∈ π.Union ↔ ∃ J ∈ π, x ∈ J := set.mem_Union₂ @[simp] lemma Union_single (h : J ≤ I) : (single I J h).Union = J := by simp [Union_def] @[simp] lemma Union_top : (⊤ : prepartition I).Union = I := by simp [prepartition.Union] @[simp] lemma Union_eq_empty : π₁.Union = ∅ ↔ π₁ = ⊥ := by simp [← injective_boxes.eq_iff, finset.ext_iff, prepartition.Union, imp_false] @[simp] lemma Union_bot : (⊥ : prepartition I).Union = ∅ := Union_eq_empty.2 rfl lemma subset_Union (h : J ∈ π) : ↑J ⊆ π.Union := subset_bUnion_of_mem h lemma Union_subset : π.Union ⊆ I := Union₂_subset π.le_of_mem' @[mono] lemma Union_mono (h : π₁ ≤ π₂) : π₁.Union ⊆ π₂.Union := λ x hx, let ⟨J₁, hJ₁, hx⟩ := π₁.mem_Union.1 hx, ⟨J₂, hJ₂, hle⟩ := h hJ₁ in π₂.mem_Union.2 ⟨J₂, hJ₂, hle hx⟩ lemma disjoint_boxes_of_disjoint_Union (h : disjoint π₁.Union π₂.Union) : disjoint π₁.boxes π₂.boxes := finset.disjoint_left.2 $ λ J h₁ h₂, disjoint.le_bot (h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂)) ⟨J.upper_mem, J.upper_mem⟩ lemma le_iff_nonempty_imp_le_and_Union_subset : π₁ ≤ π₂ ↔ (∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J') ∧ π₁.Union ⊆ π₂.Union := begin fsplit, { refine λ H, ⟨λ J hJ J' hJ' Hne, _, Union_mono H⟩, rcases H hJ with ⟨J'', hJ'', Hle⟩, rcases Hne with ⟨x, hx, hx'⟩, rwa π₂.eq_of_mem_of_mem hJ' hJ'' hx' (Hle hx) }, { rintro ⟨H, HU⟩ J hJ, simp only [set.subset_def, mem_Union] at HU, rcases HU J.upper ⟨J, hJ, J.upper_mem⟩ with ⟨J₂, hJ₂, hx⟩, exact ⟨J₂, hJ₂, H _ hJ _ hJ₂ ⟨_, J.upper_mem, hx⟩⟩ } end lemma eq_of_boxes_subset_Union_superset (h₁ : π₁.boxes ⊆ π₂.boxes) (h₂ : π₂.Union ⊆ π₁.Union) : π₁ = π₂ := le_antisymm (λ J hJ, ⟨J, h₁ hJ, le_rfl⟩) $ le_iff_nonempty_imp_le_and_Union_subset.2 ⟨λ J₁ hJ₁ J₂ hJ₂ Hne, (π₂.eq_of_mem_of_mem hJ₁ (h₁ hJ₂) Hne.some_spec.1 Hne.some_spec.2).le, h₂⟩ /-- Given a prepartition `π` of a box `I` and a collection of prepartitions `πi J` of all boxes `J ∈ π`, returns the prepartition of `I` into the union of the boxes of all `πi J`. Though we only use the values of `πi` on the boxes of `π`, we require `πi` to be a globally defined function. -/ @[simps] def bUnion (πi : Π J : box ι, prepartition J) : prepartition I := { boxes := π.boxes.bUnion $ λ J, (πi J).boxes, le_of_mem' := λ J hJ, begin simp only [finset.mem_bUnion, exists_prop, mem_boxes] at hJ, rcases hJ with ⟨J', hJ', hJ⟩, exact ((πi J').le_of_mem hJ).trans (π.le_of_mem hJ') end, pairwise_disjoint := begin simp only [set.pairwise, finset.mem_coe, finset.mem_bUnion], rintro J₁' ⟨J₁, hJ₁, hJ₁'⟩ J₂' ⟨J₂, hJ₂, hJ₂'⟩ Hne, rw [function.on_fun, set.disjoint_left], rintros x hx₁ hx₂, apply Hne, obtain rfl : J₁ = J₂, from π.eq_of_mem_of_mem hJ₁ hJ₂ ((πi J₁).le_of_mem hJ₁' hx₁) ((πi J₂).le_of_mem hJ₂' hx₂), exact (πi J₁).eq_of_mem_of_mem hJ₁' hJ₂' hx₁ hx₂ end } variables {πi πi₁ πi₂ : Π J : box ι, prepartition J} @[simp] lemma mem_bUnion : J ∈ π.bUnion πi ↔ ∃ J' ∈ π, J ∈ πi J' := by simp [bUnion] lemma bUnion_le (πi : Π J, prepartition J) : π.bUnion πi ≤ π := λ J hJ, let ⟨J', hJ', hJ⟩ := π.mem_bUnion.1 hJ in ⟨J', hJ', (πi J').le_of_mem hJ⟩ @[simp] lemma bUnion_top : π.bUnion (λ _, ⊤) = π := by { ext, simp } @[congr] lemma bUnion_congr (h : π₁ = π₂) (hi : ∀ J ∈ π₁, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := by { subst π₂, ext J, simp [hi] { contextual := tt } } lemma bUnion_congr_of_le (h : π₁ = π₂) (hi : ∀ J ≤ I, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := bUnion_congr h $ λ J hJ, hi J (π₁.le_of_mem hJ) @[simp] lemma Union_bUnion (πi : Π J : box ι, prepartition J) : (π.bUnion πi).Union = ⋃ J ∈ π, (πi J).Union := by simp [prepartition.Union] @[simp] lemma sum_bUnion_boxes {M : Type*} [add_comm_monoid M] (π : prepartition I) (πi : Π J, prepartition J) (f : box ι → M) : ∑ J in π.boxes.bUnion (λ J, (πi J).boxes), f J = ∑ J in π.boxes, ∑ J' in (πi J).boxes, f J' := begin refine finset.sum_bUnion (λ J₁ h₁ J₂ h₂ hne, finset.disjoint_left.2 $ λ J' h₁' h₂', _), exact hne (π.eq_of_le_of_le h₁ h₂ ((πi J₁).le_of_mem h₁') ((πi J₂).le_of_mem h₂')) end /-- Given a box `J ∈ π.bUnion πi`, returns the box `J' ∈ π` such that `J ∈ πi J'`. For `J ∉ π.bUnion πi`, returns `I`. -/ def bUnion_index (πi : Π J, prepartition J) (J : box ι) : box ι := if hJ : J ∈ π.bUnion πi then (π.mem_bUnion.1 hJ).some else I lemma bUnion_index_mem (hJ : J ∈ π.bUnion πi) : π.bUnion_index πi J ∈ π := by { rw [bUnion_index, dif_pos hJ], exact (π.mem_bUnion.1 hJ).some_spec.fst } lemma bUnion_index_le (πi : Π J, prepartition J) (J : box ι) : π.bUnion_index πi J ≤ I := begin by_cases hJ : J ∈ π.bUnion πi, { exact π.le_of_mem (π.bUnion_index_mem hJ) }, { rw [bUnion_index, dif_neg hJ], exact le_rfl } end lemma mem_bUnion_index (hJ : J ∈ π.bUnion πi) : J ∈ πi (π.bUnion_index πi J) := by convert (π.mem_bUnion.1 hJ).some_spec.snd; exact dif_pos hJ lemma le_bUnion_index (hJ : J ∈ π.bUnion πi) : J ≤ π.bUnion_index πi J := le_of_mem _ (π.mem_bUnion_index hJ) /-- Uniqueness property of `box_integral.partition.bUnion_index`. -/ lemma bUnion_index_of_mem (hJ : J ∈ π) {J'} (hJ' : J' ∈ πi J) : π.bUnion_index πi J' = J := have J' ∈ π.bUnion πi, from π.mem_bUnion.2 ⟨J, hJ, hJ'⟩, π.eq_of_le_of_le (π.bUnion_index_mem this) hJ (π.le_bUnion_index this) (le_of_mem _ hJ') lemma bUnion_assoc (πi : Π J, prepartition J) (πi' : box ι → Π J : box ι, prepartition J) : π.bUnion (λ J, (πi J).bUnion (πi' J)) = (π.bUnion πi).bUnion (λ J, πi' (π.bUnion_index πi J) J) := begin ext J, simp only [mem_bUnion, exists_prop], fsplit, { rintro ⟨J₁, hJ₁, J₂, hJ₂, hJ⟩, refine ⟨J₂, ⟨J₁, hJ₁, hJ₂⟩, _⟩, rwa π.bUnion_index_of_mem hJ₁ hJ₂ }, { rintro ⟨J₁, ⟨J₂, hJ₂, hJ₁⟩, hJ⟩, refine ⟨J₂, hJ₂, J₁, hJ₁, _⟩, rwa π.bUnion_index_of_mem hJ₂ hJ₁ at hJ } end /-- Create a `box_integral.prepartition` from a collection of possibly empty boxes by filtering out the empty one if it exists. -/ def of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : prepartition I := { boxes := boxes.erase_none, le_of_mem' := λ J hJ, begin rw mem_erase_none at hJ, simpa only [with_bot.some_eq_coe, with_bot.coe_le_coe] using le_of_mem _ hJ end, pairwise_disjoint := λ J₁ h₁ J₂ h₂ hne, begin simp only [mem_coe, mem_erase_none] at h₁ h₂, exact box.disjoint_coe.1 (pairwise_disjoint h₁ h₂ (mt option.some_inj.1 hne)) end } @[simp] lemma mem_of_with_bot {boxes : finset (with_bot (box ι))} {h₁ h₂} : J ∈ (of_with_bot boxes h₁ h₂ : prepartition I) ↔ (J : with_bot (box ι)) ∈ boxes := mem_erase_none @[simp] lemma Union_of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : (of_with_bot boxes le_of_mem pairwise_disjoint).Union = ⋃ J ∈ boxes, ↑J := begin suffices : (⋃ (J : box ι) (hJ : ↑J ∈ boxes), ↑J) = ⋃ J ∈ boxes, ↑J, by simpa [of_with_bot, prepartition.Union], simp only [← box.bUnion_coe_eq_coe, @Union_comm _ _ (box ι), @Union_comm _ _ (@eq _ _ _), Union_Union_eq_right] end lemma of_with_bot_le {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes, J ≠ ⊥ → ∃ J' ∈ π, J ≤ ↑J') : of_with_bot boxes le_of_mem pairwise_disjoint ≤ π := have ∀ (J : box ι), ↑J ∈ boxes → ∃ J' ∈ π, J ≤ J', from λ J hJ, by simpa only [with_bot.coe_le_coe] using H J hJ with_bot.coe_ne_bot, by simpa [of_with_bot, le_def] lemma le_of_with_bot {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ π, ∃ J' ∈ boxes, ↑J ≤ J') : π ≤ of_with_bot boxes le_of_mem pairwise_disjoint := begin intros J hJ, rcases H J hJ with ⟨J', J'mem, hle⟩, lift J' to box ι using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hle, exact ⟨J', mem_of_with_bot.2 J'mem, with_bot.coe_le_coe.1 hle⟩ end lemma of_with_bot_mono {boxes₁ : finset (with_bot (box ι))} {le_of_mem₁ : ∀ J ∈ boxes₁, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₁ : set.pairwise (boxes₁ : set (with_bot (box ι))) disjoint} {boxes₂ : finset (with_bot (box ι))} {le_of_mem₂ : ∀ J ∈ boxes₂, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₂ : set.pairwise (boxes₂ : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes₁, J ≠ ⊥ → ∃ J' ∈ boxes₂, J ≤ J') : of_with_bot boxes₁ le_of_mem₁ pairwise_disjoint₁ ≤ of_with_bot boxes₂ le_of_mem₂ pairwise_disjoint₂ := le_of_with_bot _ $ λ J hJ, H J (mem_of_with_bot.1 hJ) with_bot.coe_ne_bot lemma sum_of_with_bot {M : Type*} [add_comm_monoid M] (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) (f : box ι → M) : ∑ J in (of_with_bot boxes le_of_mem pairwise_disjoint).boxes, f J = ∑ J in boxes, option.elim 0 f J := finset.sum_erase_none _ _ /-- Restrict a prepartition to a box. -/ def restrict (π : prepartition I) (J : box ι) : prepartition J := of_with_bot (π.boxes.image (λ J', J ⊓ J')) (λ J' hJ', by { rcases finset.mem_image.1 hJ' with ⟨J', -, rfl⟩, exact inf_le_left }) begin simp only [set.pairwise, on_fun, finset.mem_coe, finset.mem_image], rintro _ ⟨J₁, h₁, rfl⟩ _ ⟨J₂, h₂, rfl⟩ Hne, have : J₁ ≠ J₂, by { rintro rfl, exact Hne rfl }, exact ((box.disjoint_coe.2 $ π.disjoint_coe_of_mem h₁ h₂ this).inf_left' _).inf_right' _ end @[simp] lemma mem_restrict : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : with_bot (box ι)) = J ⊓ J' := by simp [restrict, eq_comm] lemma mem_restrict' : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : set (ι → ℝ)) = J ∩ J' := by simp only [mem_restrict, ← box.with_bot_coe_inj, box.coe_inf, box.coe_coe] @[mono] lemma restrict_mono {π₁ π₂ : prepartition I} (Hle : π₁ ≤ π₂) : π₁.restrict J ≤ π₂.restrict J := begin refine of_with_bot_mono (λ J₁ hJ₁ hne, _), rw finset.mem_image at hJ₁, rcases hJ₁ with ⟨J₁, hJ₁, rfl⟩, rcases Hle hJ₁ with ⟨J₂, hJ₂, hle⟩, exact ⟨_, finset.mem_image_of_mem _ hJ₂, inf_le_inf_left _ $ with_bot.coe_le_coe.2 hle⟩ end lemma monotone_restrict : monotone (λ π : prepartition I, restrict π J) := λ π₁ π₂, restrict_mono /-- Restricting to a larger box does not change the set of boxes. We cannot claim equality of prepartitions because they have different types. -/ lemma restrict_boxes_of_le (π : prepartition I) (h : I ≤ J) : (π.restrict J).boxes = π.boxes := begin simp only [restrict, of_with_bot, erase_none_eq_bUnion], refine finset.image_bUnion.trans _, refine (finset.bUnion_congr rfl _).trans finset.bUnion_singleton_eq_self, intros J' hJ', rw [inf_of_le_right, ← with_bot.some_eq_coe, option.to_finset_some], exact with_bot.coe_le_coe.2 ((π.le_of_mem hJ').trans h) end @[simp] lemma restrict_self : π.restrict I = π := injective_boxes $ restrict_boxes_of_le π le_rfl @[simp] lemma Union_restrict : (π.restrict J).Union = J ∩ π.Union := by simp [restrict, ← inter_Union, ← Union_def] @[simp] lemma restrict_bUnion (πi : Π J, prepartition J) (hJ : J ∈ π) : (π.bUnion πi).restrict J = πi J := begin refine (eq_of_boxes_subset_Union_superset (λ J₁ h₁, _) _).symm, { refine (mem_restrict _).2 ⟨J₁, π.mem_bUnion.2 ⟨J, hJ, h₁⟩, (inf_of_le_right _).symm⟩, exact with_bot.coe_le_coe.2 (le_of_mem _ h₁) }, { simp only [Union_restrict, Union_bUnion, set.subset_def, set.mem_inter_iff, set.mem_Union], rintro x ⟨hxJ, J₁, h₁, hx⟩, obtain rfl : J = J₁, from π.eq_of_mem_of_mem hJ h₁ hxJ (Union_subset _ hx), exact hx } end lemma bUnion_le_iff {πi : Π J, prepartition J} {π' : prepartition I} : π.bUnion πi ≤ π' ↔ ∀ J ∈ π, πi J ≤ π'.restrict J := begin fsplit; intros H J hJ, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rw mem_bUnion at hJ, rcases hJ with ⟨J₁, h₁, hJ⟩, rcases H J₁ h₁ hJ with ⟨J₂, h₂, Hle⟩, rcases π'.mem_restrict.mp h₂ with ⟨J₃, h₃, H⟩, exact ⟨J₃, h₃, Hle.trans $ with_bot.coe_le_coe.1 $ H.trans_le inf_le_right⟩ } end lemma le_bUnion_iff {πi : Π J, prepartition J} {π' : prepartition I} : π' ≤ π.bUnion πi ↔ π' ≤ π ∧ ∀ J ∈ π, π'.restrict J ≤ πi J := begin refine ⟨λ H, ⟨H.trans (π.bUnion_le πi), λ J hJ, _⟩, _⟩, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rintro ⟨H, Hi⟩ J' hJ', rcases H hJ' with ⟨J, hJ, hle⟩, have : J' ∈ π'.restrict J, from π'.mem_restrict.2 ⟨J', hJ', (inf_of_le_right $ with_bot.coe_le_coe.2 hle).symm⟩, rcases Hi J hJ this with ⟨Ji, hJi, hlei⟩, exact ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hlei⟩ } end instance : has_inf (prepartition I) := ⟨λ π₁ π₂, π₁.bUnion (λ J, π₂.restrict J)⟩ lemma inf_def (π₁ π₂ : prepartition I) : π₁ ⊓ π₂ = π₁.bUnion (λ J, π₂.restrict J) := rfl @[simp] lemma mem_inf {π₁ π₂ : prepartition I} : J ∈ π₁ ⊓ π₂ ↔ ∃ (J₁ ∈ π₁) (J₂ ∈ π₂), (J : with_bot (box ι)) = J₁ ⊓ J₂ := by simp only [inf_def, mem_bUnion, mem_restrict] @[simp] lemma Union_inf (π₁ π₂ : prepartition I) : (π₁ ⊓ π₂).Union = π₁.Union ∩ π₂.Union := by simp only [inf_def, Union_bUnion, Union_restrict, ← Union_inter, ← Union_def] instance : semilattice_inf (prepartition I) := { inf_le_left := λ π₁ π₂, π₁.bUnion_le _, inf_le_right := λ π₁ π₂, (bUnion_le_iff _).2 (λ J hJ, le_rfl), le_inf := λ π π₁ π₂ h₁ h₂, π₁.le_bUnion_iff.2 ⟨h₁, λ J hJ, restrict_mono h₂⟩, .. prepartition.has_inf, .. prepartition.partial_order } /-- The prepartition with boxes `{J ∈ π | p J}`. -/ @[simps] def filter (π : prepartition I) (p : box ι → Prop) : prepartition I := { boxes := π.boxes.filter p, le_of_mem' := λ J hJ, π.le_of_mem (mem_filter.1 hJ).1, pairwise_disjoint := λ J₁ h₁ J₂ h₂, π.disjoint_coe_of_mem (mem_filter.1 h₁).1 (mem_filter.1 h₂).1 } @[simp] lemma mem_filter {p : box ι → Prop} : J ∈ π.filter p ↔ J ∈ π ∧ p J := finset.mem_filter lemma filter_le (π : prepartition I) (p : box ι → Prop) : π.filter p ≤ π := λ J hJ, let ⟨hπ, hp⟩ := π.mem_filter.1 hJ in ⟨J, hπ, le_rfl⟩ lemma filter_of_true {p : box ι → Prop} (hp : ∀ J ∈ π, p J) : π.filter p = π := by { ext J, simpa using hp J } @[simp] lemma filter_true : π.filter (λ _, true) = π := π.filter_of_true (λ _ _, trivial) @[simp] lemma Union_filter_not (π : prepartition I) (p : box ι → Prop) : (π.filter (λ J, ¬p J)).Union = π.Union \ (π.filter p).Union := begin simp only [prepartition.Union], convert (@set.bUnion_diff_bUnion_eq _ (box ι) π.boxes (π.filter p).boxes coe _).symm, { ext J x, simp { contextual := tt } }, { convert π.pairwise_disjoint, simp } end lemma sum_fiberwise {α M} [add_comm_monoid M] (π : prepartition I) (f : box ι → α) (g : box ι → M) : ∑ y in π.boxes.image f, ∑ J in (π.filter (λ J, f J = y)).boxes, g J = ∑ J in π.boxes, g J := by convert sum_fiberwise_of_maps_to (λ _, finset.mem_image_of_mem f) g /-- Union of two disjoint prepartitions. -/ @[simps] def disj_union (π₁ π₂ : prepartition I) (h : disjoint π₁.Union π₂.Union) : prepartition I := { boxes := π₁.boxes ∪ π₂.boxes, le_of_mem' := λ J hJ, (finset.mem_union.1 hJ).elim π₁.le_of_mem π₂.le_of_mem, pairwise_disjoint := suffices ∀ (J₁ ∈ π₁) (J₂ ∈ π₂), J₁ ≠ J₂ → disjoint (J₁ : set (ι → ℝ)) J₂, by simpa [pairwise_union_of_symmetric (symmetric_disjoint.comap _), pairwise_disjoint], λ J₁ h₁ J₂ h₂ _, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂) } @[simp] lemma mem_disj_union (H : disjoint π₁.Union π₂.Union) : J ∈ π₁.disj_union π₂ H ↔ J ∈ π₁ ∨ J ∈ π₂ := finset.mem_union @[simp] lemma Union_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).Union = π₁.Union ∪ π₂.Union := by simp [disj_union, prepartition.Union, Union_or, Union_union_distrib] @[simp] lemma sum_disj_union_boxes {M : Type*} [add_comm_monoid M] (h : disjoint π₁.Union π₂.Union) (f : box ι → M) : ∑ J in π₁.boxes ∪ π₂.boxes, f J = ∑ J in π₁.boxes, f J + ∑ J in π₂.boxes, f J := sum_union $ disjoint_boxes_of_disjoint_Union h section distortion variable [fintype ι] /-- The distortion of a prepartition is the maximum of the distortions of the boxes of this prepartition. -/ def distortion : ℝ≥0 := π.boxes.sup box.distortion lemma distortion_le_of_mem (h : J ∈ π) : J.distortion ≤ π.distortion := le_sup h lemma distortion_le_iff {c : ℝ≥0} : π.distortion ≤ c ↔ ∀ J ∈ π, box.distortion J ≤ c := finset.sup_le_iff lemma distortion_bUnion (π : prepartition I) (πi : Π J, prepartition J) : (π.bUnion πi).distortion = π.boxes.sup (λ J, (πi J).distortion) := sup_bUnion _ _ @[simp] lemma distortion_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).distortion = max π₁.distortion π₂.distortion := sup_union lemma distortion_of_const {c} (h₁ : π.boxes.nonempty) (h₂ : ∀ J ∈ π, box.distortion J = c) : π.distortion = c := (sup_congr rfl h₂).trans (sup_const h₁ _) @[simp] lemma distortion_top (I : box ι) : distortion (⊤ : prepartition I) = I.distortion := sup_singleton @[simp] lemma distortion_bot (I : box ι) : distortion (⊥ : prepartition I) = 0 := sup_empty end distortion /-- A prepartition `π` of `I` is a partition if the boxes of `π` cover the whole `I`. -/ def is_partition (π : prepartition I) := ∀ x ∈ I, ∃ J ∈ π, x ∈ J lemma is_partition_iff_Union_eq {π : prepartition I} : π.is_partition ↔ π.Union = I := by simp_rw [is_partition, set.subset.antisymm_iff, π.Union_subset, true_and, set.subset_def, mem_Union, box.mem_coe] @[simp] lemma is_partition_single_iff (h : J ≤ I) : is_partition (single I J h) ↔ J = I := by simp [is_partition_iff_Union_eq] lemma is_partition_top (I : box ι) : is_partition (⊤ : prepartition I) := λ x hx, ⟨I, mem_top.2 rfl, hx⟩ namespace is_partition variables {π} lemma Union_eq (h : π.is_partition) : π.Union = I := is_partition_iff_Union_eq.1 h lemma Union_subset (h : π.is_partition) (π₁ : prepartition I) : π₁.Union ⊆ π.Union := h.Union_eq.symm ▸ π₁.Union_subset protected lemma exists_unique (h : π.is_partition) (hx : x ∈ I) : ∃! J ∈ π, x ∈ J := begin rcases h x hx with ⟨J, h, hx⟩, exact exists_unique.intro2 J h hx (λ J' h' hx', π.eq_of_mem_of_mem h' h hx' hx), end lemma nonempty_boxes (h : π.is_partition) : π.boxes.nonempty := let ⟨J, hJ, _⟩ := h _ I.upper_mem in ⟨J, hJ⟩ lemma eq_of_boxes_subset (h₁ : π₁.is_partition) (h₂ : π₁.boxes ⊆ π₂.boxes) : π₁ = π₂ := eq_of_boxes_subset_Union_superset h₂ $ h₁.Union_subset _ lemma le_iff (h : π₂.is_partition) : π₁ ≤ π₂ ↔ ∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J' := le_iff_nonempty_imp_le_and_Union_subset.trans $ and_iff_left $ h.Union_subset _ protected lemma bUnion (h : is_partition π) (hi : ∀ J ∈ π, is_partition (πi J)) : is_partition (π.bUnion πi) := λ x hx, let ⟨J, hJ, hxi⟩ := h x hx, ⟨Ji, hJi, hx⟩ := hi J hJ x hxi in ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hx⟩ protected lemma restrict (h : is_partition π) (hJ : J ≤ I) : is_partition (π.restrict J) := is_partition_iff_Union_eq.2 $ by simp [h.Union_eq, hJ] protected lemma inf (h₁ : is_partition π₁) (h₂ : is_partition π₂) : is_partition (π₁ ⊓ π₂) := is_partition_iff_Union_eq.2 $ by simp [h₁.Union_eq, h₂.Union_eq] end is_partition lemma Union_bUnion_partition (h : ∀ J ∈ π, (πi J).is_partition) : (π.bUnion πi).Union = π.Union := (Union_bUnion _ _).trans $ Union_congr_of_surjective id surjective_id $ λ J, Union_congr_of_surjective id surjective_id $ λ hJ, (h J hJ).Union_eq lemma is_partition_disj_union_of_eq_diff (h : π₂.Union = I \ π₁.Union) : is_partition (π₁.disj_union π₂ $ h.symm ▸ disjoint_sdiff_self_right) := is_partition_iff_Union_eq.2 $ (Union_disj_union _).trans $ by simp [h, π₁.Union_subset] end prepartition end box_integral
8f10e5e5001c24b0137d732d17cf9b089b699765
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/exercises_sources/friday/topology.lean
8397eddeea66d87704f4684fd212692f58fd67fc
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
12,134
lean
import topology.metric_space.basic open_locale classical filter topological_space namespace lftcm open filter set /-! # Filters ## Definition of filters -/ def principal {α : Type*} (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := begin sorry end, sets_of_superset := begin sorry end, inter_sets := begin sorry end} def at_top : filter ℕ := { sets := {s | ∃ a, ∀ b, a ≤ b → b ∈ s}, univ_sets := begin sorry end, sets_of_superset := begin sorry end, inter_sets := begin sorry end} -- The next exercise is slightly more tricky, you should probably keep it for later def nhds (x : ℝ) : filter ℝ := { sets := {s | ∃ ε > 0, Ioo (x - ε) (x + ε) ⊆ s}, univ_sets := begin sorry end, sets_of_superset := begin sorry end, inter_sets := begin sorry end} /- The filter axiom are also available as standalone lemmas where the filter argument is implicit Compare -/ #check @filter.sets_of_superset #check @mem_sets_of_superset -- And analogously: #check @inter_mem_sets /-! ## Definition of "tends to" -/ -- We'll practive using tendsto by reproving the composition lemma `tendsto.comp` from mathlib -- Let's first use the concrete definition recorded by `tendsto_def` #check @tendsto_def #check @preimage_comp example {α β γ : Type*} {A : filter α} {B : filter β} {C : filter γ} {f : α → β} {g : β → γ} (hf : tendsto f A B) (hg : tendsto g B C) : tendsto (g ∘ f) A C := begin sorry end -- Now let's get functorial (same statement as above, different proof packaging). example {α β γ : Type*} {A : filter α} {B : filter β} {C : filter γ} {f : α → β} {g : β → γ} (hf : tendsto f A B) (hg : tendsto g B C) : tendsto (g ∘ f) A C := begin calc map (g ∘ f) A = map g (map f A) : sorry ... ≤ map g B : sorry ... ≤ C : sorry, end /- Let's now focus on the pull-back operation `filter.comap` which takes `f : X → Y` and a filter `G` on `Y` and returns a filter on `X`. -/ #check @mem_comap_sets -- this is by definition, the proof is `iff.rfl` -- It also help to record a special case of one implication: #check @preimage_mem_comap -- The following exercise, which reproves `comap_ne_bot_iff` can start using #check @forall_sets_nonempty_iff_ne_bot example {α β : Type*} {f : filter β} {m : α → β} : comap m f ≠ ⊥ ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin sorry end /-! ## Properties holding eventually -/ /-- The next exercise only needs the definition of filters and the fact that `∀ᶠ x in f, p x` is a notation for `{x | p x} ∈ f`. It is called `eventually_and` in mathlib, and won't be needed below. For instance, applied to `α = ℕ` and the `at_top` filter above, it says that, given two predicates `p` and `q` on natural numbers, p n and q n for n large enough if and only if p n holds for n large enough and q n holds for n large enough. -/ example {α : Type*} {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := begin sorry end /-! ## Topological spaces -/ section -- This is how we can talk about two topological spaces X and Y variables {X Y : Type*} [topological_space X] [topological_space Y] /- Given a topological space `X` and some `A : set X`, we have the usual zoo of predicates `is_open A`, `is_closed A`, `is_connected A`, `is_compact A` (and some more) There are also additional type classes referring to properties of `X` itself, like `compact_space X` or `connected_space X` -/ /-- We can talk about continuous functions from `X` to `Y` -/ example (f : X → Y) : continuous f ↔ ∀ V, is_open V → is_open (f ⁻¹' V) := iff.rfl /- Each point `x` of a topological space has a neighborhood filter `𝓝 x` made of sets containing an open set containing `x`. It is always a proper filter, as recorded by `nhds_ne_bot` Asking for continuity is the same as asking for continuity at each point the right-hand side below is known as `continuous_at f x` -/ example (f : X → Y) : continuous f ↔ ∀ x, tendsto f (𝓝 x) (𝓝 (f x)) := continuous_iff_continuous_at /- The topological structure also brings operations on sets. To each `A : set X`, we can associate `closure A`, `interior A` and `frontier A`. We'll focus on `closure A`. It is defined as the intersection of closed sets containing `A` but we can characterize it in terms of neighborhoods. The most concrete version is `mem_closure_iff_nhds : a ∈ closure A ↔ ∀ B ∈ 𝓝 a, (B ∩ A).nonempty` We'll pratice by reproving the slightly more abstract `mem_closure_iff_comap_ne_bot`. First let's review sets and subtypes. Fix a type `X` and recall that `A : set X` is not a type a priori, but Lean coerces automatically when needed to the type `↥A` whose terms are build of a term `x : X` and a proof of `x ∈ A`. In the other direction, inhabitants of `↥A` can be coerced to `X` automatically. This inclusion coercion map is called `coe : A → X` and `coe a` is also denoted by `↑a`. Now assume `X` is a topological space, and let's understand the closure of A in terms of `coe` and the neighborhood filter. In the next exercise, you can use `simp_rw` instead of `rw` to rewrite inside a quantifier -/ #check nonempty_inter_iff_exists_right example {A : set X} {x : X} : x ∈ closure A ↔ comap (coe : A → X) (𝓝 x) ≠ ⊥ := begin sorry end /- In elementary contexts, the main property of `closure A` is that a converging sequence `u : ℕ → X` such that `∀ n, u n ∈ A` has its limit in `closure A`. Note we don't need all the full sequence to be in `A`, it's enough to ask it for `n` large enough, ie. `∀ᶠ n in at_top, u n ∈ A`. Also there is no reason to use sequences only, we can use any map and any source filter. We hence have the important `mem_closure_of_tendsto` : ∀ {f : β → X} {F : filter β} {a : X} {A : set X}, F ≠ ⊥ → tendsto f F (𝓝 a) → (∀ᶠ x in F, f x ∈ A) → a ∈ closure A If `A` is known to be closed then we can replace `closure A` by `A`, this is `mem_of_closed_of_tendsto`. -/ /- We need one last piece of filter technology: bases. By definition, each neighborhood of a point `x` contains an *open* neighborhood of `x`. Hence we can often restrict our attention to such neighborhoods. The general definition recording such a situation is: `has_basis` (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) You can now inspect three examples of how bases allow to restrict attention to certain elements of a filter. -/ #check @has_basis.mem_iff #check @has_basis.tendsto_left_iff #check @has_basis.tendsto_right_iff -- We'll use the following bases: #check @nhds_basis_opens' #check @closed_nhds_basis /-- Our main goal is now to prove the basic theorem which allows extension by continuity. From Bourbaki's general topology book, I.8.5, Theorem 1 (taking only the non-trivial implication): Let `X` be a topological space, `A` a dense subset of `X`, `f : A → Y` a mapping of `A` into a regular space `Y`. If, for each `x` in `X`, `f(y)` tends to a limit in `Y` when `y` tends to `x` while remaining in `A` then there exists a continuous extension `φ` of `f` to `X`. The regularity assumption on `Y` ensures that each point of `Y` has a basis of *closed* neighborhoods, this is `closed_nhds_basis`. It also ensures that `Y` is Hausdorff so limits in `Y` are unique, this is `tendsto_nhds_unique`. mathlib contains a refinement of the above lemma, `dense_inducing.continuous_at_extend`, but we'll stick to Bourbaki's version here. Remember that, given `A : set X`, `↥A` is the subtype associated to `A`, and Lean will automatically insert that funny up arrow when needed. And the (inclusion) coercion map is `coe : A → X`. The assumption "tends to `x` while remaining in `A`" corresponds to the pull-back filter `comap coe (𝓝 x)`. Let's prove first an auxilliary lemma, extracted to simplify the context (in particular we don't need Y to be a topological space here). -/ lemma aux {X Y A : Type*} [topological_space X] {c : A → X} {f : A → Y} {x : X} {F : filter Y} (h : tendsto f (comap c (𝓝 x)) F) {V' : set Y} (V'_in : V' ∈ F) : ∃ V ∈ 𝓝 x, is_open V ∧ c ⁻¹' V ⊆ f ⁻¹' V' := begin sorry end /-- Let's now turn to the main proof of the extension by continuity theorem. When Lean needs a topology on `↥A` it will use the induced topology, thanks to the instance `subtype.topological_space`. This all happens automatically. The only relevant lemma is `nhds_induced coe : ∀ a : ↥A, 𝓝 a = comap coe (𝓝 ↑a)` (this is actually a general lemma about induced topologies). The proof outline is: The main assumption and the axiom of choice give a function `φ` such that `∀ x, tendsto f (comap coe $ 𝓝 x) (𝓝 (φ x))` (because `Y` is Hausdorff, `φ` is entirely determined, but we won't need that until we try to prove that `φ` indeed extends `f`). Let's first prove `φ` is continuous. Fix any `x : X`. Since `Y` is regular, it suffices to check that for every *closed* neighborhood `V'` of `φ x`, `φ ⁻¹' V' ∈ 𝓝 x`. The limit assumption gives (through the auxilliary lemma above) some `V ∈ 𝓝 x` such `is_open V ∧ coe ⁻¹' V ⊆ f ⁻¹' V'`. Since `V ∈ 𝓝 x`, it suffices to prove `V ⊆ φ ⁻¹' V'`, ie `∀ y ∈ V, φ y ∈ V'`. Let's fix `y` in `V`. Because `V` is *open*, it is a neighborhood of `y`. In particular `coe ⁻¹' V ∈ comap coe (𝓝 y)` and a fortiori `f ⁻¹' V' ∈ comap coe (𝓝 y)`. In addition `comap coe $ 𝓝 y ≠ ⊥` because `A` is dense. Because we know `tendsto f (comap coe $ 𝓝 y) (𝓝 (φ y))` this implies `φ y ∈ closure V'` and, since `V'` is closed, we have proved `φ y ∈ V'`. It remains to prove that `φ` extends `f`. This is were continuity of `f` enters the discussion, together with the fact that `Y` is Hausdorff. -/ example [regular_space Y] {A : set X} (hA : ∀ x, x ∈ closure A) {f : A → Y} (f_cont : continuous f) (hf : ∀ x : X, ∃ c : Y, tendsto f (comap coe $ 𝓝 x) $ 𝓝 c) : ∃ φ : X → Y, continuous φ ∧ ∀ a : A, φ a = f a := begin sorry end end /-! ## Metric spaces -/ /-- We now leave general topology and turn to metric spaces. The distance function is denoted by `dist`. A slight difficulty here is that, as in Bourbaki, many results you may expect to see stated for metric spaces are stated for uniform spaces, a more general notion that also includes topological groups. In this tutorial we will avoid uniform spaces for simplicity. We will prove that continuous functions from a compact metric space to a metric space are uniformly continuous. mathlib has a much more general version (about functions between uniform spaces...). The lemma `metric.uniform_continuous_iff` allows to translate the general definition of uniform continuity to the ε-δ definition that works for metric spaces only. So let's fix `ε > 0` and start looking for `δ`. We will deduce Heine-Cantor from the fact that a real value continuous function on a nonempty compact set reaches its infimum. There are several ways to state that, but here we recommend `is_compact.exists_forall_le`. Let `φ : X × X → ℝ := λ p, dist (f p.1) (f p.2)` and let `K := { p : X × X | ε ≤ φ p }`. Observe `φ` is continuous by assumption on `f` and using `continuous_dist`. And `K` is closed using `is_closed_le` hence compact since `X` is compact. Then we discuss two possibilities using `eq_empty_or_nonempty`. If `K` is empty then we are clearly done (we can set `δ = 1` for instance). So let's assume `K` is not empty, and choose `(x₀, x₁)` attaining the infimum of `φ` on `K`. We can then set `δ = dist x₀ x₁` and check everything works. -/ example {X : Type*} [metric_space X] [compact_space X] {Y : Type*} [metric_space Y] {f : X → Y} (hf : continuous f) : uniform_continuous f := begin sorry end end lftcm
62e2827d1936c0281703bed4cb77117a3aba4075
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/module/basic.lean
aae5bdcfeedc7288ae6baedff578490134a726a0
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,469
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.big_operators.basic import algebra.smul_with_zero import group_theory.group_action.group /-! # Modules over a ring In this file we define * `module R M` : an additive commutative monoid `M` is a `module` over a `semiring R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. ## Implementation notes In typical mathematical usage, our definition of `module` corresponds to "semimodule", and the word "module" is reserved for `module R M` where `R` is a `ring` and `M` an `add_comm_group`. If `R` is a `field` and `M` an `add_comm_group`, `M` would be called an `R`-vector space. Since those assumptions can be made by changing the typeclasses applied to `R` and `M`, without changing the axioms in `module`, mathlib calls everything a `module`. In older versions of mathlib, we had separate `semimodule` and `vector_space` abbreviations. This caused inference issues in some cases, while not providing any real advantages, so we decided to use a canonical `module` typeclass throughout. ## Tags semimodule, module, vector space -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A module is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[protect_proj] class module (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] (r s : R) (x y : M) /-- A module over a semiring automatically inherits a `mul_action_with_zero` structure. -/ @[priority 100] -- see Note [lower instance priority] instance module.to_mul_action_with_zero : mul_action_with_zero R M := { smul_zero := smul_zero, zero_smul := module.zero_smul, ..(infer_instance : mul_action R M) } instance add_comm_monoid.nat_module : module ℕ M := { one_smul := one_nsmul, mul_smul := λ m n a, mul_nsmul a m n, smul_add := λ n a b, nsmul_add a b n, smul_zero := nsmul_zero, zero_smul := zero_nsmul, add_smul := λ r s x, add_nsmul x r s } theorem add_smul : (r + s) • x = r • x + s • x := module.add_smul r s x variables (R) theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] theorem two_smul' : (2 : R) • x = bit0 x := two_smul R x /-- Pullback a `module` structure along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.module [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `module` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.module [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_mul_action f smul } variables {R} (M) /-- Compose a `module` with a `ring_hom`, with action `f s • m`. See note [reducible non-instances]. -/ @[reducible] def module.comp_hom [semiring S] (f : S →+* R) : module S M := { smul := has_scalar.comp.smul f, add_smul := λ r s x, by simp [add_smul], .. mul_action_with_zero.comp_hom M f.to_monoid_with_zero_hom, .. distrib_mul_action.comp_hom M (f : S →* R) } variables (R) (M) /-- `(•)` as an `add_monoid_hom`. This is a stronger version of `distrib_mul_action.to_add_monoid_End` -/ @[simps apply_apply] def module.to_add_monoid_End : R →+* add_monoid.End M := { map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul], ..distrib_mul_action.to_add_monoid_End R M } /-- A convenience alias for `module.to_add_monoid_End` as a `monoid_hom`, usually to allow the use of `add_monoid_hom.flip`. -/ def smul_add_hom : R →+ M →+ M := (module.to_add_monoid_End R M).to_add_monoid_hom variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma module.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid variables (R) /-- An `add_comm_monoid` that is a `module` over a `ring` carries a natural `add_comm_group` structure. See note [reducible non-instances]. -/ @[reducible] def module.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [module R M] : add_comm_group M := { neg := λ a, (-1 : R) • a, add_left_neg := λ a, show (-1 : R) • a + a = 0, by { nth_rewrite 1 ← one_smul _ a, rw [← add_smul, add_left_neg, zero_smul] }, ..(infer_instance : add_comm_monoid M), } variables {R} section add_comm_group variables (R M) [semiring R] [add_comm_group M] instance add_comm_group.int_module : module ℤ M := { one_smul := one_gsmul, mul_smul := λ m n a, mul_gsmul a m n, smul_add := λ n a b, gsmul_add a b n, smul_zero := gsmul_zero, zero_smul := zero_gsmul, add_smul := λ r s x, add_gsmul x r s } /-- A structure containing most informations as in a module, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a module structure by checking less properties, in `module.of_core`. -/ @[nolint has_inhabited_instance] structure module.core extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `module` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `module.core`, when the underlying space is an `add_comm_group`. -/ def module.of_core (H : module.core R M) : module R M := by letI := H.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } end add_comm_group /-- To prove two module structures on a fixed `add_comm_monoid` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℕ M` and `module ℤ M` are subsingletons. @[ext] lemma module_ext {R : Type*} [semiring R] {M : Type*} [add_comm_monoid M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ }, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) @[simp] lemma neg_smul_neg : -r • -x = r • x := by rw [neg_smul, smul_neg, neg_neg] @[simp] theorem units.neg_smul (u : units R) (x : M) : -u • x = - (u • x) := by rw [units.smul_def, units.coe_neg, neg_smul, units.smul_def] variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] end module /-- A module over a `subsingleton` semiring is a `subsingleton`. We cannot register this as an instance because Lean has no way to guess `R`. -/ protected theorem module.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [module R M] : subsingleton M := ⟨λ x y, by rw [← one_smul R x, ← one_smul R y, subsingleton.elim (1:R) 0, zero_smul, zero_smul]⟩ @[priority 910] -- see Note [lower instance priority] instance semiring.to_module [semiring R] : module R R := { smul_add := mul_add, add_smul := add_mul, zero_smul := zero_mul, smul_zero := mul_zero } /-- Like `semiring.to_module`, but multiplies on the right. -/ @[priority 910] -- see Note [lower instance priority] instance semiring.to_opposite_module [semiring R] : module Rᵒᵖ R := { smul_add := λ r x y, add_mul _ _ _, add_smul := λ r x y, mul_add _ _ _, ..monoid_with_zero.to_opposite_mul_action_with_zero R} /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_module [semiring R] [semiring S] (f : R →+* S) : module R S := module.comp_hom S f /-- The tautological action by `R →+* R` on `R`. This generalizes `function.End.apply_mul_action`. -/ instance ring_hom.apply_distrib_mul_action [semiring R] : distrib_mul_action (R →+* R) R := { smul := ($), smul_zero := ring_hom.map_zero, smul_add := ring_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma ring_hom.smul_def [semiring R] (f : R →+* R) (a : R) : f • a = f a := rfl /-- `ring_hom.apply_distrib_mul_action` is faithful. -/ instance ring_hom.apply_has_faithful_scalar [semiring R] : has_faithful_scalar (R →+* R) R := ⟨ring_hom.ext⟩ section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] section variables (R) /-- `nsmul` is equal to any other module structure via a cast. -/ lemma nsmul_eq_smul_cast (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { rw [nat.succ_eq_add_one, nat.cast_succ, add_smul, add_smul, one_smul, ih, one_smul], } end end /-- Convert back any exotic `ℕ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_monoid`s should normally have exactly one `ℕ`-module structure by design. -/ lemma nat_smul_eq_nsmul (h : module ℕ M) (n : ℕ) (x : M) : @has_scalar.smul ℕ M h.to_has_scalar n x = n • x := by rw [nsmul_eq_smul_cast ℕ n x, nat.cast_id] /-- All `ℕ`-module structures are equal. Not an instance since in mathlib all `add_comm_monoid` should normally have exactly one `ℕ`-module structure by design. -/ def add_comm_monoid.nat_module.unique : unique (module ℕ M) := { default := by apply_instance, uniq := λ P, module_ext P _ $ λ n, nat_smul_eq_nsmul P n } instance add_comm_monoid.nat_is_scalar_tower : is_scalar_tower ℕ R M := { smul_assoc := λ n x y, nat.rec_on n (by simp only [zero_smul]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ih]) } instance add_comm_monoid.nat_smul_comm_class : smul_comm_class ℕ R M := { smul_comm := λ n r m, nat.rec_on n (by simp only [zero_smul, smul_zero]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ←ih, smul_add]) } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_comm_monoid.nat_smul_comm_class' : smul_comm_class R ℕ M := smul_comm_class.symm _ _ _ end add_comm_monoid section add_comm_group variables [semiring S] [ring R] [add_comm_group M] [module S M] [module R M] section variables (R) /-- `gsmul` is equal to any other module structure via a cast. -/ lemma gsmul_eq_smul_cast (n : ℤ) (b : M) : n • b = (n : R) • b := begin induction n using int.induction_on with p hp n hn, { rw [int.cast_zero, zero_smul, zero_smul] }, { rw [int.cast_add, int.cast_one, add_smul, add_smul, one_smul, one_smul, hp] }, { rw [int.cast_sub, int.cast_one, sub_smul, sub_smul, one_smul, one_smul, hn] }, end end /-- Convert back any exotic `ℤ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_group`s should normally have exactly one `ℤ`-module structure by design. -/ lemma int_smul_eq_gsmul (h : module ℤ M) (n : ℤ) (x : M) : @has_scalar.smul ℤ M h.to_has_scalar n x = n • x := by rw [gsmul_eq_smul_cast ℤ n x, int.cast_id] /-- All `ℤ`-module structures are equal. Not an instance since in mathlib all `add_comm_group` should normally have exactly one `ℤ`-module structure by design. -/ def add_comm_group.int_module.unique : unique (module ℤ M) := { default := by apply_instance, uniq := λ P, module_ext P _ $ λ n, int_smul_eq_gsmul P n } instance add_comm_group.int_is_scalar_tower : is_scalar_tower ℤ R M := { smul_assoc := λ n x y, int.induction_on n (by simp only [zero_smul]) (λ n ih, by simp only [one_smul, add_smul, ih]) (λ n ih, by simp only [one_smul, sub_smul, ih]) } instance add_comm_group.int_smul_comm_class : smul_comm_class ℤ S M := { smul_comm := λ n x y, int.induction_on n (by simp only [zero_smul, smul_zero]) (λ n ih, by simp only [one_smul, add_smul, smul_add, ih]) (λ n ih, by simp only [one_smul, sub_smul, smul_sub, ih]) } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_comm_group.int_smul_comm_class' : smul_comm_class S ℤ M := smul_comm_class.symm _ _ _ end add_comm_group namespace add_monoid_hom lemma map_nat_module_smul [add_comm_monoid M] [add_comm_monoid M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f (x • a) = x • f a := by simp only [f.map_nsmul] lemma map_int_module_smul [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [f.map_gsmul] lemma map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [←gsmul_eq_smul_cast, f.map_gsmul] lemma map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [←nsmul_eq_smul_cast, f.map_nsmul] lemma map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma map_rat_module_smul {E : Type*} [add_comm_group E] [module ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x end add_monoid_hom section no_zero_smul_divisors /-! ### `no_zero_smul_divisors` This section defines the `no_zero_smul_divisors` class, and includes some tests for the vanishing of elements (especially in modules over division rings). -/ /-- `no_zero_smul_divisors R M` states that a scalar multiple is `0` only if either argument is `0`. This a version of saying that `M` is torsion free, without assuming `R` is zero-divisor free. The main application of `no_zero_smul_divisors R M`, when `M` is a module, is the result `smul_eq_zero`: a scalar multiple is `0` iff either argument is `0`. It is a generalization of the `no_zero_divisors` class to heterogeneous multiplication. -/ class no_zero_smul_divisors (R M : Type*) [has_zero R] [has_zero M] [has_scalar R M] : Prop := (eq_zero_or_eq_zero_of_smul_eq_zero : ∀ {c : R} {x : M}, c • x = 0 → c = 0 ∨ x = 0) export no_zero_smul_divisors (eq_zero_or_eq_zero_of_smul_eq_zero) section module variables [semiring R] [add_comm_monoid M] [module R M] instance no_zero_smul_divisors.of_no_zero_divisors [no_zero_divisors R] : no_zero_smul_divisors R R := ⟨λ c x, no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[simp] theorem smul_eq_zero [no_zero_smul_divisors R M] {c : R} {x : M} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨eq_zero_or_eq_zero_of_smul_eq_zero, λ h, h.elim (λ h, h.symm ▸ zero_smul R x) (λ h, h.symm ▸ smul_zero c)⟩ theorem smul_ne_zero [no_zero_smul_divisors R M] {c : R} {x : M} : c • x ≠ 0 ↔ c ≠ 0 ∧ x ≠ 0 := by simp only [ne.def, smul_eq_zero, not_or_distrib] section nat variables (R) (M) [no_zero_smul_divisors R M] [char_zero R] include R lemma nat.no_zero_smul_divisors : no_zero_smul_divisors ℕ M := ⟨by { intros c x, rw [nsmul_eq_smul_cast R, smul_eq_zero], simp }⟩ variables {M} lemma eq_zero_of_smul_two_eq_zero {v : M} (hv : 2 • v = 0) : v = 0 := by haveI := nat.no_zero_smul_divisors R M; exact (smul_eq_zero.mp hv).resolve_left (by norm_num) end nat end module section add_comm_group -- `R` can still be a semiring here variables [semiring R] [add_comm_group M] [module R M] section smul_injective variables (M) lemma smul_right_injective [no_zero_smul_divisors R M] {c : R} (hc : c ≠ 0) : function.injective (λ (x : M), c • x) := λ x y h, sub_eq_zero.mp ((smul_eq_zero.mp (calc c • (x - y) = c • x - c • y : smul_sub c x y ... = 0 : sub_eq_zero.mpr h)).resolve_left hc) end smul_injective section nat variables (R) [no_zero_smul_divisors R M] [char_zero R] include R lemma eq_zero_of_eq_neg {v : M} (hv : v = - v) : v = 0 := begin haveI := nat.no_zero_smul_divisors R M, refine eq_zero_of_smul_two_eq_zero R _, rw two_smul, exact add_eq_zero_iff_eq_neg.mpr hv end end nat end add_comm_group section module variables [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] section smul_injective variables (R) lemma smul_left_injective {x : M} (hx : x ≠ 0) : function.injective (λ (c : R), c • x) := λ c d h, sub_eq_zero.mp ((smul_eq_zero.mp (calc (c - d) • x = c • x - d • x : sub_smul c d x ... = 0 : sub_eq_zero.mpr h)).resolve_right hx) end smul_injective section nat variables [char_zero R] lemma ne_neg_of_ne_zero [no_zero_divisors R] {v : R} (hv : v ≠ 0) : v ≠ -v := λ h, hv (eq_zero_of_eq_neg R h) end nat end module section division_ring variables [division_ring R] [add_comm_group M] [module R M] @[priority 100] -- see note [lower instance priority] instance no_zero_smul_divisors.of_division_ring : no_zero_smul_divisors R M := ⟨λ c x h, or_iff_not_imp_left.2 $ λ hc, (smul_eq_zero_iff_eq' hc).1 h⟩ end division_ring end no_zero_smul_divisors @[simp] lemma nat.smul_one_eq_coe {R : Type*} [semiring R] (m : ℕ) : m • (1 : R) = ↑m := by rw [nsmul_eq_mul, mul_one] @[simp] lemma int.smul_one_eq_coe {R : Type*} [ring R] (m : ℤ) : m • (1 : R) = ↑m := by rw [gsmul_eq_mul, mul_one]
3cc61a882aa2e62102b1bc6e339898141bb4c041
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/measure_theory/lp_space.lean
bc7fb052ef52879b0a37ab577b4f095900545d15
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
79,166
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import measure_theory.ess_sup import measure_theory.ae_eq_fun import analysis.mean_inequalities import topology.continuous_function.compact /-! # ℒp space and Lp space This file describes properties of almost everywhere measurable functions with finite seminorm, denoted by `snorm f p μ` and defined for `p:ℝ≥0∞` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`. The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm. The space `Lp E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and `Lp` is a complete metric space. ## Main definitions * `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable space and `F` is a normed group. * `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`. * `snorm f p μ` : for `p : ℝ≥0∞`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ` for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`. * `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite p-seminorm for measure `μ` (`snorm f p μ < ∞`) * `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined as an `add_subgroup` of `α →ₘ[μ] E`. Lipschitz functions vanishing at zero act by composition on `Lp`. We define this action, and prove that it is continuous. In particular, * `continuous_linear_map.comp_Lp` defines the action on `Lp` of a continuous linear map. * `Lp.pos_part` is the positive part of an `Lp` function. * `Lp.neg_part` is the negative part of an `Lp` function. When `α` is a topological space equipped with a finite Borel measure, there is a bounded linear map from the normed space of bounded continuous functions (`α →ᵇ E`) to `Lp E p μ`. We construct this as `bounded_continuous_function.to_Lp`. ## Notations * `α →₁[μ] E` : the type `Lp E 1 μ`. * `α →₂[μ] E` : the type `Lp E 2 μ`. ## Implementation Since `Lp` is defined as an `add_subgroup`, dot notation does not work. Use `Lp.measurable f` to say that the coercion of `f` to a genuine function is measurable, instead of the non-working `f.measurable`. To prove that two `Lp` elements are equal, it suffices to show that their coercions to functions coincide almost everywhere (this is registered as an `ext` rule). This can often be done using `filter_upwards`. For instance, a proof from first principles that `f + (g + h) = (f + g) + h` could read (in the `Lp` namespace) ``` example (f g h : Lp E p μ) : (f + g) + h = f + (g + h) := begin ext1, filter_upwards [coe_fn_add (f + g) h, coe_fn_add f g, coe_fn_add f (g + h), coe_fn_add g h], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, add_assoc], end ``` The lemma `coe_fn_add` states that the coercion of `f + g` coincides almost everywhere with the sum of the coercions of `f` and `g`. All such lemmas use `coe_fn` in their name, to distinguish the function coercion from the coercion to almost everywhere defined functions. -/ noncomputable theory open topological_space measure_theory filter open_locale nnreal ennreal big_operators topological_space lemma fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_refl _⟩ lemma fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) := ⟨ennreal.coe_le_coe.2 (show (1 : ℝ≥0) ≤ 2, by norm_num)⟩ lemma fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := ⟨le_top⟩ local attribute [instance] fact_one_le_one_ennreal fact_one_le_two_ennreal fact_one_le_top_ennreal variables {α E F G : Type*} [measurable_space α] {p : ℝ≥0∞} {q : ℝ} {μ : measure α} [measurable_space E] [normed_group E] [normed_group F] [normed_group G] namespace measure_theory section ℒp /-! ### ℒp seminorm We define the ℒp seminorm, denoted by `snorm f p μ`. For real `p`, it is given by an integral formula (for which we use the notation `snorm' f p μ`), and for `p = ∞` it is the essential supremum (for which we use the notation `snorm_ess_sup f μ`). We also define a predicate `mem_ℒp f p μ`, requesting that a function is almost everywhere measurable and has finite `snorm f p μ`. This paragraph is devoted to the basic properties of these definitions. It is constructed as follows: for a given property, we prove it for `snorm'` and `snorm_ess_sup` when it makes sense, deduce it for `snorm`, and translate it in terms of `mem_ℒp`. -/ section ℒp_space_definition /-- `(∫ ∥f a∥^q ∂μ) ^ (1/q)`, which is a seminorm on the space of measurable functions for which this quantity is finite -/ def snorm' (f : α → F) (q : ℝ) (μ : measure α) : ℝ≥0∞ := (∫⁻ a, (nnnorm (f a))^q ∂μ) ^ (1/q) /-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/ def snorm_ess_sup (f : α → F) (μ : measure α) := ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) μ /-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to `ess_sup ∥f∥ μ` for `p = ∞`. -/ def snorm (f : α → F) (p : ℝ≥0∞) (μ : measure α) : ℝ≥0∞ := if p = 0 then 0 else (if p = ∞ then snorm_ess_sup f μ else snorm' f (ennreal.to_real p) μ) lemma snorm_eq_snorm' (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} : snorm f p μ = snorm' f (ennreal.to_real p) μ := by simp [snorm, hp_ne_zero, hp_ne_top] @[simp] lemma snorm_exponent_top {f : α → F} : snorm f ∞ μ = snorm_ess_sup f μ := by simp [snorm] /-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite if `p < ∞`, or `ess_sup f < ∞` if `p = ∞`. -/ def mem_ℒp (f : α → E) (p : ℝ≥0∞) (μ : measure α) : Prop := ae_measurable f μ ∧ snorm f p μ < ∞ lemma mem_ℒp.ae_measurable {f : α → E} {p : ℝ≥0∞} {μ : measure α} (h : mem_ℒp f p μ) : ae_measurable f μ := h.1 lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hq0_lt : 0 < q) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ = (snorm' f q μ) ^ q := begin rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one], exact (ne_of_lt hq0_lt).symm, end end ℒp_space_definition section top lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ < ∞ := hfp.2 lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ∞ := ne_of_lt (hfp.2) lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hq0_lt : 0 < q) (hfq : snorm' f q μ < ∞) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ < ∞ := begin rw lintegral_rpow_nnnorm_eq_rpow_snorm' hq0_lt, exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hq0_lt) (ne_of_lt hfq), end end top section zero @[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 := by rw [snorm', div_zero, ennreal.rpow_zero] @[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 := by simp [snorm] lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ := by simp [mem_ℒp, snorm_exponent_zero] @[simp] lemma snorm'_zero (hp0_lt : 0 < q) : snorm' (0 : α → F) q μ = 0 := by simp [snorm', hp0_lt] @[simp] lemma snorm'_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) q μ = 0 := begin cases le_or_lt 0 q with hq0 hq_neg, { exact snorm'_zero (lt_of_le_of_ne hq0 hq0_ne.symm), }, { simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hq_neg], }, end @[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 := begin simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero], exact ess_sup_const_bot, end @[simp] lemma snorm_zero : snorm (0 : α → F) p μ = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma zero_mem_ℒp : mem_ℒp (0 : α → E) p μ := ⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩ lemma snorm'_measure_zero_of_pos {f : α → F} (hq_pos : 0 < q) : snorm' f q 0 = 0 := by simp [snorm', hq_pos] lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 0 = 1 := by simp [snorm'] lemma snorm'_measure_zero_of_neg {f : α → F} (hq_neg : q < 0) : snorm' f q 0 = ∞ := by simp [snorm', hq_neg] @[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f 0 = 0 := by simp [snorm_ess_sup] @[simp] lemma snorm_measure_zero {f : α → F} : snorm f p 0 = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, snorm', ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end end zero section const lemma snorm'_const (c : F) (hq_pos : 0 < q) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [hq_pos.le])], congr, rw ←ennreal.rpow_mul, suffices hq_cancel : q * (1/q) = 1, by rw [hq_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel (ne_of_lt hq_pos).symm], end lemma snorm'_const' [finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hq_ne_zero : q ≠ 0) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)], { congr, rw ←ennreal.rpow_mul, suffices hp_cancel : q * (1/q) = 1, by rw [hp_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel hq_ne_zero], }, { rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq], split, { left, rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], }, { exact or.inl ennreal.coe_ne_top, }, }, end lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) : snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ℝ≥0∞) := by rw [snorm_ess_sup, ess_sup_const _ hμ] lemma snorm'_const_of_probability_measure (c : F) (hq_pos : 0 < q) [probability_measure μ] : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) := by simp [snorm'_const c hq_pos, measure_univ] lemma snorm_const (c : F) (h0 : p ≠ 0) (hμ : μ ≠ 0) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const c hμ], }, simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma snorm_const' (c : F) (h0 : p ≠ 0) (h_top: p ≠ ∞) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma mem_ℒp_const (c : E) [finite_measure μ] : mem_ℒp (λ a:α, c) p μ := begin refine ⟨measurable_const.ae_measurable, _⟩, by_cases h0 : p = 0, { simp [h0], }, by_cases hμ : μ = 0, { simp [hμ], }, rw snorm_const c h0 hμ, refine ennreal.mul_lt_top ennreal.coe_lt_top _, refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ), simp, end end const lemma snorm'_mono_ae {f : α → F} {g : α → G} (hq : 0 ≤ q) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm' f q μ ≤ snorm' g q μ := begin rw [snorm'], refine ennreal.rpow_le_rpow _ (one_div_nonneg.2 hq), refine lintegral_mono_ae (h.mono $ λ x hx, _), exact ennreal.rpow_le_rpow (ennreal.coe_le_coe.2 hx) hq end lemma snorm'_congr_norm_ae {f g : α → F} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm' f q μ = snorm' g q μ := begin have : (λ x, (nnnorm (f x) ^ q : ℝ≥0∞)) =ᵐ[μ] (λ x, nnnorm (g x) ^ q), from hfg.mono (λ x hx, by { simp only [← coe_nnnorm, nnreal.coe_eq] at hx, simp [hx] }), simp only [snorm', lintegral_congr_ae this] end lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f q μ = snorm' g q μ := snorm'_congr_norm_ae (hfg.fun_comp _) lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm_ess_sup f μ = snorm_ess_sup g μ := ess_sup_congr_ae (hfg.fun_comp (coe ∘ nnnorm)) lemma snorm_mono_ae {f : α → F} {g : α → G} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm f p μ ≤ snorm g p μ := begin simp only [snorm], split_ifs, { exact le_rfl }, { refine ess_sup_mono_ae (h.mono $ λ x hx, _), exact_mod_cast hx }, { exact snorm'_mono_ae ennreal.to_real_nonneg h } end lemma snorm_le_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : snorm f p μ ≤ ((μ set.univ) ^ p.to_real⁻¹) * (ennreal.of_real C) := begin by_cases hμ : μ = 0, { simp [hμ] }, haveI : μ.ae.ne_bot := ae_ne_bot.mpr hμ, by_cases hp : p = 0, { simp [hp] }, have hC : 0 ≤ C, from le_trans (norm_nonneg _) hfC.exists.some_spec, have hC' : ∥C∥ = C := by rw [real.norm_eq_abs, abs_eq_self.mpr hC], have : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥(λ _, C) x∥, from hfC.mono (λ x hx, hx.trans (le_of_eq hC'.symm)), convert snorm_mono_ae this, rw [snorm_const _ hp hμ, mul_comm, ← of_real_norm_eq_coe_nnnorm, hC', one_div] end lemma snorm_congr_norm_ae {f : α → F} {g : α → G} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm f p μ = snorm g p μ := le_antisymm (snorm_mono_ae $ eventually_eq.le hfg) (snorm_mono_ae $ (eventually_eq.symm hfg).le) @[simp] lemma snorm'_norm {f : α → F} : snorm' (λ a, ∥f a∥) q μ = snorm' f q μ := by simp [snorm'] @[simp] lemma snorm_norm (f : α → F) : snorm (λ x, ∥f x∥) p μ = snorm f p μ := snorm_congr_norm_ae $ eventually_of_forall $ λ x, norm_norm _ lemma snorm'_norm_rpow (f : α → F) (p q : ℝ) (hq_pos : 0 < q) : snorm' (λ x, ∥f x∥ ^ q) p μ = (snorm' f (p * q) μ) ^ q := begin simp_rw snorm', rw [← ennreal.rpow_mul, ←one_div_mul_one_div], simp_rw one_div, rw [mul_assoc, inv_mul_cancel hq_pos.ne.symm, mul_one], congr, ext1 x, simp_rw ← of_real_norm_eq_coe_nnnorm, rw [real.norm_eq_abs, abs_eq_self.mpr (real.rpow_nonneg_of_nonneg (norm_nonneg _) _), mul_comm, ← ennreal.of_real_rpow_of_nonneg (norm_nonneg _) hq_pos.le, ennreal.rpow_mul], end lemma snorm_norm_rpow (f : α → F) (hq_pos : 0 < q) : snorm (λ x, ∥f x∥ ^ q) p μ = (snorm f (p * ennreal.of_real q) μ) ^ q := begin by_cases h0 : p = 0, { simp [h0, ennreal.zero_rpow_of_pos hq_pos], }, by_cases hp_top : p = ∞, { simp only [hp_top, snorm_exponent_top, ennreal.top_mul, hq_pos.not_le, ennreal.of_real_eq_zero, if_false, snorm_exponent_top, snorm_ess_sup], have h_rpow : ess_sup (λ (x : α), (nnnorm (∥f x∥ ^ q) : ℝ≥0∞)) μ = ess_sup (λ (x : α), (↑(nnnorm (f x))) ^ q) μ, { congr, ext1 x, nth_rewrite 1 ← nnnorm_norm, rw [ennreal.coe_rpow_of_nonneg _ hq_pos.le, ennreal.coe_eq_coe], ext, push_cast, rw real.norm_rpow_of_nonneg (norm_nonneg _), }, rw h_rpow, have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hq_pos, have h_rpow_surj := (ennreal.rpow_left_bijective hq_pos.ne.symm).2, let iso := h_rpow_mono.order_iso_of_surjective _ h_rpow_surj, exact (iso.ess_sup_apply (λ x, ((nnnorm (f x)) : ℝ≥0∞)) μ).symm, }, rw [snorm_eq_snorm' h0 hp_top, snorm_eq_snorm' _ _], swap, { refine mul_ne_zero h0 _, rwa [ne.def, ennreal.of_real_eq_zero, not_le], }, swap, { exact ennreal.mul_ne_top hp_top ennreal.of_real_ne_top, }, rw [ennreal.to_real_mul, ennreal.to_real_of_real hq_pos.le], exact snorm'_norm_rpow f p.to_real q hq_pos, end lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f p μ = snorm g p μ := snorm_congr_norm_ae $ hfg.mono (λ x hx, hx ▸ rfl) lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f p μ ↔ mem_ℒp g p μ := by simp only [mem_ℒp, snorm_congr_ae hfg, ae_measurable_congr hfg] lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f p μ) : mem_ℒp g p μ := (mem_ℒp_congr_ae hfg).1 hf_Lp lemma mem_ℒp.of_le [measurable_space F] {f : α → E} {g : α → F} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : mem_ℒp f p μ := ⟨hf, (snorm_mono_ae hfg).trans_lt hg.snorm_lt_top⟩ lemma mem_ℒp.of_bound [finite_measure μ] {f : α → E} (hf : ae_measurable f μ) (C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : mem_ℒp f p μ := (mem_ℒp_const C).of_le hf (hfC.mono (λ x hx, le_trans hx (le_abs_self _))) section opens_measurable_space variable [opens_measurable_space E] lemma mem_ℒp.norm {f : α → E} (h : mem_ℒp f p μ) : mem_ℒp (λ x, ∥f x∥) p μ := h.of_le h.ae_measurable.norm (eventually_of_forall (λ x, by simp)) lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hq0_lt : 0 < q) (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero hq0_lt] lemma snorm'_eq_zero_of_ae_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero' hq0_ne hμ] lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hq0 : 0 ≤ q) (hf : ae_measurable f μ) (h : snorm' f q μ = 0) : f =ᵐ[μ] 0 := begin rw [snorm', ennreal.rpow_eq_zero_iff] at h, cases h, { rw lintegral_eq_zero_iff' (hf.ennnorm.pow_const q) at h, refine h.left.mono (λ x hx, _), rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx, cases hx, { cases hx with hx _, rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, }, { exact absurd hx.left ennreal.coe_ne_top, }, }, { exfalso, rw [one_div, inv_lt_zero] at h, exact hq0.not_lt h.right }, end lemma snorm'_eq_zero_iff (hq0_lt : 0 < q) {f : α → E} (hf : ae_measurable f μ) : snorm' f q μ = 0 ↔ f =ᵐ[μ] 0 := ⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hq0_lt) hf, snorm'_eq_zero_of_ae_zero hq0_lt⟩ lemma coe_nnnorm_ae_le_snorm_ess_sup (f : α → F) (μ : measure α) : ∀ᵐ x ∂μ, (nnnorm (f x) : ℝ≥0∞) ≤ snorm_ess_sup f μ := ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) @[simp] lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 := by simp [eventually_eq, snorm_ess_sup] lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : p ≠ 0) : snorm f p μ = 0 ↔ f =ᵐ[μ] 0 := begin by_cases h_top : p = ∞, { rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], }, rw snorm_eq_snorm' h0 h_top, exact snorm'_eq_zero_iff (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf, end end opens_measurable_space @[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) q μ = snorm' f q μ := by simp [snorm'] @[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup], }, simp [snorm_eq_snorm' h0 h_top], end section borel_space variable [borel_space E] lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ := ⟨ae_measurable.neg hf.1, by simp [hf.right]⟩ lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) := begin have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq, by_cases hpq_eq : p = q, { rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one], exact le_refl _, }, have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq, let g := λ a : α, (1 : ℝ≥0∞), have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ, from lintegral_congr (λ a, by simp), repeat {rw snorm'}, rw h_rw, let r := p * q / (q - p), have hpqr : 1/p = 1/q + 1/r, { field_simp [(ne_of_lt hp0_lt).symm, (ne_of_lt hq0_lt).symm], ring, }, calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p) ≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) : ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.ennnorm ae_measurable_const ... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) : by simp [hpqr], end lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hq_pos : 0 < q) {f : α → F} : snorm' f q μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/q) := begin have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ q ∂μ, { refine lintegral_mono_ae _, have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ, refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hq_pos)), }, rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)], nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hq_pos).symm, rw [ennreal.rpow_mul, one_div, ←@ennreal.mul_rpow_of_nonneg _ _ q⁻¹ (by simp [hq_pos.le])], refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le]), rwa lintegral_const at h_le, end lemma snorm'_le_snorm'_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ := begin have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf, rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ, end lemma snorm'_le_snorm_ess_sup (hq_pos : 0 < q) {f : α → F} [probability_measure μ] : snorm' f q μ ≤ snorm_ess_sup f μ := le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hq_pos) (le_of_eq (by simp [measure_univ])) lemma snorm_le_snorm_of_exponent_le {p q : ℝ≥0∞} (hpq : p ≤ q) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm f p μ ≤ snorm f q μ := begin by_cases hp0 : p = 0, { simp [hp0], }, rw ←ne.def at hp0, by_cases hq_top : q = ∞, { by_cases hp_top : p = ∞, { rw [hq_top, hp_top], exact le_refl _, }, { have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, rw [snorm_eq_snorm' hp0 hp_top, hq_top, snorm_exponent_top], refine le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) (le_of_eq _), simp [measure_univ], }, }, { have hp_top : p ≠ ∞, { by_contra hp_eq_top, push_neg at hp_eq_top, refine hq_top _, rwa [hp_eq_top, top_le_iff] at hpq, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw [snorm_eq_snorm' hp0 hp_top, snorm_eq_snorm' hq0 hq_top], exact snorm'_le_snorm'_of_exponent_le hp_pos hpq_real _ hf, }, end lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [finite_measure μ] {f : α → E} (hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ∞) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) : snorm' f p μ < ∞ := begin cases le_or_lt p 0 with hp_nonpos hp_pos, { rw le_antisymm hp_nonpos hp_nonneg, simp, }, have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq, calc snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) : snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf ... < ∞ : begin rw ennreal.mul_lt_top_iff, refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩, rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos], end end lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ≥0∞} [finite_measure μ] {f : α → E} (hfq : mem_ℒp f q μ) (hpq : p ≤ q) : mem_ℒp f p μ := begin cases hfq with hfq_m hfq_lt_top, by_cases hp0 : p = 0, { rwa [hp0, mem_ℒp_zero_iff_ae_measurable], }, rw ←ne.def at hp0, refine ⟨hfq_m, _⟩, by_cases hp_top : p = ∞, { have hq_top : q = ∞, by rwa [hp_top, top_le_iff] at hpq, rw [hp_top], rwa hq_top at hfq_lt_top, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, by_cases hq_top : q = ∞, { rw snorm_eq_snorm' hp0 hp_top, rw [hq_top, snorm_exponent_top] at hfq_lt_top, refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _, refine ennreal.mul_lt_top hfq_lt_top _, exact ennreal.rpow_lt_top_of_nonneg (by simp [le_of_lt hp_pos]) (measure_ne_top μ set.univ), }, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw snorm_eq_snorm' hp0 hp_top, rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top, exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real, end lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) : snorm' (f + g) q μ ≤ snorm' f q μ + snorm' g q μ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [le_trans zero_le_one hq1]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hq1)), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ snorm' f q μ + snorm' g q μ : ennreal.lintegral_Lp_add_le hf.ennnorm hg.ennnorm hq1 lemma snorm_ess_sup_add_le {f g : α → F} : snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ := begin refine le_trans (ess_sup_mono_ae (eventually_of_forall (λ x, _))) (ennreal.ess_sup_add_le _ _), simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _, end lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hp_top : p = ∞, { simp [hp_top, snorm_ess_sup_add_le], }, have hp1_real : 1 ≤ p.to_real, by rwa [← ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hp_top], repeat { rw snorm_eq_snorm' hp0 hp_top, }, exact snorm'_add_le hf hg hp1_real, end lemma snorm'_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hq1 : 1 ≤ q) : snorm' (∑ i in s, f i) q μ ≤ ∑ i in s, snorm' (f i) q μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm' f q μ) (λ f, ae_measurable f μ) (snorm'_zero (zero_lt_one.trans_le hq1)) (λ f g hf hg, snorm'_add_le hf hg hq1) (λ x y, ae_measurable.add) _ hfs lemma snorm_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hp1 : 1 ≤ p) : snorm (∑ i in s, f i) p μ ≤ ∑ i in s, snorm (f i) p μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm f p μ) (λ f, ae_measurable f μ) snorm_zero (λ f g hf hg, snorm_add_le hf hg hp1) (λ x y, ae_measurable.add) _ hfs lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) (hq1 : 1 ≤ p) : snorm (f + g) p μ < ∞ := lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩) lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_snorm : snorm' f q μ < ∞) (hg_snorm : snorm' g q μ < ∞) (hq_pos : 0 < q) (hq1 : q ≤ 1) : snorm' (f + g) q μ < ∞ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [hq_pos.le]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hq_pos.le), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q + (nnnorm (g a) : ℝ≥0∞) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) (lintegral_mono (λ a, _)) (by simp [hq_pos.le]), exact ennreal.rpow_add_le_add_rpow _ _ hq_pos hq1, end ... < ∞ : begin refine @ennreal.rpow_lt_top_of_nonneg _ (1/q) (by simp [hq_pos.le]) _, rw [lintegral_add' (hf.ennnorm.pow_const q) (hg.ennnorm.pow_const q), ennreal.add_ne_top, ←lt_top_iff_ne_top, ←lt_top_iff_ne_top], exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hf_snorm, lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hg_snorm⟩, end lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : snorm (f + g) p μ < ∞ := begin by_cases h0 : p = 0, { simp [h0], }, rw ←ne.def at h0, cases le_total 1 p with hp1 hp1, { exact snorm_add_lt_top_of_one_le hf hg hp1, }, have hp_top : p ≠ ∞, from (lt_of_le_of_lt hp1 ennreal.coe_lt_top).ne, have hp_pos : 0 < p.to_real, { rw [← ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 p ennreal.coe_ne_top hp_top], exact ((zero_le p).lt_of_ne h0.symm), }, have hp1_real : p.to_real ≤ 1, { rwa [← ennreal.one_to_real, @ennreal.to_real_le_to_real p 1 hp_top ennreal.coe_ne_top], }, rw snorm_eq_snorm' h0 hp_top, rw [mem_ℒp, snorm_eq_snorm' h0 hp_top] at hf hg, exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hp_pos hp1_real, end section second_countable_topology variable [second_countable_topology E] lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f + g) p μ := ⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩ lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f - g) p μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } end second_countable_topology end borel_space section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hq0_lt : 0 < q) : snorm' (c • f) q μ = (nnnorm c : ℝ≥0∞) * snorm' f q μ := begin rw snorm', simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.mul_rpow_of_nonneg _ _ (le_of_lt hq0_lt)], suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ q * ↑(nnnorm (f a)) ^ q ∂μ = (nnnorm c : ℝ≥0∞)^q * ∫⁻ a, (nnnorm (f a)) ^ q ∂μ, { apply_fun (λ x, x ^ (1/q)) at h_integral, rw [h_integral, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [le_of_lt hq0_lt])], congr, simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel (ne_of_lt hq0_lt).symm, ennreal.rpow_one], }, rw lintegral_const_mul', rw ennreal.coe_rpow_of_nonneg _ hq0_lt.le, exact ennreal.coe_ne_top, end lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) : snorm_ess_sup (c • f) μ = (nnnorm c : ℝ≥0∞) * snorm_ess_sup f μ := by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul] lemma snorm_const_smul {f : α → F} (c : 𝕜) : snorm (c • f) p μ = (nnnorm c : ℝ≥0∞) * snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const_smul], }, repeat { rw snorm_eq_snorm' h0 h_top, }, rw ←ne.def at h0, exact snorm'_const_smul c (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩), end lemma mem_ℒp.const_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] [borel_space E] {f : α → E} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (c • f) p μ := ⟨ae_measurable.const_smul hf.1 c, lt_of_le_of_lt (le_of_eq (snorm_const_smul c)) (ennreal.mul_lt_top ennreal.coe_lt_top hf.2)⟩ lemma mem_ℒp.const_mul [measurable_space 𝕜] [borel_space 𝕜] {f : α → 𝕜} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (λ x, c * f x) p μ := hf.const_smul c lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {p q r : ℝ} {f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ) (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) : snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ := begin simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul], exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.ennnorm hf.ennnorm, end end normed_space section monotonicity lemma snorm_le_mul_snorm_aux_of_nonneg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : 0 ≤ c) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin lift c to ℝ≥0 using hc, rw [ennreal.of_real_coe_nnreal, ← c.nnnorm_eq, ← snorm_norm g, ← snorm_const_smul (c : ℝ)], swap, apply_instance, refine snorm_mono_ae _, simpa end lemma snorm_le_mul_snorm_aux_of_neg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : c < 0) (p : ℝ≥0∞) : snorm f p μ = 0 ∧ snorm g p μ = 0 := begin suffices : f =ᵐ[μ] 0 ∧ g =ᵐ[μ] 0, by simp [snorm_congr_ae this.1, snorm_congr_ae this.2], refine ⟨h.mono $ λ x hx, _, h.mono $ λ x hx, _⟩, { refine norm_le_zero_iff.1 (hx.trans _), exact mul_nonpos_of_nonpos_of_nonneg hc.le (norm_nonneg _) }, { refine norm_le_zero_iff.1 (nonpos_of_mul_nonneg_right _ hc), exact (norm_nonneg _).trans hx } end lemma snorm_le_mul_snorm_of_ae_le_mul {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin cases le_or_lt 0 c with hc hc, { exact snorm_le_mul_snorm_aux_of_nonneg h hc p }, { simp [snorm_le_mul_snorm_aux_of_neg h hc p] } end lemma mem_ℒp.of_le_mul [measurable_space F] {f : α → E} {g : α → F} {c : ℝ} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : mem_ℒp f p μ := begin simp only [mem_ℒp, hf, true_and], apply lt_of_le_of_lt (snorm_le_mul_snorm_of_ae_le_mul hfg p), simp [lt_top_iff_ne_top, hg.snorm_ne_top], end end monotonicity end ℒp /-! ### Lp space The space of equivalence classes of measurable functions for which `snorm f p μ < ∞`. -/ @[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hf : ae_measurable f μ) : snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ := snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _) lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hfp : mem_ℒp f p μ) : snorm (ae_eq_fun.mk f hfp.1) p μ < ∞ := by simp [hfp.2] /-- Lp space -/ def Lp {α} (E : Type*) [measurable_space α] [measurable_space E] [normed_group E] [borel_space E] [second_countable_topology E] (p : ℝ≥0∞) (μ : measure α) : add_subgroup (α →ₘ[μ] E) := { carrier := {f | snorm f p μ < ∞}, zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero], add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _), snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩], neg_mem' := λ f hf, by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] } localized "notation α ` →₁[`:25 μ `] ` E := measure_theory.Lp E 1 μ" in measure_theory localized "notation α ` →₂[`:25 μ `] ` E := measure_theory.Lp E 2 μ" in measure_theory namespace mem_ℒp variables [borel_space E] [second_countable_topology E] /-- make an element of Lp from a function verifying `mem_ℒp` -/ def to_Lp (f : α → E) (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ := ⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩ lemma coe_fn_to_Lp {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk _ _ @[simp] lemma to_Lp_eq_to_Lp_iff {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : hf.to_Lp f = hg.to_Lp g ↔ f =ᵐ[μ] g := by simp [to_Lp] @[simp] lemma to_Lp_zero (h : mem_ℒp (0 : α → E) p μ ) : h.to_Lp 0 = 0 := rfl lemma to_Lp_add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.add hg).to_Lp (f + g) = hf.to_Lp f + hg.to_Lp g := rfl lemma to_Lp_neg {f : α → E} (hf : mem_ℒp f p μ) : hf.neg.to_Lp (-f) = - hf.to_Lp f := rfl lemma to_Lp_sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.sub hg).to_Lp (f - g) = hf.to_Lp f - hg.to_Lp g := rfl end mem_ℒp namespace Lp variables [borel_space E] [second_countable_topology E] instance : has_coe_to_fun (Lp E p μ) := ⟨λ _, α → E, λ f, ((f : α →ₘ[μ] E) : α → E)⟩ @[ext] lemma ext {f g : Lp E p μ} (h : f =ᵐ[μ] g) : f = g := begin cases f, cases g, simp only [subtype.mk_eq_mk], exact ae_eq_fun.ext h end lemma ext_iff {f g : Lp E p μ} : f = g ↔ f =ᵐ[μ] g := ⟨λ h, by rw h, λ h, ext h⟩ lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ∞ := iff.refl _ lemma mem_Lp_iff_mem_ℒp {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ mem_ℒp f p μ := by simp [mem_Lp_iff_snorm_lt_top, mem_ℒp, f.measurable.ae_measurable] lemma antimono [finite_measure μ] {p q : ℝ≥0∞} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ := λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2 @[simp] lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α → E) = f := rfl @[simp] lemma coe_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α →ₘ[μ] E) = f := rfl @[simp] lemma to_Lp_coe_fn (f : Lp E p μ) (hf : mem_ℒp f p μ) : hf.to_Lp f = f := by { cases f, simp [mem_ℒp.to_Lp] } lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ∞ := f.prop lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ∞ := (snorm_lt_top f).ne protected lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable protected lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable protected lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨Lp.ae_measurable f, f.prop⟩ variables (E p μ) lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero variables {E p μ} lemma coe_fn_neg (f : Lp E p μ) : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _ lemma coe_fn_add (f g : Lp E p μ) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _ lemma coe_fn_sub (f g : Lp E p μ) : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _ lemma mem_Lp_const (α) [measurable_space α] (μ : measure α) (c : E) [finite_measure μ] : @ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ := (mem_ℒp_const c).snorm_mk_lt_top instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) } instance : has_dist (Lp E p μ) := { dist := λ f g, ∥f - g∥} instance : has_edist (Lp E p μ) := { edist := λ f g, ennreal.of_real (dist f g) } lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl @[simp] lemma norm_to_Lp (f : α → E) (hf : mem_ℒp f p μ) : ∥hf.to_Lp f∥ = ennreal.to_real (snorm f p μ) := by rw [norm_def, snorm_congr_ae (mem_ℒp.coe_fn_to_Lp hf)] lemma dist_def (f g : Lp E p μ) : dist f g = (snorm (f - g) p μ).to_real := begin simp_rw [dist, norm_def], congr' 1, apply snorm_congr_ae (coe_fn_sub _ _), end lemma edist_def (f g : Lp E p μ) : edist f g = snorm (f - g) p μ := begin simp_rw [edist, dist, norm_def, ennreal.of_real_to_real (snorm_ne_top _)], exact snorm_congr_ae (coe_fn_sub _ _) end @[simp] lemma edist_to_Lp_to_Lp (f g : α → E) (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : edist (hf.to_Lp f) (hg.to_Lp g) = snorm (f - g) p μ := by { rw edist_def, exact snorm_congr_ae (hf.coe_fn_to_Lp.sub hg.coe_fn_to_Lp) } @[simp] lemma edist_to_Lp_zero (f : α → E) (hf : mem_ℒp f p μ) : edist (hf.to_Lp f) 0 = snorm f p μ := by { convert edist_to_Lp_to_Lp f 0 hf zero_mem_ℒp, simp } @[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 := begin change (snorm ⇑(0 : α →ₘ[μ] E) p μ).to_real = 0, simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero] end lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 := begin refine ⟨λ hf, _, λ hf, by simp [hf]⟩, rw [norm_def, ennreal.to_real_eq_zero_iff] at hf, cases hf, { rw snorm_eq_zero_iff (Lp.ae_measurable f) hp.ne.symm at hf, exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), }, { exact absurd hf (snorm_ne_top f), }, end lemma eq_zero_iff_ae_eq_zero {f : Lp E p μ} : f = 0 ↔ f =ᵐ[μ] 0 := begin split, { assume h, rw h, exact ae_eq_fun.coe_fn_const _ _ }, { assume h, ext1, filter_upwards [h, ae_eq_fun.coe_fn_const α (0 : E)], assume a ha h'a, rw ha, exact h'a.symm } end @[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ := by rw [norm_def, norm_def, snorm_congr_ae (coe_fn_neg _), snorm_neg] lemma norm_le_mul_norm_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : ∥f∥ ≤ c * ∥g∥ := begin by_cases pzero : p = 0, { simp [pzero, norm_def] }, cases le_or_lt 0 c with hc hc, { have := snorm_le_mul_snorm_aux_of_nonneg h hc p, rw [← ennreal.to_real_le_to_real, ennreal.to_real_mul, ennreal.to_real_of_real hc] at this, { exact this }, { exact (Lp.mem_ℒp _).snorm_ne_top }, { simp [(Lp.mem_ℒp _).snorm_ne_top] } }, { have := snorm_le_mul_snorm_aux_of_neg h hc p, simp only [snorm_eq_zero_iff (Lp.ae_measurable _) pzero, ← eq_zero_iff_ae_eq_zero] at this, simp [this] } end lemma norm_le_norm_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : ∥f∥ ≤ ∥g∥ := begin rw [norm_def, norm_def, ennreal.to_real_le_to_real (snorm_ne_top _) (snorm_ne_top _)], exact snorm_mono_ae h end lemma mem_Lp_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le_mul (Lp.mem_ℒp g) f.ae_measurable h lemma mem_Lp_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le (Lp.mem_ℒp g) f.ae_measurable h lemma mem_Lp_of_ae_bound [finite_measure μ] {f : α →ₘ[μ] E} (C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_bound f.ae_measurable _ hfC lemma norm_le_of_ae_bound [finite_measure μ] {f : Lp E p μ} {C : ℝ} (hC : 0 ≤ C) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥f∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * C := begin by_cases hμ : μ = 0, { by_cases hp : p.to_real⁻¹ = 0, { simpa [hp, hμ, norm_def] using hC }, { simp [hμ, norm_def, real.zero_rpow hp] } }, let A : ℝ≥0 := (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ⟨C, hC⟩, suffices : snorm f p μ ≤ A, { exact ennreal.to_real_le_coe_of_le_coe this }, convert snorm_le_of_ae_bound hfC, rw [← coe_measure_univ_nnreal μ, ennreal.coe_rpow_of_ne_zero (measure_univ_nnreal_pos hμ).ne', ennreal.coe_mul], congr, rw max_eq_left hC end instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) := normed_group.of_core _ { norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp.1), triangle := begin assume f g, simp only [norm_def], rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g), suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ, { rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)), exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, }, rw [snorm_congr_ae (coe_fn_add _ _)], exact snorm_add_le (Lp.ae_measurable f) (Lp.ae_measurable g) hp.1, end, norm_neg := by simp } instance normed_group_L1 : normed_group (Lp E 1 μ) := by apply_instance instance normed_group_L2 : normed_group (Lp E 2 μ) := by apply_instance instance normed_group_Ltop : normed_group (Lp E ∞ μ) := by apply_instance section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ := begin rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul, ennreal.mul_lt_top_iff], exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩, end variables (E p μ 𝕜) /-- The `𝕜`-submodule of elements of `α →ₘ[μ] E` whose `Lp` norm is finite. This is `Lp E p μ`, with extra structure. -/ def Lp_submodule : submodule 𝕜 (α →ₘ[μ] E) := { smul_mem' := λ c f hf, by simpa using mem_Lp_const_smul c ⟨f, hf⟩, .. Lp E p μ } variables {E p μ 𝕜} lemma coe_Lp_submodule : (Lp_submodule E p μ 𝕜).to_add_subgroup = Lp E p μ := rfl instance : module 𝕜 (Lp E p μ) := { .. (Lp_submodule E p μ 𝕜).module } lemma coe_fn_smul (c : 𝕜) (f : Lp E p μ) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _ lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ := by rw [norm_def, snorm_congr_ae (coe_fn_smul _ _), snorm_const_smul c, ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def] instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) := { norm_smul_le := λ _ _, by simp [norm_const_smul] } instance normed_space_L1 : normed_space 𝕜 (Lp E 1 μ) := by apply_instance instance normed_space_L2 : normed_space 𝕜 (Lp E 2 μ) := by apply_instance instance normed_space_Ltop : normed_space 𝕜 (Lp E ∞ μ) := by apply_instance end normed_space end Lp namespace mem_ℒp variables [borel_space E] [second_countable_topology E] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma to_Lp_const_smul {f : α → E} (c : 𝕜) (hf : mem_ℒp f p μ) : (hf.const_smul c).to_Lp (c • f) = c • hf.to_Lp f := rfl end mem_ℒp end measure_theory open measure_theory /-! ### Composition on `L^p` We show that Lipschitz functions vanishing at zero act by composition on `L^p`, and specialize this to the composition with continuous linear maps, and to the definition of the positive part of an `L^p` function. -/ section composition variables [second_countable_topology E] [borel_space E] [second_countable_topology F] [measurable_space F] [borel_space F] {g : E → F} {c : ℝ≥0} namespace lipschitz_with lemma mem_ℒp_comp_iff_of_antilipschitz {α E F} {K K'} [measurable_space α] {μ : measure α} [measurable_space E] [measurable_space F] [normed_group E] [normed_group F] [borel_space E] [borel_space F] [complete_space E] {f : α → E} {g : E → F} (hg : lipschitz_with K g) (hg' : antilipschitz_with K' g) (g0 : g 0 = 0) : mem_ℒp (g ∘ f) p μ ↔ mem_ℒp f p μ := begin have := ae_measurable_comp_iff_of_closed_embedding g (hg'.closed_embedding hg.uniform_continuous), split, { assume H, have A : ∀ᵐ x ∂μ, ∥f x∥ ≤ K' * ∥g (f x)∥, { apply filter.eventually_of_forall (λ x, _), rw [← dist_zero_right, ← dist_zero_right, ← g0], apply hg'.le_mul_dist }, exact H.of_le_mul (this.1 H.ae_measurable) A }, { assume H, have A : ∀ᵐ x ∂μ, ∥g (f x)∥ ≤ K * ∥f x∥, { apply filter.eventually_of_forall (λ x, _), rw [← dist_zero_right, ← dist_zero_right, ← g0], apply hg.dist_le_mul }, exact H.of_le_mul (this.2 H.ae_measurable) A } end /-- When `g` is a Lipschitz function sending `0` to `0` and `f` is in `Lp`, then `g ∘ f` is well defined as an element of `Lp`. -/ def comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : Lp F p μ := ⟨ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E), begin suffices : ∀ᵐ x ∂μ, ∥ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E) x∥ ≤ c * ∥f x∥, { exact Lp.mem_Lp_of_ae_le_mul this }, filter_upwards [ae_eq_fun.coe_fn_comp g hg.continuous.measurable (f : α →ₘ[μ] E)], assume a ha, simp only [ha], rw [← dist_zero_right, ← dist_zero_right, ← g0], exact hg.dist_le_mul (f a) 0, end⟩ lemma coe_fn_comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : hg.comp_Lp g0 f =ᵐ[μ] g ∘ f := ae_eq_fun.coe_fn_comp _ _ _ @[simp] lemma comp_Lp_zero (hg : lipschitz_with c g) (g0 : g 0 = 0) : hg.comp_Lp g0 (0 : Lp E p μ) = 0 := begin rw Lp.eq_zero_iff_ae_eq_zero, apply (coe_fn_comp_Lp _ _ _).trans, filter_upwards [Lp.coe_fn_zero E p μ], assume a ha, simp [ha, g0] end lemma norm_comp_Lp_sub_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f f' : Lp E p μ) : ∥hg.comp_Lp g0 f - hg.comp_Lp g0 f'∥ ≤ c * ∥f - f'∥ := begin apply Lp.norm_le_mul_norm_of_ae_le_mul, filter_upwards [hg.coe_fn_comp_Lp g0 f, hg.coe_fn_comp_Lp g0 f', Lp.coe_fn_sub (hg.comp_Lp g0 f) (hg.comp_Lp g0 f'), Lp.coe_fn_sub f f'], assume a ha1 ha2 ha3 ha4, simp [ha1, ha2, ha3, ha4, ← dist_eq_norm], exact hg.dist_le_mul (f a) (f' a) end lemma norm_comp_Lp_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : ∥hg.comp_Lp g0 f∥ ≤ c * ∥f∥ := by simpa using hg.norm_comp_Lp_sub_le g0 f 0 lemma lipschitz_with_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : lipschitz_with c (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := lipschitz_with.of_dist_le_mul $ λ f g, by simp [dist_eq_norm, norm_comp_Lp_sub_le] lemma continuous_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : continuous (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := (lipschitz_with_comp_Lp hg g0).continuous end lipschitz_with namespace continuous_linear_map variables [normed_space ℝ E] [normed_space ℝ F] /-- Composing `f : Lp ` with `L : E →L[ℝ] F`. -/ def comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : Lp F p μ := L.lipschitz.comp_Lp (map_zero L) f lemma coe_fn_comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : ∀ᵐ a ∂μ, (L.comp_Lp f) a = L (f a) := lipschitz_with.coe_fn_comp_Lp _ _ _ variables (μ p) /-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `Lp E p μ`. -/ def comp_Lpₗ (L : E →L[ℝ] F) : (Lp E p μ) →ₗ[ℝ] (Lp F p μ) := { to_fun := λ f, L.comp_Lp f, map_add' := begin intros f g, ext1, filter_upwards [Lp.coe_fn_add f g, coe_fn_comp_Lp L (f + g), coe_fn_comp_Lp L f, coe_fn_comp_Lp L g, Lp.coe_fn_add (L.comp_Lp f) (L.comp_Lp g)], assume a ha1 ha2 ha3 ha4 ha5, simp only [ha1, ha2, ha3, ha4, ha5, map_add, pi.add_apply], end, map_smul' := begin intros c f, ext1, filter_upwards [Lp.coe_fn_smul c f, coe_fn_comp_Lp L (c • f), Lp.coe_fn_smul c (L.comp_Lp f), coe_fn_comp_Lp L f], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, map_smul, pi.smul_apply], end } variables {μ p} lemma norm_comp_Lp_le (L : E →L[ℝ] F) (f : Lp E p μ) : ∥L.comp_Lp f∥ ≤ ∥L∥ * ∥f∥ := lipschitz_with.norm_comp_Lp_le _ _ _ variables (μ p) /-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on `Lp E p μ`. -/ def comp_LpL [fact (1 ≤ p)] (L : E →L[ℝ] F) : (Lp E p μ) →L[ℝ] (Lp F p μ) := linear_map.mk_continuous (L.comp_Lpₗ p μ) ∥L∥ L.norm_comp_Lp_le lemma norm_compLpL_le [fact (1 ≤ p)] (L : E →L[ℝ] F) : ∥L.comp_LpL p μ∥ ≤ ∥L∥ := linear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end continuous_linear_map namespace measure_theory namespace Lp section pos_part lemma lipschitz_with_pos_part : lipschitz_with 1 (λ (x : ℝ), max x 0) := lipschitz_with.of_dist_le_mul $ λ x y, by simp [dist, abs_max_sub_max_le_abs] /-- Positive part of a function in `L^p`. -/ def pos_part (f : Lp ℝ p μ) : Lp ℝ p μ := lipschitz_with_pos_part.comp_Lp (max_eq_right (le_refl _)) f /-- Negative part of a function in `L^p`. -/ def neg_part (f : Lp ℝ p μ) : Lp ℝ p μ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : Lp ℝ p μ) : (pos_part f : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl lemma coe_fn_pos_part (f : Lp ℝ p μ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 := ae_eq_fun.coe_fn_pos_part _ lemma coe_fn_neg_part_eq_max (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 := begin rw neg_part, filter_upwards [coe_fn_pos_part (-f), coe_fn_neg f], assume a h₁ h₂, rw [h₁, h₂, pi.neg_apply] end lemma coe_fn_neg_part (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 := (coe_fn_neg_part_eq_max f).mono $ assume a h, by rw [h, ← max_neg_neg, neg_zero] lemma continuous_pos_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, pos_part f) := lipschitz_with.continuous_comp_Lp _ _ lemma continuous_neg_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, neg_part f) := have eq : (λf : Lp ℝ p μ, neg_part f) = (λf : Lp ℝ p μ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part end Lp end measure_theory end composition /-! ## `L^p` is a complete space We show that `L^p` is a complete space for `1 ≤ p`. -/ section complete_space variables [borel_space E] [second_countable_topology E] namespace measure_theory namespace Lp lemma snorm'_lim_eq_lintegral_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {p : ℝ} (hp_nonneg : 0 ≤ p) {f_lim : α → G} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm' f_lim p μ = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ) ^ (1/p) := begin suffices h_no_pow : (∫⁻ a, (nnnorm (f_lim a)) ^ p ∂μ) = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ), { rw [snorm', h_no_pow], }, refine lintegral_congr_ae (h_lim.mono (λ a ha, _)), rw tendsto.liminf_eq, simp_rw [ennreal.coe_rpow_of_nonneg _ hp_nonneg, ennreal.tendsto_coe], refine ((nnreal.continuous_rpow_const hp_nonneg).tendsto (nnnorm (f_lim a))).comp _, exact (continuous_nnnorm.tendsto (f_lim a)).comp ha, end lemma snorm'_lim_le_liminf_snorm' {E} [measurable_space E] [normed_group E] [borel_space E] {f : ℕ → α → E} {p : ℝ} (hp_pos : 0 < p) (hf : ∀ n, ae_measurable (f n) μ) {f_lim : α → E} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm' f_lim p μ ≤ at_top.liminf (λ n, snorm' (f n) p μ) := begin rw snorm'_lim_eq_lintegral_liminf hp_pos.le h_lim, rw [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div], refine (lintegral_liminf_le' (λ m, ((hf m).ennnorm.pow_const _))).trans_eq _, have h_pow_liminf : at_top.liminf (λ n, snorm' (f n) p μ) ^ p = at_top.liminf (λ n, (snorm' (f n) p μ) ^ p), { have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hp_pos, have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2, refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _, all_goals { is_bounded_default }, }, rw h_pow_liminf, simp_rw [snorm', ← ennreal.rpow_mul, one_div, inv_mul_cancel hp_pos.ne.symm, ennreal.rpow_one], end lemma snorm_exponent_top_lim_eq_ess_sup_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {f_lim : α → G} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim ∞ μ = ess_sup (λ x, at_top.liminf (λ m, (nnnorm (f m x) : ℝ≥0∞))) μ := begin rw [snorm_exponent_top, snorm_ess_sup], refine ess_sup_congr_ae (h_lim.mono (λ x hx, _)), rw tendsto.liminf_eq, rw ennreal.tendsto_coe, exact (continuous_nnnorm.tendsto (f_lim x)).comp hx, end lemma snorm_exponent_top_lim_le_liminf_snorm_exponent_top {ι} [nonempty ι] [encodable ι] [linear_order ι] {f : ι → α → F} {f_lim : α → F} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim ∞ μ ≤ at_top.liminf (λ n, snorm (f n) ∞ μ) := begin rw snorm_exponent_top_lim_eq_ess_sup_liminf h_lim, simp_rw [snorm_exponent_top, snorm_ess_sup], exact ennreal.ess_sup_liminf_le (λ n, (λ x, (nnnorm (f n x) : ℝ≥0∞))), end lemma snorm_lim_le_liminf_snorm {E} [measurable_space E] [normed_group E] [borel_space E] {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E) (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim p μ ≤ at_top.liminf (λ n, snorm (f n) p μ) := begin by_cases hp0 : p = 0, { simp [hp0], }, rw ← ne.def at hp0, by_cases hp_top : p = ∞, { simp_rw [hp_top], exact snorm_exponent_top_lim_le_liminf_snorm_exponent_top h_lim, }, simp_rw snorm_eq_snorm' hp0 hp_top, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, exact snorm'_lim_le_liminf_snorm' hp_pos hf h_lim, end /-! ### `Lp` is complete iff Cauchy sequences of `ℒp` have limits in `ℒp` -/ lemma tendsto_Lp_of_tendsto_ℒp {ι} [linear_order ι] [hp : fact (1 ≤ p)] {f : ι → Lp E p μ} (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ) (h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : at_top.tendsto f (𝓝 (f_lim_ℒp.to_Lp f_lim)) := begin by_cases hι : nonempty ι, swap, { exact tendsto_of_not_nonempty hι, }, haveI : nonempty ι := hι, rw ennreal.tendsto_at_top_zero at h_tendsto, simp_rw metric.tendsto_at_top, intros ε hε, have hε_pos : 0 < ennreal.of_real ε, from ennreal.of_real_pos.mpr hε, have hε2_pos : 0 < ennreal.of_real ε / 2, by { rw ennreal.div_pos_iff, exact ⟨hε_pos.ne.symm, ennreal.two_ne_top⟩, }, cases (h_tendsto (ennreal.of_real ε / 2) hε2_pos) with N h_tendsto, refine ⟨N, λ n hn, _⟩, specialize h_tendsto n hn, have hp_pos : 0 < p, from ennreal.zero_lt_one.trans_le hp.elim, rw [dist_def, ←@ennreal.to_real_of_real ε (le_of_lt hε), ennreal.to_real_lt_to_real _ ennreal.of_real_ne_top], swap, { rw snorm_congr_ae (coe_fn_sub _ _).symm, exact snorm_ne_top _, }, have h_coe : ⇑(f n) - f_lim =ᵐ[μ] ⇑(f n) - ⇑(mem_ℒp.to_Lp f_lim f_lim_ℒp), { have h_coe' : f_lim =ᵐ[μ] ⇑(mem_ℒp.to_Lp f_lim f_lim_ℒp), from (mem_ℒp.coe_fn_to_Lp _).symm, refine h_coe'.mono (λ x hx, _), rw [pi.sub_apply, pi.sub_apply, hx], }, rw snorm_congr_ae h_coe.symm, exact lt_of_le_of_lt h_tendsto (ennreal.half_lt_self hε_pos.ne.symm ennreal.of_real_ne_top), end lemma complete_space_Lp_of_cauchy_complete_ℒp [hp : fact (1 ≤ p)] (H : ∀ (f : ℕ → α → E) (hf : ∀ n, mem_ℒp (f n) p μ) (B : ℕ → ℝ≥0∞) (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N), ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : complete_space (Lp E p μ) := begin let B := λ n : ℕ, ((1:ℝ) / 2) ^ n, have hB_pos : ∀ n, 0 < B n, from λ n, pow_pos (div_pos zero_lt_one zero_lt_two) n, refine metric.complete_of_convergent_controlled_sequences B hB_pos (λ f hf, _), suffices h_limit : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0), { rcases h_limit with ⟨f_lim, hf_lim_meas, h_tendsto⟩, exact ⟨hf_lim_meas.to_Lp f_lim, tendsto_Lp_of_tendsto_ℒp f_lim hf_lim_meas h_tendsto⟩, }, have hB : summable B, from summable_geometric_two, cases hB with M hB, let B1 := λ n, ennreal.of_real (B n), have hB1_has : has_sum B1 (ennreal.of_real M), { have h_tsum_B1 : ∑' i, B1 i = (ennreal.of_real M), { change (∑' (n : ℕ), ennreal.of_real (B n)) = ennreal.of_real M, rw ←hB.tsum_eq, exact (ennreal.of_real_tsum_of_nonneg (λ n, le_of_lt (hB_pos n)) hB.summable).symm, }, have h_sum := (@ennreal.summable _ B1).has_sum, rwa h_tsum_B1 at h_sum, }, have hB1 : ∑' i, B1 i < ∞, by {rw hB1_has.tsum_eq, exact ennreal.of_real_lt_top, }, let f1 : ℕ → α → E := λ n, f n, refine H f1 (λ n, Lp.mem_ℒp (f n)) B1 hB1 (λ N n m hn hm, _), specialize hf N n m hn hm, rw dist_def at hf, simp_rw [f1, B1], rwa ennreal.lt_of_real_iff_to_real_lt, rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm, exact Lp.snorm_ne_top _, end /-! ### Prove that controlled Cauchy sequences of `ℒp` have limits in `ℒp` -/ private lemma snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) (n : ℕ) : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i := begin let f_norm_diff := λ i x, norm (f (i + 1) x - f i x), have hgf_norm_diff : ∀ n, (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) = ∑ i in finset.range (n + 1), f_norm_diff i, from λ n, funext (λ x, by simp [f_norm_diff]), rw hgf_norm_diff, refine (snorm'_sum_le (λ i _, ((hf (i+1)).sub (hf i)).norm) hp1).trans _, simp_rw [←pi.sub_apply, snorm'_norm], refine (finset.sum_le_sum _).trans (sum_le_tsum _ (λ m _, zero_le _) ennreal.summable), exact λ m _, (h_cau m (m + 1) m (nat.le_succ m) (le_refl m)).le, end private lemma lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (n : ℕ) (hn : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i) : ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, rw [←one_div_one_div p, @ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div p], simp_rw snorm' at hn, have h_nnnorm_nonneg : (λ a, (nnnorm (∑ i in finset.range (n + 1), ∥f (i + 1) a - f i a∥) : ℝ≥0∞) ^ p) = λ a, (∑ i in finset.range (n + 1), (nnnorm(f (i + 1) a - f i a) : ℝ≥0∞)) ^ p, { ext1 a, congr, simp_rw ←of_real_norm_eq_coe_nnnorm, rw ←ennreal.of_real_sum_of_nonneg, { rw real.norm_of_nonneg _, exact finset.sum_nonneg (λ x hx, norm_nonneg _), }, { exact λ x hx, norm_nonneg _, }, }, change (∫⁻ a, (λ x, ↑(nnnorm (∑ i in finset.range (n + 1), ∥f (i+1) x - f i x∥))^p) a ∂μ)^(1/p) ≤ ∑' i, B i at hn, rwa h_nnnorm_nonneg at hn, end private lemma lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (h : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p) : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, suffices h_pow : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p, by rwa [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div], have h_tsum_1 : ∀ g : ℕ → ℝ≥0∞, ∑' i, g i = at_top.liminf (λ n, ∑ i in finset.range (n + 1), g i), by { intro g, rw [ennreal.tsum_eq_liminf_sum_nat, ← liminf_nat_add _ 1], }, simp_rw h_tsum_1 _, rw ← h_tsum_1, have h_liminf_pow : ∫⁻ a, at_top.liminf (λ n, ∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p ∂μ = ∫⁻ a, at_top.liminf (λ n, (∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p) ∂μ, { refine lintegral_congr (λ x, _), have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos (zero_lt_one.trans_le hp1), have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2, refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _, all_goals { is_bounded_default }, }, rw h_liminf_pow, refine (lintegral_liminf_le' _).trans _, { exact λ n, (finset.ae_measurable_sum (finset.range (n+1)) (λ i _, ((hf (i+1)).sub (hf i)).ennnorm)).pow_const _, }, { exact liminf_le_of_frequently_le' (frequently_of_forall h), }, end private lemma tsum_nnnorm_sub_ae_lt_top {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i) : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞ := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, have h_integral : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ < ∞, { have h_tsum_lt_top : (∑' i, B i) ^ p < ∞, from ennreal.rpow_lt_top_of_nonneg hp_pos.le (lt_top_iff_ne_top.mp hB), refine lt_of_le_of_lt _ h_tsum_lt_top, rwa [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div] at h, }, have rpow_ae_lt_top : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞)^p < ∞, { refine ae_lt_top' (ae_measurable.pow_const _ _) h_integral, exact ae_measurable.ennreal_tsum (λ n, ((hf (n+1)).sub (hf n)).ennnorm), }, refine rpow_ae_lt_top.mono (λ x hx, _), rwa [←ennreal.lt_rpow_one_div_iff hp_pos, @ennreal.top_rpow_of_pos (1/p) (by simp [hp_pos])] at hx, end lemma ae_tendsto_of_cauchy_snorm' [complete_space E] {f : ℕ → α → E} {p : ℝ} (hf : ∀ n, ae_measurable (f n) μ) (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) := begin have h_summable : ∀ᵐ x ∂μ, summable (λ (i : ℕ), f (i + 1) x - f i x), { have h1 : ∀ n, snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i, from snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' hf hp1 h_cau, have h2 : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p, from λ n, lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum hf hp1 n (h1 n), have h3 : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i, from lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum hf hp1 h2, have h4 : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞, from tsum_nnnorm_sub_ae_lt_top hf hp1 hB h3, exact h4.mono (λ x hx, summable_of_summable_nnnorm (ennreal.tsum_coe_ne_top_iff_summable.mp (lt_top_iff_ne_top.mp hx))), }, have h : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) (𝓝 l), { refine h_summable.mono (λ x hx, _), let hx_sum := (summable.has_sum_iff_tendsto_nat hx).mp hx.has_sum, exact ⟨∑' i, (f (i + 1) x - f i x), hx_sum⟩, }, refine h.mono (λ x hx, _), cases hx with l hx, have h_rw_sum : (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) = λ n, f n x - f 0 x, { ext1 n, change ∑ (i : ℕ) in finset.range n, ((λ m, f m x) (i + 1) - (λ m, f m x) i) = f n x - f 0 x, rw finset.sum_range_sub, }, rw h_rw_sum at hx, have hf_rw : (λ n, f n x) = λ n, f n x - f 0 x + f 0 x, by { ext1 n, abel, }, rw hf_rw, exact ⟨l + f 0 x, tendsto.add_const _ hx⟩, end lemma ae_tendsto_of_cauchy_snorm [complete_space E] {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (hp : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) := begin by_cases hp_top : p = ∞, { simp_rw [hp_top] at *, have h_cau_ae : ∀ᵐ x ∂μ, ∀ N n m, N ≤ n → N ≤ m → (nnnorm ((f n - f m) x) : ℝ≥0∞) < B N, { simp_rw [ae_all_iff, ae_imp_iff], exact λ N n m hnN hmN, ae_lt_of_ess_sup_lt (h_cau N n m hnN hmN), }, simp_rw [snorm_exponent_top, snorm_ess_sup] at h_cau, refine h_cau_ae.mono (λ x hx, cauchy_seq_tendsto_of_complete _), refine cauchy_seq_of_le_tendsto_0 (λ n, (B n).to_real) _ _, { intros n m N hnN hmN, specialize hx N n m hnN hmN, rw [dist_eq_norm, ←ennreal.to_real_of_real (norm_nonneg _), ennreal.to_real_le_to_real ennreal.of_real_ne_top ((ennreal.ne_top_of_tsum_ne_top (lt_top_iff_ne_top.mp hB)) N)], rw ←of_real_norm_eq_coe_nnnorm at hx, exact hx.le, }, { rw ← ennreal.zero_to_real, exact tendsto.comp (ennreal.tendsto_to_real ennreal.zero_ne_top) (ennreal.tendsto_at_top_zero_of_tsum_lt_top hB), }, }, have hp1 : 1 ≤ p.to_real, { rw [← ennreal.of_real_le_iff_le_to_real hp_top, ennreal.of_real_one], exact hp, }, have h_cau' : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) (p.to_real) μ < B N, { intros N n m hn hm, specialize h_cau N n m hn hm, rwa snorm_eq_snorm' (ennreal.zero_lt_one.trans_le hp).ne.symm hp_top at h_cau, }, exact ae_tendsto_of_cauchy_snorm' hf hp1 hB h_cau', end lemma cauchy_tendsto_of_tendsto {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin rw ennreal.tendsto_at_top_zero, intros ε hε, have h_B : ∃ (N : ℕ), B N ≤ ε, { suffices h_tendsto_zero : ∃ (N : ℕ), ∀ n : ℕ, N ≤ n → B n ≤ ε, from ⟨h_tendsto_zero.some, h_tendsto_zero.some_spec _ (le_refl _)⟩, exact (ennreal.tendsto_at_top_zero.mp (ennreal.tendsto_at_top_zero_of_tsum_lt_top hB)) ε hε, }, cases h_B with N h_B, refine ⟨N, λ n hn, _⟩, have h_sub : snorm (f n - f_lim) p μ ≤ at_top.liminf (λ m, snorm (f n - f m) p μ), { refine snorm_lim_le_liminf_snorm (λ m, (hf n).sub (hf m)) (f n - f_lim) _, refine h_lim.mono (λ x hx, _), simp_rw sub_eq_add_neg, exact tendsto.add tendsto_const_nhds (tendsto.neg hx), }, refine h_sub.trans _, refine liminf_le_of_frequently_le' (frequently_at_top.mpr _), refine λ N1, ⟨max N N1, le_max_right _ _, _⟩, exact (h_cau N n (max N N1) hn (le_max_left _ _)).le.trans h_B, end lemma mem_ℒp_of_cauchy_tendsto (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) (f_lim : α → E) (h_lim_meas : ae_measurable f_lim μ) (h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : mem_ℒp f_lim p μ := begin refine ⟨h_lim_meas, _⟩, rw ennreal.tendsto_at_top_zero at h_tendsto, cases (h_tendsto 1 ennreal.zero_lt_one) with N h_tendsto_1, specialize h_tendsto_1 N (le_refl N), have h_add : f_lim = f_lim - f N + f N, by abel, rw h_add, refine lt_of_le_of_lt (snorm_add_le (h_lim_meas.sub (hf N).1) (hf N).1 hp) _, rw ennreal.add_lt_top, split, { refine lt_of_le_of_lt _ ennreal.one_lt_top, have h_neg : f_lim - f N = -(f N - f_lim), by simp, rwa [h_neg, snorm_neg], }, { exact (hf N).2, }, end lemma cauchy_complete_ℒp [complete_space E] (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin obtain ⟨f_lim, h_f_lim_meas, h_lim⟩ : ∃ (f_lim : α → E) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (nhds (f_lim x)), from measurable_limit_of_tendsto_metric_ae (λ n, (hf n).1) (ae_tendsto_of_cauchy_snorm (λ n, (hf n).1) hp hB h_cau), have h_tendsto' : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0), from cauchy_tendsto_of_tendsto (λ m, (hf m).1) f_lim hB h_cau h_lim, have h_ℒp_lim : mem_ℒp f_lim p μ, from mem_ℒp_of_cauchy_tendsto hp hf f_lim h_f_lim_meas.ae_measurable h_tendsto', exact ⟨f_lim, h_ℒp_lim, h_tendsto'⟩, end /-! ### `Lp` is complete for `1 ≤ p` -/ instance [complete_space E] [hp : fact (1 ≤ p)] : complete_space (Lp E p μ) := complete_space_Lp_of_cauchy_complete_ℒp (λ f hf B hB h_cau, cauchy_complete_ℒp hp.elim hf hB h_cau) end Lp end measure_theory end complete_space namespace bounded_continuous_function open_locale bounded_continuous_function variables [borel_space E] [second_countable_topology E] variables [topological_space α] [borel_space α] variables [finite_measure μ] /-- A bounded continuous function is in `Lp`. -/ lemma mem_Lp (f : α →ᵇ E) : f.to_continuous_map.to_ae_eq_fun μ ∈ Lp E p μ := begin refine Lp.mem_Lp_of_ae_bound (∥f∥) _, filter_upwards [f.to_continuous_map.coe_fn_to_ae_eq_fun μ], intros x hx, convert f.norm_coe_le_norm x end /-- The `Lp`-norm of a bounded continuous function is at most a constant (depending on the measure of the whole space) times its sup-norm. -/ lemma Lp_norm_le (f : α →ᵇ E) : ∥(⟨f.to_continuous_map.to_ae_eq_fun μ, mem_Lp f⟩ : Lp E p μ)∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ∥f∥ := begin apply Lp.norm_le_of_ae_bound (norm_nonneg f), { refine (f.to_continuous_map.coe_fn_to_ae_eq_fun μ).mono _, intros x hx, convert f.norm_coe_le_norm x }, { apply_instance } end variables (E p μ) /-- The normed group homomorphism of considering a bounded continuous function on a finite-measure space as an element of `Lp`. -/ def to_Lp_hom [fact (1 ≤ p)] : normed_group_hom (α →ᵇ E) (Lp E p μ) := { bound' := ⟨_, Lp_norm_le⟩, .. add_monoid_hom.cod_restrict ((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E)) (Lp E p μ) mem_Lp } variables (𝕜 : Type*) [measurable_space 𝕜] /-- The bounded linear map of considering a bounded continuous function on a finite-measure space as an element of `Lp`. -/ def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] : (α →ᵇ E) →L[𝕜] (Lp E p μ) := linear_map.mk_continuous (linear_map.cod_restrict (Lp.Lp_submodule E p μ 𝕜) ((continuous_map.to_ae_eq_fun_linear_map μ).comp (forget_boundedness_linear_map α E)) mem_Lp) _ Lp_norm_le variables {E p 𝕜} lemma to_Lp_norm_le [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] : ∥to_Lp E p μ 𝕜∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ := linear_map.mk_continuous_norm_le _ ((measure_univ_nnreal μ) ^ (p.to_real)⁻¹).coe_nonneg _ end bounded_continuous_function namespace continuous_map open_locale bounded_continuous_function variables [borel_space E] [second_countable_topology E] variables [topological_space α] [compact_space α] [borel_space α] variables [finite_measure μ] variables (𝕜 : Type*) [measurable_space 𝕜] (E p μ) [fact (1 ≤ p)] /-- The bounded linear map of considering a continuous function on a compact finite-measure space `α` as an element of `Lp`. By definition, the norm on `C(α, E)` is the sup-norm, transferred from the space `α →ᵇ E` of bounded continuous functions, so this construction is just a matter of transferring the structure from `bounded_continuous_function.to_Lp` along the isometry. -/ def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] : C(α, E) →L[𝕜] (Lp E p μ) := (bounded_continuous_function.to_Lp E p μ 𝕜).comp (linear_isometry_bounded_of_compact α E 𝕜).to_linear_isometry.to_continuous_linear_map variables {E p 𝕜} lemma to_Lp_def [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) : to_Lp E p μ 𝕜 f = bounded_continuous_function.to_Lp E p μ 𝕜 (linear_isometry_bounded_of_compact α E 𝕜 f) := rfl @[simp] lemma to_Lp_comp_forget_boundedness [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : α →ᵇ E) : to_Lp E p μ 𝕜 (bounded_continuous_function.forget_boundedness α E f) = bounded_continuous_function.to_Lp E p μ 𝕜 f := rfl @[simp] lemma coe_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) : (to_Lp E p μ 𝕜 f : α →ₘ[μ] E) = f.to_ae_eq_fun μ := rfl variables [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] lemma to_Lp_norm_eq_to_Lp_norm_coe : ∥to_Lp E p μ 𝕜∥ = ∥bounded_continuous_function.to_Lp E p μ 𝕜∥ := (bounded_continuous_function.to_Lp E p μ 𝕜).op_norm_comp_linear_isometry_equiv _ /-- Bound for the operator norm of `continuous_map.to_Lp`. -/ lemma to_Lp_norm_le : ∥to_Lp E p μ 𝕜∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ := by { rw to_Lp_norm_eq_to_Lp_norm_coe, exact bounded_continuous_function.to_Lp_norm_le μ } end continuous_map
fb15cf5f288e24daff0d614d5397f525b08e49e3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/reduce_auto.lean
61714732ce23296203d0edd3bfe12da1f4280c8c
[]
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
18,766
lean
/- Copyright (c) 2019 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Minchao Wu, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.computability.halting import Mathlib.PostPort universes u_1 u_2 u_3 u v namespace Mathlib /-! # Strong reducibility and degrees. This file defines the notions of computable many-one reduction and one-one reduction between sets, and shows that the corresponding degrees form a semilattice. ## Notations This file uses the local notation `⊕'` for `sum.elim` to denote the disjoint union of two degrees. ## References * [Robert Soare, *Recursively enumerable sets and degrees*][soare1987] ## Tags computability, reducibility, reduction -/ /-- `p` is many-one reducible to `q` if there is a computable function translating questions about `p` to questions about `q`. -/ def many_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) := ∃ (f : α → β), computable f ∧ ∀ (a : α), p a ↔ q (f a) infixl:1000 " ≤₀ " => Mathlib.many_one_reducible theorem many_one_reducible.mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → β} (q : β → Prop) (h : computable f) : (fun (a : α) => q (f a)) ≤₀ q := Exists.intro f { left := h, right := fun (a : α) => iff.rfl } theorem many_one_reducible_refl {α : Type u_1} [primcodable α] (p : α → Prop) : p ≤₀ p := sorry theorem many_one_reducible.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ q → q ≤₀ r → p ≤₀ r := sorry theorem reflexive_many_one_reducible {α : Type u_1} [primcodable α] : reflexive many_one_reducible := many_one_reducible_refl theorem transitive_many_one_reducible {α : Type u_1} [primcodable α] : transitive many_one_reducible := fun (p q r : α → Prop) => many_one_reducible.trans /-- `p` is one-one reducible to `q` if there is an injective computable function translating questions about `p` to questions about `q`. -/ def one_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) := ∃ (f : α → β), computable f ∧ function.injective f ∧ ∀ (a : α), p a ↔ q (f a) infixl:1000 " ≤₁ " => Mathlib.one_one_reducible theorem one_one_reducible.mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → β} (q : β → Prop) (h : computable f) (i : function.injective f) : (fun (a : α) => q (f a)) ≤₁ q := Exists.intro f { left := h, right := { left := i, right := fun (a : α) => iff.rfl } } theorem one_one_reducible_refl {α : Type u_1} [primcodable α] (p : α → Prop) : p ≤₁ p := sorry theorem one_one_reducible.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₁ q → q ≤₁ r → p ≤₁ r := sorry theorem one_one_reducible.to_many_one {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : p ≤₁ q → p ≤₀ q := sorry theorem one_one_reducible.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (q : β → Prop) (h : computable ⇑e) : (q ∘ ⇑e) ≤₁ q := one_one_reducible.mk q h (equiv.injective e) theorem one_one_reducible.of_equiv_symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (q : β → Prop) (h : computable ⇑(equiv.symm e)) : q ≤₁ (q ∘ ⇑e) := sorry theorem reflexive_one_one_reducible {α : Type u_1} [primcodable α] : reflexive one_one_reducible := one_one_reducible_refl theorem transitive_one_one_reducible {α : Type u_1} [primcodable α] : transitive one_one_reducible := fun (p q r : α → Prop) => one_one_reducible.trans namespace computable_pred theorem computable_of_many_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} (h₁ : p ≤₀ q) (h₂ : computable_pred q) : computable_pred p := sorry theorem computable_of_one_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} (h : p ≤₁ q) : computable_pred q → computable_pred p := computable_of_many_one_reducible (one_one_reducible.to_many_one h) end computable_pred /-- `p` and `q` are many-one equivalent if each one is many-one reducible to the other. -/ def many_one_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) := p ≤₀ q ∧ q ≤₀ p /-- `p` and `q` are one-one equivalent if each one is one-one reducible to the other. -/ def one_one_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) := p ≤₁ q ∧ q ≤₁ p theorem many_one_equiv_refl {α : Type u_1} [primcodable α] (p : α → Prop) : many_one_equiv p p := { left := many_one_reducible_refl p, right := many_one_reducible_refl p } theorem many_one_equiv.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : many_one_equiv p q → many_one_equiv q p := and.swap theorem many_one_equiv.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : many_one_equiv p q → many_one_equiv q r → many_one_equiv p r := sorry theorem equivalence_of_many_one_equiv {α : Type u_1} [primcodable α] : equivalence many_one_equiv := { left := many_one_equiv_refl, right := { left := fun (x y : α → Prop) => many_one_equiv.symm, right := fun (x y z : α → Prop) => many_one_equiv.trans } } theorem one_one_equiv_refl {α : Type u_1} [primcodable α] (p : α → Prop) : one_one_equiv p p := { left := one_one_reducible_refl p, right := one_one_reducible_refl p } theorem one_one_equiv.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : one_one_equiv p q → one_one_equiv q p := and.swap theorem one_one_equiv.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : one_one_equiv p q → one_one_equiv q r → one_one_equiv p r := sorry theorem equivalence_of_one_one_equiv {α : Type u_1} [primcodable α] : equivalence one_one_equiv := { left := one_one_equiv_refl, right := { left := fun (x y : α → Prop) => one_one_equiv.symm, right := fun (x y z : α → Prop) => one_one_equiv.trans } } theorem one_one_equiv.to_many_one {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : one_one_equiv p q → many_one_equiv p q := sorry /-- a computable bijection -/ def equiv.computable {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (e : α ≃ β) := computable ⇑e ∧ computable ⇑(equiv.symm e) theorem equiv.computable.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} : equiv.computable e → equiv.computable (equiv.symm e) := and.swap theorem equiv.computable.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {e₁ : α ≃ β} {e₂ : β ≃ γ} : equiv.computable e₁ → equiv.computable e₂ → equiv.computable (equiv.trans e₁ e₂) := sorry theorem computable.eqv (α : Type u_1) [denumerable α] : equiv.computable (denumerable.eqv α) := { left := computable.encode, right := computable.of_nat α } theorem computable.equiv₂ (α : Type u_1) (β : Type u_2) [denumerable α] [denumerable β] : equiv.computable (denumerable.equiv₂ α β) := equiv.computable.trans (computable.eqv α) (equiv.computable.symm (computable.eqv β)) theorem one_one_equiv.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (h : equiv.computable e) {p : β → Prop} : one_one_equiv (p ∘ ⇑e) p := { left := one_one_reducible.of_equiv p (and.left h), right := one_one_reducible.of_equiv_symm p (and.right h) } theorem many_one_equiv.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (h : equiv.computable e) {p : β → Prop} : many_one_equiv (p ∘ ⇑e) p := one_one_equiv.to_many_one (one_one_equiv.of_equiv h) theorem many_one_equiv.le_congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv p q) : p ≤₀ r ↔ q ≤₀ r := { mp := many_one_reducible.trans (and.right h), mpr := many_one_reducible.trans (and.left h) } theorem many_one_equiv.le_congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv q r) : p ≤₀ q ↔ p ≤₀ r := { mp := fun (h' : p ≤₀ q) => many_one_reducible.trans h' (and.left h), mpr := fun (h' : p ≤₀ r) => many_one_reducible.trans h' (and.right h) } theorem one_one_equiv.le_congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv p q) : p ≤₁ r ↔ q ≤₁ r := { mp := one_one_reducible.trans (and.right h), mpr := one_one_reducible.trans (and.left h) } theorem one_one_equiv.le_congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv q r) : p ≤₁ q ↔ p ≤₁ r := { mp := fun (h' : p ≤₁ q) => one_one_reducible.trans h' (and.left h), mpr := fun (h' : p ≤₁ r) => one_one_reducible.trans h' (and.right h) } theorem many_one_equiv.congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv p q) : many_one_equiv p r ↔ many_one_equiv q r := and_congr (many_one_equiv.le_congr_left h) (many_one_equiv.le_congr_right h) theorem many_one_equiv.congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv q r) : many_one_equiv p q ↔ many_one_equiv p r := and_congr (many_one_equiv.le_congr_right h) (many_one_equiv.le_congr_left h) theorem one_one_equiv.congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv p q) : one_one_equiv p r ↔ one_one_equiv q r := and_congr (one_one_equiv.le_congr_left h) (one_one_equiv.le_congr_right h) theorem one_one_equiv.congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv q r) : one_one_equiv p q ↔ one_one_equiv p r := and_congr (one_one_equiv.le_congr_right h) (one_one_equiv.le_congr_left h) @[simp] theorem ulower.down_computable {α : Type u_1} [primcodable α] : equiv.computable (ulower.equiv α) := { left := primrec.to_comp primrec.ulower_down, right := primrec.to_comp primrec.ulower_up } theorem many_one_equiv_up {α : Type u_1} [primcodable α] {p : α → Prop} : many_one_equiv (p ∘ ulower.up) p := many_one_equiv.of_equiv (equiv.computable.symm ulower.down_computable) theorem one_one_reducible.disjoin_left {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : p ≤₁ sum.elim p q := Exists.intro sum.inl { left := computable.sum_inl, right := { left := fun (x y : α) => iff.mp sum.inl.inj_iff, right := fun (a : α) => iff.rfl } } theorem one_one_reducible.disjoin_right {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : q ≤₁ sum.elim p q := Exists.intro sum.inr { left := computable.sum_inr, right := { left := fun (x y : β) => iff.mp sum.inr.inj_iff, right := fun (a : β) => iff.rfl } } theorem disjoin_many_one_reducible {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ r → q ≤₀ r → sum.elim p q ≤₀ r := sorry theorem disjoin_le {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : sum.elim p q ≤₀ r ↔ p ≤₀ r ∧ q ≤₀ r := sorry /-- Computable and injective mapping of predicates to sets of natural numbers. -/ def to_nat {α : Type u} [primcodable α] [Inhabited α] (p : set α) : set ℕ := set_of fun (n : ℕ) => p (option.get_or_else (encodable.decode α n) Inhabited.default) @[simp] theorem to_nat_many_one_reducible {α : Type u} [primcodable α] [Inhabited α] {p : set α} : to_nat p ≤₀ p := Exists.intro (fun (n : ℕ) => option.get_or_else (encodable.decode α n) Inhabited.default) { left := computable.option_get_or_else computable.decode (computable.const Inhabited.default), right := fun (_x : ℕ) => iff.rfl } @[simp] theorem many_one_reducible_to_nat {α : Type u} [primcodable α] [Inhabited α] {p : set α} : p ≤₀ to_nat p := sorry @[simp] theorem many_one_reducible_to_nat_to_nat {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] {p : set α} {q : set β} : to_nat p ≤₀ to_nat q ↔ p ≤₀ q := sorry @[simp] theorem to_nat_many_one_equiv {α : Type u} [primcodable α] [Inhabited α] {p : set α} : many_one_equiv (to_nat p) p := sorry @[simp] theorem many_one_equiv_to_nat {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] (p : set α) (q : set β) : many_one_equiv (to_nat p) (to_nat q) ↔ many_one_equiv p q := sorry /-- A many-one degree is an equivalence class of sets up to many-one equivalence. -/ def many_one_degree := quotient (setoid.mk many_one_equiv sorry) namespace many_one_degree /-- The many-one degree of a set on a primcodable type. -/ def of {α : Type u} [primcodable α] [Inhabited α] (p : α → Prop) : many_one_degree := quotient.mk' (to_nat p) protected theorem ind_on {C : many_one_degree → Prop} (d : many_one_degree) (h : ∀ (p : set ℕ), C (of p)) : C d := quotient.induction_on' d h /-- Lifts a function on sets of natural numbers to many-one degrees. -/ protected def lift_on {φ : Sort u_1} (d : many_one_degree) (f : set ℕ → φ) (h : ∀ (p q : ℕ → Prop), many_one_equiv p q → f p = f q) : φ := quotient.lift_on' d f h @[simp] protected theorem lift_on_eq {φ : Sort u_1} (p : set ℕ) (f : set ℕ → φ) (h : ∀ (p q : ℕ → Prop), many_one_equiv p q → f p = f q) : many_one_degree.lift_on (of p) f h = f p := rfl /-- Lifts a binary function on sets of natural numbers to many-one degrees. -/ @[simp] protected def lift_on₂ {φ : Sort u_1} (d₁ : many_one_degree) (d₂ : many_one_degree) (f : set ℕ → set ℕ → φ) (h : ∀ (p₁ p₂ q₁ q₂ : ℕ → Prop), many_one_equiv p₁ p₂ → many_one_equiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) : φ := many_one_degree.lift_on d₁ (fun (p : set ℕ) => many_one_degree.lift_on d₂ (f p) sorry) sorry @[simp] protected theorem lift_on₂_eq {φ : Sort u_1} (p : set ℕ) (q : set ℕ) (f : set ℕ → set ℕ → φ) (h : ∀ (p₁ p₂ q₁ q₂ : ℕ → Prop), many_one_equiv p₁ p₂ → many_one_equiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) : many_one_degree.lift_on₂ (of p) (of q) f h = f p q := rfl @[simp] theorem of_eq_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] {p : α → Prop} {q : β → Prop} : of p = of q ↔ many_one_equiv p q := sorry protected instance inhabited : Inhabited many_one_degree := { default := of ∅ } /-- For many-one degrees `d₁` and `d₂`, `d₁ ≤ d₂` if the sets in `d₁` are many-one reducible to the sets in `d₂`. -/ protected instance has_le : HasLessEq many_one_degree := { LessEq := fun (d₁ d₂ : many_one_degree) => many_one_degree.lift_on₂ d₁ d₂ many_one_reducible sorry } @[simp] theorem of_le_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] {p : α → Prop} {q : β → Prop} : of p ≤ of q ↔ p ≤₀ q := many_one_reducible_to_nat_to_nat protected instance partial_order : partial_order many_one_degree := partial_order.mk LessEq (preorder.lt._default LessEq) le_refl sorry sorry /-- The join of two degrees, induced by the disjoint union of two underlying sets. -/ protected instance has_add : Add many_one_degree := { add := fun (d₁ d₂ : many_one_degree) => many_one_degree.lift_on₂ d₁ d₂ (fun (a b : set ℕ) => of (sum.elim a b)) sorry } @[simp] theorem add_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] (p : set α) (q : set β) : of (sum.elim p q) = of p + of q := sorry @[simp] protected theorem add_le {d₁ : many_one_degree} {d₂ : many_one_degree} {d₃ : many_one_degree} : d₁ + d₂ ≤ d₃ ↔ d₁ ≤ d₃ ∧ d₂ ≤ d₃ := sorry @[simp] protected theorem le_add_left (d₁ : many_one_degree) (d₂ : many_one_degree) : d₁ ≤ d₁ + d₂ := and.left (iff.mp many_one_degree.add_le (le_refl (d₁ + d₂))) @[simp] protected theorem le_add_right (d₁ : many_one_degree) (d₂ : many_one_degree) : d₂ ≤ d₁ + d₂ := and.right (iff.mp many_one_degree.add_le (le_refl (d₁ + d₂))) protected instance semilattice_sup : semilattice_sup many_one_degree := semilattice_sup.mk Add.add partial_order.le partial_order.lt partial_order.le_refl partial_order.le_trans partial_order.le_antisymm many_one_degree.le_add_left many_one_degree.le_add_right sorry end Mathlib
2e5579408ff32e2d0369f54f147c57d1dec6ee8c
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/native/default.lean
f72b79b4264ea6c9aaf075a2b63c1d9b464de8ee
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,814
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.meta.format import init.meta.expr import init.category.state import init.data.string import init.data.list.instances import init.native.ir import init.native.format import init.native.internal import init.native.anf import init.native.cf import init.native.pass import init.native.util import init.native.config import init.native.result namespace native inductive error : Type | string : string → error | many : list error → error meta def error.to_string : error → string | (error.string s) := s | (error.many es) := to_string $ list.map error.to_string es meta def arity_map : Type := rb_map name nat meta def get_arity : expr → nat | (expr.lam _ _ _ body) := 1 + get_arity body | _ := 0 @[reducible] def ir_result (A : Type*) := native.result error A meta def mk_arity_map : list (name × expr) → arity_map | [] := rb_map.mk name nat | ((n, body) :: rest) := rb_map.insert (mk_arity_map rest) n (get_arity body) @[reducible] meta def ir_compiler_state := (config × arity_map × nat) @[reducible] meta def ir_compiler (A : Type) := native.resultT (state ir_compiler_state) error A meta def lift {A} (action : state ir_compiler_state A) : ir_compiler A := ⟨fmap (fun (a : A), native.result.ok a) action⟩ meta def trace_ir (s : string) : ir_compiler unit := do (conf, map, counter) ← lift $ state.read, if config.debug conf then trace s (return ()) else return () -- An `exotic` monad combinator that accumulates errors. meta def run {M E A} (res : native.resultT M E A) : M (native.result E A) := match res with | ⟨action⟩ := action end meta def sequence_err : list (ir_compiler format) → ir_compiler (list format × list error) | [] := return ([], []) | (action :: remaining) := ⟨ fun s, match (run (sequence_err remaining)) s with | (native.result.err e, s') := (native.result.err e, s) | (native.result.ok (res, errs), s') := match (run action) s' with | (native.result.err e, s'') := (native.result.ok (res, e :: errs), s'') | (native.result.ok v, s'') := (native.result.ok (v :: res, errs), s'') end end ⟩ -- meta lemma sequence_err_always_ok : -- forall xs v s s', sequence_err xs s = native.result.ok (v, s') := sorry meta def lift_result {A} (action : ir_result A) : ir_compiler A := ⟨fun s, (action, s)⟩ -- TODO: fix naming here private meta def take_arguments' : expr → list name → (list name × expr) | (expr.lam n _ _ body) ns := take_arguments' body (n :: ns) | e' ns := (ns, e') meta def fresh_name : ir_compiler name := do (conf, map, counter) ← lift state.read, let fresh := name.mk_numeral (unsigned.of_nat counter) `native._ir_compiler_ in do lift $ state.write (conf, map, counter + 1), return fresh meta def take_arguments (e : expr) : ir_compiler (list name × expr) := let (arg_names, body) := take_arguments' e [] in do fresh_names ← monad.mapm (fun x, fresh_name) arg_names, let locals := list.map mk_local fresh_names in return $ (fresh_names, expr.instantiate_vars body (list.reverse locals)) -- meta def lift_state {A} (action : state arity_map A) : ir_compiler A := -- fun (s : arity_map), match action s with -- | (a, s) := (return a, s) -- end meta def mk_error {T} : string → ir_compiler T := fun s, do trace_ir "CREATEDERROR", lift_result (native.result.err $ error.string s) meta def lookup_arity (n : name) : ir_compiler nat := do (_, map, counter) ← lift state.read, if n = `nat.cases_on then pure 2 else match rb_map.find map n with | option.none := mk_error $ "could not find arity for: " ++ to_string n | option.some n := return n end meta def mk_nat_literal (n : nat) : ir_compiler ir.expr := return (ir.expr.lit $ ir.literal.nat n) def repeat {A : Type} : nat → A → list A | 0 _ := [] | (n + 1) a := a :: repeat n a def zip {A B : Type} : list A → list B → list (A × B) | [] [] := [] | [] (y :: ys) := [] | (x :: xs) [] := [] | (x :: xs) (y :: ys) := (x, y) :: zip xs ys private def upto' : ℕ → list ℕ | 0 := [] | (n + 1) := n :: upto' n def upto (n : ℕ) : list ℕ := list.reverse $ upto' n def label {A : Type} (xs : list A) : list (nat × A) := zip (upto (list.length xs)) xs -- lemma label_size_eq : -- forall A (xs : list A), -- list.length (label xs) = list.length xs := -- begin -- intros, -- induction xs, -- apply sorry -- apply sorry -- end -- HELPERS -- meta def assert_name : ir.expr → ir_compiler name | (ir.expr.locl n) := lift_result $ native.result.ok n | e := mk_error $ "expected name found: " ++ to_string (format_cpp.expr e) meta def assert_expr : ir.stmt → ir_compiler ir.expr | (ir.stmt.e exp) := return exp | s := mk_error ("internal invariant violated, found: " ++ (to_string (format_cpp.stmt s))) meta def mk_call (head : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', return (ir.expr.call head args') meta def mk_under_sat_call (head : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', return $ ir.expr.mk_native_closure head args' meta def bind_value_with_ty (val : ir.expr) (ty : ir.ty) (body : name → ir_compiler ir.stmt) : ir_compiler ir.stmt := do fresh ← fresh_name, ir.stmt.letb fresh ty val <$> (body fresh) meta def bind_value (val : ir.expr) (body : name → ir_compiler ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty val ir.ty.object body -- not in love with this --solution-- hack, revisit meta def compile_local (n : name) : ir_compiler name := return $ (mk_str_name "_$local$_" (name.to_string_with_sep "_" n)) meta def mk_invoke (loc : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', loc' ← compile_local loc, lift_result (native.result.ok $ ir.expr.invoke loc' args') meta def mk_over_sat_call (head : name) (fst snd : list ir.expr) : ir_compiler ir.expr := let fst' := list.map assert_name fst, snd' := list.map assert_name snd in do args' ← monad.sequence fst', args'' ← monad.sequence snd', fresh ← fresh_name, locl ← compile_local fresh, invoke ← ir.stmt.e <$> (mk_invoke fresh (fmap ir.expr.locl args'')), return $ ir.expr.block (ir.stmt.seq [ ir.stmt.letb locl ir.ty.object (ir.expr.call head args') ir.stmt.nop, invoke ]) meta def is_return (n : name) : bool := decidable.to_bool $ `native_compiler.return = n meta def compile_call (head : name) (arity : nat) (args : list ir.expr) : ir_compiler ir.expr := do trace_ir $ "compile_call: " ++ (to_string head), if list.length args = arity then mk_call head args else if list.length args < arity then mk_under_sat_call head args else mk_over_sat_call head (list.taken arity args) (list.dropn arity args) meta def mk_object (arity : unsigned) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', lift_result (native.result.ok $ ir.expr.mk_object (unsigned.to_nat arity) args') meta def one_or_error (args : list expr) : ir_compiler expr := match args with | ((h : expr) :: []) := lift_result $ native.result.ok h | _ := mk_error "internal invariant violated, should only have one argument" end meta def panic (msg : string) : ir_compiler ir.expr := return $ ir.expr.panic msg -- END HELPERS -- meta def bind_case_fields' (scrut : name) : list (nat × name) → ir.stmt → ir_compiler ir.stmt | [] body := return body | ((n, f) :: fs) body := do loc ← compile_local f, ir.stmt.letb f ir.ty.object (ir.expr.project scrut n) <$> (bind_case_fields' fs body) meta def bind_case_fields (scrut : name) (fs : list name) (body : ir.stmt) : ir_compiler ir.stmt := bind_case_fields' scrut (label fs) body meta def mk_cases_on (case_name scrut : name) (cases : list (nat × ir.stmt)) (default : ir.stmt) : ir.stmt := ir.stmt.seq [ ir.stmt.letb `ctor_index ir.ty.int (ir.expr.call `cidx [scrut]) ir.stmt.nop, ir.stmt.switch `ctor_index cases default ] meta def compile_cases (action : expr → ir_compiler ir.stmt) (scrut : name) : list (nat × expr) → ir_compiler (list (nat × ir.stmt)) | [] := return [] | ((n, body) :: cs) := do (fs, body') ← take_arguments body, body'' ← action body', cs' ← compile_cases cs, case ← bind_case_fields scrut fs body'', return $ (n, case) :: cs' meta def compile_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do default ← panic "default case should never be reached", match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, ir.expr.block <$> bind_value ir_scrut (fun scrut, do cs' ← compile_cases action scrut (label cs), return (mk_cases_on case_name scrut cs' (ir.stmt.e default))) end meta def bind_builtin_case_fields' (scrut : name) : list (nat × name) → ir.stmt → ir_compiler ir.stmt | [] body := return body | ((n, f) :: fs) body := do loc ← compile_local f, ir.stmt.letb loc ir.ty.object (ir.expr.project scrut n) <$> (bind_builtin_case_fields' fs body) meta def bind_builtin_case_fields (scrut : name) (fs : list name) (body : ir.stmt) : ir_compiler ir.stmt := bind_builtin_case_fields' scrut (label fs) body meta def compile_builtin_cases (action : expr → ir_compiler ir.stmt) (scrut : name) : list (nat × expr) → ir_compiler (list (nat × ir.stmt)) | [] := return [] | ((n, body) :: cs) := do (fs, body') ← take_arguments body, body'' ← action body', cs' ← compile_builtin_cases cs, case ← bind_builtin_case_fields scrut fs body'', return $ (n, case) :: cs' meta def in_lean_ns (n : name) : name := mk_simple_name ("lean::" ++ name.to_string_with_sep "_" n) meta def mk_builtin_cases_on (case_name scrut : name) (cases : list (nat × ir.stmt)) (default : ir.stmt) : ir.stmt := -- replace `ctor_index with a generated name ir.stmt.seq [ ir.stmt.letb `buffer ir.ty.object_buffer ir.expr.uninitialized ir.stmt.nop, ir.stmt.letb `ctor_index ir.ty.int (ir.expr.call (in_lean_ns case_name) [scrut, `buffer]) ir.stmt.nop, ir.stmt.switch `ctor_index cases default ] meta def compile_builtin_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do default ← panic "default case should never be reached", match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, ir.expr.block <$> bind_value ir_scrut (fun scrut, do cs' ← compile_builtin_cases action scrut (label cs), return (mk_builtin_cases_on case_name scrut cs' (ir.stmt.e default))) end meta def mk_is_simple (scrut : name) : ir.expr := ir.expr.call `is_simple [scrut] meta def mk_is_zero (n : name) : ir.expr := ir.expr.equals (ir.expr.raw_int 0) (ir.expr.locl n) meta def mk_cidx (obj : name) : ir.expr := ir.expr.call `cidx [obj] -- we should add applicative brackets meta def mk_simple_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty (mk_cidx scrut) (ir.ty.name `int) (fun cidx, bind_value_with_ty (mk_is_zero cidx) (ir.ty.name `bool) (fun is_zero, pure $ ir.stmt.ite is_zero zero_case succ_case)) meta def mk_mpz_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := ir.stmt.e <$> panic "mpz" meta def mk_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty (mk_is_simple scrut) (ir.ty.name `bool) (fun is_simple, ir.stmt.ite is_simple <$> mk_simple_nat_cases_on scrut zero_case succ_case <*> mk_mpz_nat_cases_on scrut zero_case succ_case) meta def assert_two_cases (cases : list expr) : ir_compiler (expr × expr) := match cases with | c1 :: c2 :: _ := return (c1, c2) | _ := mk_error "nat.cases_on should have exactly two cases" end meta def mk_vm_nat (n : name) : ir.expr := ir.expr.call (in_lean_ns `mk_vm_simple) [n] meta def compile_succ_case (action : expr → ir_compiler ir.stmt) (scrut : name) (succ_case : expr) : ir_compiler ir.stmt := do (fs, body') ← take_arguments succ_case, body'' ← action body', match fs with | pred :: _ := do loc ← compile_local pred, fresh ← fresh_name, bind_value_with_ty (mk_cidx scrut) (ir.ty.name `int) (fun cidx, bind_value_with_ty (ir.expr.sub (ir.expr.locl cidx) (ir.expr.raw_int 1)) (ir.ty.name `int) (fun sub, pure $ ir.stmt.letb loc ir.ty.object (mk_vm_nat sub) body'' )) | _ := mk_error "compile_succ_case too many fields" end meta def compile_nat_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, (zero_case, succ_case) ← assert_two_cases cs, trace_ir (to_string zero_case), trace_ir (to_string succ_case), ir.expr.block <$> bind_value ir_scrut (fun scrut, do zc ← action zero_case, sc ← compile_succ_case action scrut succ_case, mk_nat_cases_on scrut zc sc ) end -- this→emit_indented("if (is_simple("); -- action(scrutinee); -- this→emit_string("))"); -- this→emit_block([&] () { -- this→emit_indented("if (cidx("); -- action(scrutinee); -- this→emit_string(") == 0) "); -- this→emit_block([&] () { -- action(zero_case); -- *this→m_output_stream << ";\n"; -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- action(succ_case); -- *this→m_output_stream << ";\n"; -- }); -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- this→emit_indented("if (to_mpz("); -- action(scrutinee); -- this→emit_string(") == 0) "); -- this→emit_block([&] () { -- action(zero_case); -- *this→m_output_stream << ";\n"; -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- action(succ_case); -- }); -- }); -- this code isnt' great working around the semi-functional frontend meta def compile_expr_app_to_ir_expr (head : expr) (args : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do trace_ir (to_string head ++ to_string args), if expr.is_constant head = bool.tt then (if is_return (expr.const_name head) then do rexp ← one_or_error args, (ir.expr.block ∘ ir.stmt.return) <$> ((action rexp) >>= assert_expr) else if is_nat_cases_on (expr.const_name head) then compile_nat_cases_on_to_ir_expr (expr.const_name head) args action else match is_internal_cnstr head with | option.some n := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, mk_object n args' | option.none := match is_internal_cases head with | option.some n := compile_cases_on_to_ir_expr (expr.const_name head) args action | option.none := match get_builtin (expr.const_name head) with | option.some builtin := match builtin with | builtin.vm n := mk_error "vm" | builtin.cfun n arity := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, compile_call n arity args' | builtin.cases n arity := compile_builtin_cases_on_to_ir_expr (expr.const_name head) args action end | option.none := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, arity ← lookup_arity (expr.const_name head), compile_call (expr.const_name head) arity args' end end end) else if expr.is_local_constant head then do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, mk_invoke (expr.local_uniq_name head) args' else (mk_error ("unsupported call position" ++ (to_string head))) meta def compile_expr_macro_to_ir_expr (e : expr) : ir_compiler ir.expr := match native.get_nat_value e with | option.none := mk_error "unsupported macro" | option.some n := mk_nat_literal n end meta def compile_expr_to_ir_expr (action : expr → ir_compiler ir.stmt): expr → ir_compiler ir.expr | (expr.const n ls) := match native.is_internal_cnstr (expr.const n ls) with | option.none := -- TODO, do I need to case on arity here? I should probably always emit a call match get_builtin n with | option.some (builtin.cfun n' arity) := compile_call n arity [] | _ := if n = "_neutral_" then (pure $ ir.expr.mk_object 0 []) else do arity ← lookup_arity n, compile_call n arity [] end | option.some arity := pure $ ir.expr.mk_object (unsigned.to_nat arity) [] end | (expr.var i) := mk_error "there should be no bound variables in compiled terms" | (expr.sort _) := mk_error "found sort" | (expr.mvar _ _) := mk_error "unexpected meta-variable in expr" | (expr.local_const n _ _ _) := ir.expr.locl <$> compile_local n | (expr.app f x) := let head := expr.get_app_fn (expr.app f x), args := expr.get_app_args (expr.app f x) in compile_expr_app_to_ir_expr head args action | (expr.lam _ _ _ _) := mk_error "found lam" | (expr.pi _ _ _ _) := mk_error "found pi" | (expr.elet n _ v body) := mk_error "internal error: can not translate let binding into a ir_expr" | (expr.macro d sz args) := compile_expr_macro_to_ir_expr (expr.macro d sz args) meta def compile_expr_to_ir_stmt : expr → ir_compiler ir.stmt | (expr.pi _ _ _ _) := mk_error "found pi, should not be translating a Pi for any reason (yet ...)" | (expr.elet n _ v body) := do n' ← compile_local n, v' ← compile_expr_to_ir_expr compile_expr_to_ir_stmt v, -- this is a scoping fail, we need to fix how we compile locals body' ← compile_expr_to_ir_stmt (expr.instantiate_vars body [mk_local n]), -- not the best solution, here need to think hard about how to prevent thing, more aggressive anf? match v' with | ir.expr.block stmt := return (ir.stmt.seq [ir.stmt.letb n' ir.ty.object ir.expr.uninitialized ir.stmt.nop, body']) | _ := return (ir.stmt.letb n' ir.ty.object v' body') end | e' := ir.stmt.e <$> compile_expr_to_ir_expr compile_expr_to_ir_stmt e' meta def compile_defn_to_ir (decl_name : name) (args : list name) (body : expr) : ir_compiler ir.defn := do body' ← compile_expr_to_ir_stmt body, let params := (zip args (repeat (list.length args) (ir.ty.ref ir.ty.object))) in pure (ir.defn.mk decl_name params ir.ty.object body') def unwrap_or_else {T R : Type} : ir_result T → (T → R) → (error → R) → R | (native.result.err e) f err := err e | (native.result.ok t) f err := f t meta def replace_main (n : name) : name := if n = `main then "___lean__main" else n meta def trace_expr (e : expr) : ir_compiler unit := trace ("trace_expr: " ++ to_string e) (return ()) meta def compile_defn (decl_name : name) (e : expr) : ir_compiler format := let arity := get_arity e in do (args, body) ← take_arguments e, ir ← compile_defn_to_ir (replace_main decl_name) args body, return $ format_cpp.defn ir meta def compile' : list (name × expr) → list (ir_compiler format) | [] := [] | ((n, e) :: rest) := do let decl := (fun d, d ++ format.line ++ format.line) <$> compile_defn n e in decl :: (compile' rest) meta def format_error : error → format | (error.string s) := to_fmt s | (error.many es) := format_concat (list.map format_error es) meta def mk_lean_name (n : name) : ir.expr := ir.expr.constructor (in_lean_ns `name) (name.components n) meta def emit_declare_vm_builtins : list (name × expr) → ir_compiler (list ir.stmt) | [] := return [] | ((n, body) :: es) := do vm_name ← pure $ (mk_lean_name n), tail ← emit_declare_vm_builtins es, fresh ← fresh_name, let cpp_name := in_lean_ns `name, single_binding := ir.stmt.seq [ ir.stmt.letb fresh (ir.ty.name cpp_name) vm_name ir.stmt.nop, ir.stmt.e $ ir.expr.assign `env (ir.expr.call `add_native [`env, fresh, replace_main n]) ] in return $ single_binding :: tail meta def emit_main (procs : list (name × expr)) : ir_compiler ir.defn := do builtins ← emit_declare_vm_builtins procs, arity ← lookup_arity `main, vm_simple_obj ← fresh_name, call_main ← compile_call "___lean__main" arity [ir.expr.locl vm_simple_obj], return (ir.defn.mk `main [] ir.ty.int $ ir.stmt.seq ([ ir.stmt.e $ ir.expr.call (in_lean_ns `initialize) [], ir.stmt.letb `env (ir.ty.name (in_lean_ns `environment)) ir.expr.uninitialized ir.stmt.nop ] ++ builtins ++ [ ir.stmt.letb `ios (ir.ty.name (in_lean_ns `io_state)) (ir.expr.call (in_lean_ns `get_global_ios) []) ir.stmt.nop, ir.stmt.letb `opts (ir.ty.name (in_lean_ns `options)) (ir.expr.call (in_lean_ns `get_options_from_ios) [`ios]) ir.stmt.nop, ir.stmt.letb `S (ir.ty.name (in_lean_ns `vm_state)) (ir.expr.constructor (in_lean_ns `vm_state) [`env, `opts]) ir.stmt.nop, ir.stmt.letb `scoped (ir.ty.name (in_lean_ns `scope_vm_state)) (ir.expr.constructor (in_lean_ns `scope_vm_state) [`S]) ir.stmt.nop, ir.stmt.e $ ir.expr.assign `g_env (ir.expr.address_of `env), ir.stmt.letb vm_simple_obj ir.ty.object (ir.expr.mk_object 0 []) ir.stmt.nop, ir.stmt.e call_main ])) -- -- call_mains -- -- buffer<expr> args; -- -- auto unit = mk_neutral_expr(); -- -- args.push_back(unit); -- -- // Make sure to invoke the C call machinery since it is non-deterministic -- -- // which case we enter here. -- -- compile_to_c_call(main_fn, args, 0, name_map<unsigned>()); -- -- *this→m_output_stream << ";\n return 0;\n}" << std::endl; -- ] meta def unzip {A B} : list (A × B) → (list A × list B) | [] := ([], []) | ((x, y) :: rest) := let (xs, ys) := unzip rest in (x :: xs, y :: ys) meta def configuration : ir_compiler config := do (conf, _, _) ← lift $ state.read, pure conf meta def apply_pre_ir_passes (procs : list procedure) (conf : config) : list procedure := run_passes conf [anf, cf] procs meta def driver (procs : list (name × expr)) : ir_compiler (list format × list error) := do procs' ← apply_pre_ir_passes procs <$> configuration, (fmt_decls, errs) ← sequence_err (compile' procs'), main ← emit_main procs', return (format_cpp.defn main :: fmt_decls, errs) meta def compile (conf : config) (procs : list (name × expr)) : format := let arities := mk_arity_map procs in -- Put this in a combinator or something ... match run (driver procs) (conf, arities, 0) with | (native.result.err e, s) := error.to_string e | (native.result.ok (decls, errs), s) := if list.length errs = 0 then format_concat decls else format_error (error.many errs) end -- meta def compile (procs : list (name)) end native
846c263c2c4130e8287ac608d2dff0e0bb244507
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/set/basic.lean
0dc45166f664b8e3c464252f88d1732fa6efcabf
[ "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
36,003
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import logic.connectives logic.identities algebra.binary open eq.ops binary function definition set (X : Type) := X → Prop namespace set variable {X : Type} /- membership and subset -/ definition mem (x : X) (a : set X) := a x infix ∈ := mem notation a ∉ b := ¬ mem a b theorem ext {a b : set X} (H : ∀x, x ∈ a ↔ x ∈ b) : a = b := funext (take x, propext (H x)) definition subset (a b : set X) := ∀⦃x⦄, x ∈ a → x ∈ b infix ⊆ := subset definition superset (s t : set X) : Prop := t ⊆ s infix ⊇ := superset theorem subset.refl (a : set X) : a ⊆ a := take x, assume H, H theorem subset.trans {a b c : set X} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c := take x, assume ax, subbc (subab ax) theorem subset.antisymm {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) -- an alterantive name theorem eq_of_subset_of_subset {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set X} {a : X} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ _ h₂ /- strict subset -/ definition strict_subset (a b : set X) := a ⊆ b ∧ a ≠ b infix ` ⊂ `:50 := strict_subset theorem strict_subset.irrefl (a : set X) : ¬ a ⊂ a := assume h, absurd rfl (and.elim_right h) /- bounded quantification -/ abbreviation bounded_forall (a : set X) (P : X → Prop) := ∀⦃x⦄, x ∈ a → P x notation `forallb` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_forall a r notation `∀₀` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_forall a r abbreviation bounded_exists (a : set X) (P : X → Prop) := ∃⦃x⦄, x ∈ a ∧ P x notation `existsb` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_exists a r notation `∃₀` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_exists a r theorem bounded_exists.intro {P : X → Prop} {s : set X} {x : X} (xs : x ∈ s) (Px : P x) : ∃₀ x ∈ s, P x := exists.intro x (and.intro xs Px) lemma bounded_forall_congr {A : Type} {S : set A} {P Q : A → Prop} (H : ∀₀ x ∈ S, P x ↔ Q x) : (∀₀ x ∈ S, P x) = (∀₀ x ∈ S, Q x) := begin apply propext, apply forall_congr, intros x, apply imp_congr_right, apply H end lemma bounded_exists_congr {A : Type} {S : set A} {P Q : A → Prop} (H : ∀₀ x ∈ S, P x ↔ Q x) : (∃₀ x ∈ S, P x) = (∃₀ x ∈ S, Q x) := begin apply propext, apply exists_congr, intros x, apply and_congr_right, apply H end section local attribute classical.prop_decidable [instance] lemma not_bounded_exists {A : Type} {S : set A} {P : A → Prop} : (¬ (∃₀ x ∈ S, P x)) = (∀₀ x ∈ S, ¬ P x) := begin rewrite forall_iff_not_exists, apply propext, apply forall_congr, intro x, rewrite not_and_iff_not_or_not, rewrite imp_iff_not_or end lemma not_bounded_forall {A : Type} {S : set A} {P : A → Prop} : (¬ (∀₀ x ∈ S, P x)) = (∃₀ x ∈ S, ¬ P x) := calc (¬ (∀₀ x ∈ S, P x)) = ¬ ¬ (∃₀ x ∈ S, ¬ P x) : begin rewrite not_bounded_exists, apply (congr_arg not), apply bounded_forall_congr, intros x H, rewrite not_not_iff end ... = (∃₀ x ∈ S, ¬ P x) : by (rewrite not_not_iff) end /- empty set -/ definition empty : set X := λx, false notation `∅` := empty theorem not_mem_empty (x : X) : ¬ (x ∈ ∅) := assume H : x ∈ ∅, H theorem mem_empty_eq (x : X) : x ∈ ∅ = false := rfl theorem eq_empty_of_forall_not_mem {s : set X} (H : ∀ x, x ∉ s) : s = ∅ := ext (take x, iff.intro (assume xs, absurd xs (H x)) (assume xe, absurd xe !not_mem_empty)) theorem ne_empty_of_mem {s : set X} {x : X} (H : x ∈ s) : s ≠ ∅ := begin intro Hs, rewrite Hs at H, apply not_mem_empty _ H end section local attribute classical.prop_decidable [instance] theorem exists_mem_of_ne_empty {s : set X} (H : s ≠ ∅) : ∃ x, x ∈ s := by_contradiction (assume H', H (eq_empty_of_forall_not_mem (forall_not_of_not_exists H'))) end theorem empty_subset (s : set X) : ∅ ⊆ s := take x, assume H, false.elim H theorem eq_empty_of_subset_empty {s : set X} (H : s ⊆ ∅) : s = ∅ := subset.antisymm H (empty_subset s) theorem subset_empty_iff (s : set X) : s ⊆ ∅ ↔ s = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) lemma bounded_forall_empty_iff {P : X → Prop} : (∀₀x∈∅, P x) ↔ true := iff.intro (take H, true.intro) (take H, by contradiction) /- universal set -/ definition univ : set X := λx, true theorem mem_univ (x : X) : x ∈ univ := trivial theorem mem_univ_iff (x : X) : x ∈ univ ↔ true := !iff.refl theorem mem_univ_eq (x : X) : x ∈ univ = true := rfl theorem empty_ne_univ [h : inhabited X] : (empty : set X) ≠ univ := assume H : empty = univ, absurd (mem_univ (inhabited.value h)) (eq.rec_on H (not_mem_empty _)) theorem subset_univ (s : set X) : s ⊆ univ := λ x H, trivial theorem eq_univ_of_univ_subset {s : set X} (H : univ ⊆ s) : s = univ := eq_of_subset_of_subset (subset_univ s) H theorem eq_univ_of_forall {s : set X} (H : ∀ x, x ∈ s) : s = univ := ext (take x, iff.intro (assume H', trivial) (assume H', H x)) /- union -/ definition union (a b : set X) : set X := λx, x ∈ a ∨ x ∈ b notation a ∪ b := union a b theorem mem_union_left {x : X} {a : set X} (b : set X) : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_union_right {x : X} {b : set X} (a : set X) : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_unionl {x : X} {a b : set X} : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_unionr {x : X} {a b : set X} : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_or_mem_of_mem_union {x : X} {a b : set X} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : X} {a b : set X} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union_iff (x : X) (a b : set X) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := !iff.refl theorem mem_union_eq (x : X) (a b : set X) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl theorem union_self (a : set X) : a ∪ a = a := ext (take x, !or_self) theorem union_empty (a : set X) : a ∪ ∅ = a := ext (take x, !or_false) theorem empty_union (a : set X) : ∅ ∪ a = a := ext (take x, !false_or) theorem union_comm (a b : set X) : a ∪ b = b ∪ a := ext (take x, or.comm) theorem union_assoc (a b c : set X) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (take x, or.assoc) theorem union_left_comm (s₁ s₂ s₃ : set X) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : set X) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem subset_union_left (s t : set X) : s ⊆ s ∪ t := λ x H, or.inl H theorem subset_union_right (s t : set X) : t ⊆ s ∪ t := λ x H, or.inr H theorem union_subset {s t r : set X} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x xst, or.elim xst (λ xs, sr xs) (λ xt, tr xt) /- intersection -/ definition inter (a b : set X) : set X := λx, x ∈ a ∧ x ∈ b notation a ∩ b := inter a b theorem mem_inter_iff (x : X) (a b : set X) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := !iff.refl theorem mem_inter_eq (x : X) (a b : set X) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : X} {a b : set X} (Ha : x ∈ a) (Hb : x ∈ b) : x ∈ a ∩ b := and.intro Ha Hb theorem mem_of_mem_inter_left {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ a := and.left H theorem mem_of_mem_inter_right {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ b := and.right H theorem inter_self (a : set X) : a ∩ a = a := ext (take x, !and_self) theorem inter_empty (a : set X) : a ∩ ∅ = ∅ := ext (take x, !and_false) theorem empty_inter (a : set X) : ∅ ∩ a = ∅ := ext (take x, !false_and) theorem nonempty_of_inter_nonempty_right {T : Type} {s t : set T} (H : s ∩ t ≠ ∅) : t ≠ ∅ := suppose t = ∅, have s ∩ t = ∅, by rewrite this; apply inter_empty, H this theorem nonempty_of_inter_nonempty_left {T : Type} {s t : set T} (H : s ∩ t ≠ ∅) : s ≠ ∅ := suppose s = ∅, have s ∩ t = ∅, by rewrite this; apply empty_inter, H this theorem inter_comm (a b : set X) : a ∩ b = b ∩ a := ext (take x, !and.comm) theorem inter_assoc (a b c : set X) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (take x, !and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : set X) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : set X) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_univ (a : set X) : a ∩ univ = a := ext (take x, !and_true) theorem univ_inter (a : set X) : univ ∩ a = a := ext (take x, !true_and) theorem inter_subset_left (s t : set X) : s ∩ t ⊆ s := λ x H, and.left H theorem inter_subset_right (s t : set X) : s ∩ t ⊆ t := λ x H, and.right H theorem inter_subset_inter_right {s t : set X} (u : set X) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := take x, assume xsu, and.intro (H (and.left xsu)) (and.right xsu) theorem inter_subset_inter_left {s t : set X} (u : set X) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := take x, assume xus, and.intro (and.left xus) (H (and.right xus)) theorem subset_inter {s t r : set X} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x xr, and.intro (rs xr) (rt xr) theorem not_mem_of_mem_of_not_mem_inter_left {s t : set X} {x : X} (Hxs : x ∈ s) (Hnm : x ∉ s ∩ t) : x ∉ t := suppose x ∈ t, have x ∈ s ∩ t, from and.intro Hxs this, show false, from Hnm this theorem not_mem_of_mem_of_not_mem_inter_right {s t : set X} {x : X} (Hxs : x ∈ t) (Hnm : x ∉ s ∩ t) : x ∉ s := suppose x ∈ s, have x ∈ s ∩ t, from and.intro this Hxs, show false, from Hnm this /- distributivity laws -/ theorem inter_distrib_left (s t u : set X) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, !and.left_distrib) theorem inter_distrib_right (s t u : set X) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, !and.right_distrib) theorem union_distrib_left (s t u : set X) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, !or.left_distrib) theorem union_distrib_right (s t u : set X) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, !or.right_distrib) /- set-builder notation -/ -- {x : X | P} definition set_of (P : X → Prop) : set X := P notation `{` binder ` | ` r:(scoped:1 P, set_of P) `}` := r -- {x ∈ s | P} definition sep (P : X → Prop) (s : set X) : set X := λx, x ∈ s ∧ P x notation `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r /- insert -/ definition insert (x : X) (a : set X) : set X := {y : X | y = x ∨ y ∈ a} -- '{x, y, z} notation `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem subset_insert (x : X) (a : set X) : a ⊆ insert x a := take y, assume ys, or.inr ys theorem mem_insert (x : X) (s : set X) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : X} {s : set X} (y : X) : x ∈ s → x ∈ insert y s := assume h, or.inr h theorem eq_or_mem_of_mem_insert {x a : X} {s : set X} : x ∈ insert a s → x = a ∨ x ∈ s := assume h, h theorem mem_of_mem_insert_of_ne {x a : X} {s : set X} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_eq (x a : X) (s : set X) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem)) theorem insert_eq_of_mem {a : X} {s : set X} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem insert.comm (x y : X) (s : set X) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) -- useful in proofs by induction theorem forall_of_forall_insert {P : X → Prop} {a : X} {s : set X} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (!mem_insert_of_mem xs) lemma bounded_forall_insert_iff {P : X → Prop} {a : X} {s : set X} : (∀₀x ∈ insert a s, P x) ↔ P a ∧ (∀₀x ∈ s, P x) := begin apply iff.intro, all_goals (intro H), { apply and.intro, { apply H, apply mem_insert }, { intro x Hx, apply H, apply mem_insert_of_mem, assumption } }, { intro x Hx, cases Hx with eq Hx, { cases eq, apply (and.elim_left H) }, { apply (and.elim_right H), assumption } } end /- singleton -/ theorem mem_singleton_iff (a b : X) : a ∈ '{b} ↔ a = b := iff.intro (assume ainb, or.elim ainb (λ aeqb, aeqb) (λ f, false.elim f)) (assume aeqb, or.inl aeqb) theorem mem_singleton (a : X) : a ∈ '{a} := !mem_insert theorem eq_of_mem_singleton {x y : X} (h : x ∈ '{y}) : x = y := or.elim (eq_or_mem_of_mem_insert h) (suppose x = y, this) (suppose x ∈ ∅, absurd this !not_mem_empty) theorem mem_singleton_of_eq {x y : X} (H : x = y) : x ∈ '{y} := eq.symm H ▸ mem_singleton y theorem insert_eq (x : X) (s : set X) : insert x s = '{x} ∪ s := ext (take y, iff.intro (suppose y ∈ insert x s, or.elim this (suppose y = x, or.inl (or.inl this)) (suppose y ∈ s, or.inr this)) (suppose y ∈ '{x} ∪ s, or.elim this (suppose y ∈ '{x}, or.inl (eq_of_mem_singleton this)) (suppose y ∈ s, or.inr this))) theorem pair_eq_singleton (a : X) : '{a, a} = '{a} := by rewrite [insert_eq_of_mem !mem_singleton] theorem singleton_ne_empty (a : X) : '{a} ≠ ∅ := begin intro H, apply not_mem_empty a, rewrite -H, apply mem_insert end /- separation -/ theorem mem_sep {s : set X} {P : X → Prop} {x : X} (xs : x ∈ s) (Px : P x) : x ∈ {x ∈ s | P x} := and.intro xs Px theorem eq_sep_of_subset {s t : set X} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, and.intro (ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, and.right this)) theorem mem_sep_iff {s : set X} {P : X → Prop} {x : X} : x ∈ {x ∈ s | P x} ↔ x ∈ s ∧ P x := !iff.refl theorem sep_subset (s : set X) (P : X → Prop) : {x ∈ s | P x} ⊆ s := take x, assume H, and.left H theorem forall_not_of_sep_empty {s : set X} {P : X → Prop} (H : {x ∈ s | P x} = ∅) : ∀₀ x ∈ s, ¬ P x := take x, suppose x ∈ s, suppose P x, have x ∈ {x ∈ s | P x}, from and.intro `x ∈ s` this, show false, from ne_empty_of_mem this H /- complement -/ definition compl (s : set X) : set X := {x | x ∉ s} prefix `-` := compl theorem mem_compl {s : set X} {x : X} (H : x ∉ s) : x ∈ -s := H theorem not_mem_of_mem_compl {s : set X} {x : X} (H : x ∈ -s) : x ∉ s := H theorem mem_compl_iff (s : set X) (x : X) : x ∈ -s ↔ x ∉ s := !iff.refl theorem inter_compl_self (s : set X) : s ∩ -s = ∅ := ext (take x, !and_not_self_iff) theorem compl_inter_self (s : set X) : -s ∩ s = ∅ := ext (take x, !not_and_self_iff) /- some classical identities -/ section local attribute classical.prop_decidable [instance] theorem compl_empty : -(∅ : set X) = univ := ext (take x, iff.intro (assume H, trivial) (assume H, not_false)) theorem compl_union (s t : set X) : -(s ∪ t) = -s ∩ -t := ext (take x, !not_or_iff_not_and_not) theorem compl_compl (s : set X) : -(-s) = s := ext (take x, !not_not_iff) theorem compl_inter (s t : set X) : -(s ∩ t) = -s ∪ -t := ext (take x, !not_and_iff_not_or_not) theorem compl_univ : -(univ : set X) = ∅ := by rewrite [-compl_empty, compl_compl] theorem union_eq_compl_compl_inter_compl (s t : set X) : s ∪ t = -(-s ∩ -t) := ext (take x, !or_iff_not_and_not) theorem inter_eq_compl_compl_union_compl (s t : set X) : s ∩ t = -(-s ∪ -t) := ext (take x, !and_iff_not_or_not) theorem union_compl_self (s : set X) : s ∪ -s = univ := ext (take x, !or_not_self_iff) theorem compl_union_self (s : set X) : -s ∪ s = univ := ext (take x, !not_or_self_iff) theorem compl_comp_compl : #function compl ∘ compl = @id (set X) := funext (λ s, compl_compl s) end /- set difference -/ definition diff (s t : set X) : set X := {x ∈ s | x ∉ t} infix `\`:70 := diff theorem mem_diff {s t : set X} {x : X} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := and.intro H1 H2 theorem mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∈ s := and.left H theorem not_mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∉ t := and.right H theorem mem_diff_iff (s t : set X) (x : X) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := !iff.refl theorem mem_diff_eq (s t : set X) (x : X) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := rfl theorem diff_eq (s t : set X) : s \ t = s ∩ -t := rfl theorem union_diff_cancel {s t : set X} [dec : Π x, decidable (x ∈ s)] (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (assume H1 : x ∈ s ∪ (t \ s), or.elim H1 (assume H2, !H H2) (assume H2, and.left H2)) (assume H1 : x ∈ t, decidable.by_cases (suppose x ∈ s, or.inl this) (suppose x ∉ s, or.inr (and.intro H1 this)))) theorem diff_subset (s t : set X) : s \ t ⊆ s := inter_subset_left s _ theorem compl_eq_univ_diff (s : set X) : -s = univ \ s := ext (take x, iff.intro (assume H, and.intro trivial H) (assume H, and.right H)) /- powerset -/ definition powerset (s : set X) : set (set X) := {x : set X | x ⊆ s} prefix `𝒫`:100 := powerset theorem mem_powerset {x s : set X} (H : x ⊆ s) : x ∈ 𝒫 s := H theorem subset_of_mem_powerset {x s : set X} (H : x ∈ 𝒫 s) : x ⊆ s := H theorem mem_powerset_iff (x s : set X) : x ∈ 𝒫 s ↔ x ⊆ s := !iff.refl /- function image -/ section image variables {Y Z : Type} abbreviation eq_on (f1 f2 : X → Y) (a : set X) : Prop := ∀₀ x ∈ a, f1 x = f2 x definition image (f : X → Y) (a : set X) : set Y := {y : Y | ∃x, x ∈ a ∧ f x = y} infix ` ' ` := image theorem image_eq_image_of_eq_on {f1 f2 : X → Y} {a : set X} (H1 : eq_on f1 f2 a) : f1 ' a = f2 ' a := ext (take y, iff.intro (assume H2, obtain x (H3 : x ∈ a ∧ f1 x = y), from H2, have H4 : x ∈ a, from and.left H3, have H5 : f2 x = y, from (H1 H4)⁻¹ ⬝ and.right H3, exists.intro x (and.intro H4 H5)) (assume H2, obtain x (H3 : x ∈ a ∧ f2 x = y), from H2, have H4 : x ∈ a, from and.left H3, have H5 : f1 x = y, from (H1 H4) ⬝ and.right H3, exists.intro x (and.intro H4 H5))) theorem mem_image {f : X → Y} {a : set X} {x : X} {y : Y} (H1 : x ∈ a) (H2 : f x = y) : y ∈ f ' a := exists.intro x (and.intro H1 H2) theorem mem_image_of_mem (f : X → Y) {x : X} {a : set X} (H : x ∈ a) : f x ∈ image f a := mem_image H rfl lemma image_comp (f : Y → Z) (g : X → Y) (a : set X) : (f ∘ g) ' a = f ' (g ' a) := ext (take z, iff.intro (assume Hz : z ∈ (f ∘ g) ' a, obtain x (Hx₁ : x ∈ a) (Hx₂ : f (g x) = z), from Hz, have Hgx : g x ∈ g ' a, from mem_image Hx₁ rfl, show z ∈ f ' (g ' a), from mem_image Hgx Hx₂) (assume Hz : z ∈ f ' (g 'a), obtain y (Hy₁ : y ∈ g ' a) (Hy₂ : f y = z), from Hz, obtain x (Hz₁ : x ∈ a) (Hz₂ : g x = y), from Hy₁, show z ∈ (f ∘ g) ' a, from mem_image Hz₁ (Hz₂⁻¹ ▸ Hy₂))) lemma image_subset {a b : set X} (f : X → Y) (H : a ⊆ b) : f ' a ⊆ f ' b := take y, assume Hy : y ∈ f ' a, obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from Hy, mem_image (H Hx₁) Hx₂ theorem image_union (f : X → Y) (s t : set X) : image f (s ∪ t) = image f s ∪ image f t := ext (take y, iff.intro (assume H : y ∈ image f (s ∪ t), obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from H, or.elim xst (assume xs, or.inl (mem_image xs fxy)) (assume xt, or.inr (mem_image xt fxy))) (assume H : y ∈ image f s ∪ image f t, or.elim H (assume yifs : y ∈ image f s, obtain x [(xs : x ∈ s) (fxy : f x = y)], from yifs, mem_image (or.inl xs) fxy) (assume yift : y ∈ image f t, obtain x [(xt : x ∈ t) (fxy : f x = y)], from yift, mem_image (or.inr xt) fxy))) theorem image_empty (f : X → Y) : image f ∅ = ∅ := eq_empty_of_forall_not_mem (take y, suppose y ∈ image f ∅, obtain x [(H : x ∈ empty) H'], from this, H) theorem mem_image_compl (t : set X) (S : set (set X)) : t ∈ compl ' S ↔ -t ∈ S := iff.intro (suppose t ∈ compl ' S, obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this, show -t ∈ S, by rewrite [-Ht, compl_compl]; exact Ht') (suppose -t ∈ S, have -(-t) ∈ compl 'S, from mem_image_of_mem compl this, show t ∈ compl 'S, from compl_compl t ▸ this) theorem image_id (s : set X) : id ' s = s := ext (take x, iff.intro (suppose x ∈ id ' s, obtain x' [(Hx' : x' ∈ s) (x'eq : x' = x)], from this, show x ∈ s, by rewrite [-x'eq]; apply Hx') (suppose x ∈ s, mem_image_of_mem id this)) theorem compl_compl_image (S : set (set X)) : compl ' (compl ' S) = S := by rewrite [-image_comp, compl_comp_compl, image_id] lemma bounded_forall_image_of_bounded_forall {f : X → Y} {S : set X} {P : Y → Prop} (H : ∀₀ x ∈ S, P (f x)) : ∀₀ y ∈ f ' S, P y := begin intro x' Hx; cases Hx with x Hx; cases Hx with Hx eq; rewrite (eq⁻¹); apply H; assumption end lemma bounded_forall_image_iff {f : X → Y} {S : set X} {P : Y → Prop} : (∀₀ y ∈ f ' S, P y) ↔ (∀₀ x ∈ S, P (f x)) := iff.intro (take H x Hx, H _ (!mem_image_of_mem `x ∈ S`)) bounded_forall_image_of_bounded_forall lemma image_insert_eq {f : X → Y} {a : X} {S : set X} : f ' insert a S = insert (f a) (f ' S) := begin apply set.ext, intro x, apply iff.intro, all_goals (intros H), { cases H with y Hy, cases Hy with Hy eq, rewrite (eq⁻¹), cases Hy with y_eq, { rewrite y_eq, apply mem_insert }, { apply mem_insert_of_mem, apply mem_image_of_mem, assumption } }, { cases H with eq Hx, { rewrite eq, apply mem_image_of_mem, apply mem_insert }, { cases Hx with y Hy, cases Hy with Hy eq, rewrite (eq⁻¹), apply mem_image_of_mem, apply mem_insert_of_mem, assumption } } end end image /- collections of disjoint sets -/ definition disjoint_sets (S : set (set X)) : Prop := ∀ a b, a ∈ S → b ∈ S → a ≠ b → a ∩ b = ∅ theorem disjoint_sets_empty : disjoint_sets (∅ : set (set X)) := take a b, assume H, !not.elim !not_mem_empty H theorem disjoint_sets_union {s t : set (set X)} (Hs : disjoint_sets s) (Ht : disjoint_sets t) (H : ∀ x y, x ∈ s ∧ y ∈ t → x ∩ y = ∅) : disjoint_sets (s ∪ t) := take a b, assume Ha Hb Hneq, or.elim Ha (assume H1, or.elim Hb (suppose b ∈ s, (Hs a b) H1 this Hneq) (suppose b ∈ t, (H a b) (and.intro H1 this))) (assume H2, or.elim Hb (suppose b ∈ s, !inter_comm ▸ ((H b a) (and.intro this H2))) (suppose b ∈ t, (Ht a b) H2 this Hneq)) theorem disjoint_sets_singleton (s : set (set X)) : disjoint_sets '{s} := take a b, assume Ha Hb Hneq, absurd (eq.trans ((iff.elim_left !mem_singleton_iff) Ha) ((iff.elim_left !mem_singleton_iff) Hb)⁻¹) Hneq /- large unions -/ section large_unions variables {I : Type} variable a : set I variable b : I → set X variable C : set (set X) definition sUnion : set X := {x : X | ∃₀ c ∈ C, x ∈ c} definition sInter : set X := {x : X | ∀₀ c ∈ C, x ∈ c} prefix `⋃₀`:110 := sUnion prefix `⋂₀`:110 := sInter definition Union : set X := {x : X | ∃i, x ∈ b i} definition Inter : set X := {x : X | ∀i, x ∈ b i} notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r definition bUnion : set X := {x : X | ∃₀ i ∈ a, x ∈ b i} definition bInter : set X := {x : X | ∀₀ i ∈ a, x ∈ b i} notation `⋃` binders ` ∈ ` s `, ` r:(scoped f, bUnion s f) := r notation `⋂` binders ` ∈ ` s `, ` r:(scoped f, bInter s f) := r end large_unions -- sUnion and sInter: a collection (set) of sets theorem mem_sUnion {x : X} {t : set X} {S : set (set X)} (Hx : x ∈ t) (Ht : t ∈ S) : x ∈ ⋃₀ S := exists.intro t (and.intro Ht Hx) theorem not_mem_of_not_mem_sUnion {x : X} {t : set X} {S : set (set X)} (Hx : x ∉ ⋃₀ S) (Ht : t ∈ S) : x ∉ t := suppose x ∈ t, have x ∈ ⋃₀ S, from mem_sUnion this Ht, show false, from Hx this theorem mem_sInter {x : X} {t : set X} {S : set (set X)} (H : ∀₀ t ∈ S, x ∈ t) : x ∈ ⋂₀ S := H theorem sInter_subset_of_mem {S : set (set X)} {t : set X} (tS : t ∈ S) : (⋂₀ S) ⊆ t := take x, assume H, H t tS theorem subset_sUnion_of_mem {S : set (set X)} {t : set X} (tS : t ∈ S) : t ⊆ (⋃₀ S) := take x, assume H, exists.intro t (and.intro tS H) theorem sUnion_empty : ⋃₀ ∅ = (∅ : set X) := eq_empty_of_forall_not_mem (take x, suppose x ∈ sUnion ∅, obtain t [(Ht : t ∈ ∅) Ht'], from this, show false, from Ht) theorem sInter_empty : ⋂₀ ∅ = (univ : set X) := eq_univ_of_forall (λ x s H, false.elim H) theorem sUnion_singleton (s : set X) : ⋃₀ '{s} = s := ext (take x, iff.intro (suppose x ∈ sUnion '{s}, obtain u [(Hu : u ∈ '{s}) (xu : x ∈ u)], from this, have u = s, from eq_of_mem_singleton Hu, show x ∈ s, by rewrite -this; apply xu) (suppose x ∈ s, mem_sUnion this (mem_singleton s))) theorem sInter_singleton (s : set X) : ⋂₀ '{s} = s := ext (take x, iff.intro (suppose x ∈ ⋂₀ '{s}, show x ∈ s, from this (mem_singleton s)) (suppose x ∈ s, take u, suppose u ∈ '{s}, show x ∈ u, by rewrite [eq_of_mem_singleton this]; assumption)) theorem sUnion_union (S T : set (set X)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := ext (take x, iff.intro (suppose x ∈ sUnion (S ∪ T), obtain u [(Hu : u ∈ S ∪ T) (xu : x ∈ u)], from this, or.elim Hu (assume uS, or.inl (mem_sUnion xu uS)) (assume uT, or.inr (mem_sUnion xu uT))) (suppose x ∈ sUnion S ∪ sUnion T, or.elim this (suppose x ∈ sUnion S, obtain u [(uS : u ∈ S) (xu : x ∈ u)], from this, mem_sUnion xu (or.inl uS)) (suppose x ∈ sUnion T, obtain u [(uT : u ∈ T) (xu : x ∈ u)], from this, mem_sUnion xu (or.inr uT)))) theorem sInter_union (S T : set (set X)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := ext (take x, iff.intro (assume H : x ∈ ⋂₀ (S ∪ T), and.intro (λ u uS, H (or.inl uS)) (λ u uT, H (or.inr uT))) (assume H : x ∈ ⋂₀ S ∩ ⋂₀ T, take u, suppose u ∈ S ∪ T, or.elim this (λ uS, and.left H u uS) (λ uT, and.right H u uT))) theorem sUnion_insert (s : set X) (T : set (set X)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := by rewrite [insert_eq, sUnion_union, sUnion_singleton] theorem sInter_insert (s : set X) (T : set (set X)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := by rewrite [insert_eq, sInter_union, sInter_singleton] theorem compl_sUnion (S : set (set X)) : - ⋃₀ S = ⋂₀ (compl ' S) := ext (take x, iff.intro (assume H : x ∈ -(⋃₀ S), take t, suppose t ∈ compl ' S, obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this, have x ∈ -t', from suppose x ∈ t', H (mem_sUnion this Ht'), show x ∈ t, by rewrite -Ht; apply this) (assume H : x ∈ ⋂₀ (compl ' S), suppose x ∈ ⋃₀ S, obtain t [(tS : t ∈ S) (xt : x ∈ t)], from this, have -t ∈ compl ' S, from mem_image_of_mem compl tS, have x ∈ -t, from H this, show false, proof this xt qed)) theorem sUnion_eq_compl_sInter_compl (S : set (set X)) : ⋃₀ S = - ⋂₀ (compl ' S) := by rewrite [-compl_compl, compl_sUnion] theorem compl_sInter (S : set (set X)) : - ⋂₀ S = ⋃₀ (compl ' S) := by rewrite [sUnion_eq_compl_sInter_compl, compl_compl_image] theorem sInter_eq_comp_sUnion_compl (S : set (set X)) : ⋂₀ S = -(⋃₀ (compl ' S)) := by rewrite [-compl_compl, compl_sInter] theorem inter_sUnion_nonempty_of_inter_nonempty {s t : set X} {S : set (set X)} (Hs : t ∈ S) (Hne : s ∩ t ≠ ∅) : s ∩ ⋃₀ S ≠ ∅ := obtain x Hsx Htx, from exists_mem_of_ne_empty Hne, have x ∈ ⋃₀ S, from mem_sUnion Htx Hs, ne_empty_of_mem (mem_inter Hsx this) theorem sUnion_inter_nonempty_of_inter_nonempty {s t : set X} {S : set (set X)} (Hs : t ∈ S) (Hne : t ∩ s ≠ ∅) : (⋃₀ S) ∩ s ≠ ∅ := obtain x Htx Hsx, from exists_mem_of_ne_empty Hne, have x ∈ ⋃₀ S, from mem_sUnion Htx Hs, ne_empty_of_mem (mem_inter this Hsx) -- Union and Inter: a family of sets indexed by a type theorem Union_subset {I : Type} {b : I → set X} {c : set X} (H : ∀ i, b i ⊆ c) : (⋃ i, b i) ⊆ c := take x, suppose x ∈ Union b, obtain i (Hi : x ∈ b i), from this, show x ∈ c, from H i Hi theorem subset_Inter {I : Type} {b : I → set X} {c : set X} (H : ∀ i, c ⊆ b i) : c ⊆ ⋂ i, b i := λ x cx i, H i cx theorem Union_eq_sUnion_image {X I : Type} (s : I → set X) : (⋃ i, s i) = ⋃₀ (s ' univ) := ext (take x, iff.intro (suppose x ∈ Union s, obtain i (Hi : x ∈ s i), from this, mem_sUnion Hi (mem_image_of_mem s trivial)) (suppose x ∈ sUnion (s ' univ), obtain t [(Ht : t ∈ s ' univ) (Hx : x ∈ t)], from this, obtain i [univi (Hi : s i = t)], from Ht, exists.intro i (show x ∈ s i, by rewrite Hi; apply Hx))) theorem Inter_eq_sInter_image {X I : Type} (s : I → set X) : (⋂ i, s i) = ⋂₀ (s ' univ) := ext (take x, iff.intro (assume H : x ∈ Inter s, take t, suppose t ∈ s 'univ, obtain i [univi (Hi : s i = t)], from this, show x ∈ t, by rewrite -Hi; exact H i) (assume H : x ∈ ⋂₀ (s ' univ), take i, have s i ∈ s ' univ, from mem_image_of_mem s trivial, show x ∈ s i, from H this)) theorem compl_Union {X I : Type} (s : I → set X) : - (⋃ i, s i) = (⋂ i, - s i) := by rewrite [Union_eq_sUnion_image, compl_sUnion, -image_comp, -Inter_eq_sInter_image] theorem compl_Inter {X I : Type} (s : I → set X) : -(⋂ i, s i) = (⋃ i, - s i) := by rewrite [Inter_eq_sInter_image, compl_sInter, -image_comp, -Union_eq_sUnion_image] theorem Union_eq_comp_Inter_comp {X I : Type} (s : I → set X) : (⋃ i, s i) = - (⋂ i, - s i) := by rewrite [-compl_compl, compl_Union] theorem Inter_eq_comp_Union_comp {X I : Type} (s : I → set X) : (⋂ i, s i) = - (⋃ i, -s i) := by rewrite [-compl_compl, compl_Inter] lemma inter_distrib_Union_left {X I : Type} (s : I → set X) (a : set X) : a ∩ (⋃ i, s i) = ⋃ i, a ∩ s i := ext (take x, iff.intro (assume H, obtain i Hi, from and.elim_right H, have x ∈ a ∩ s i, from and.intro (and.elim_left H) Hi, show _, from exists.intro i this) (assume H, obtain i [xa xsi], from H, show _, from and.intro xa (exists.intro i xsi))) section local attribute classical.prop_decidable [instance] lemma union_distrib_Inter_left {X I : Type} (s : I → set X) (a : set X) : a ∪ (⋂ i, s i) = ⋂ i, a ∪ s i := ext (take x, iff.intro (assume H, or.elim H (assume H1, take i, or.inl H1) (assume H1, take i, or.inr (H1 i))) (assume H, by_cases (suppose x ∈ a, or.inl this) (suppose x ∉ a, or.inr (take i, or.resolve_left (H i) this)))) end -- these are useful for turning binary union / intersection into countable ones definition bin_ext (s t : set X) (n : ℕ) : set X := nat.cases_on n s (λ m, t) lemma Union_bin_ext (s t : set X) : (⋃ i, bin_ext s t i) = s ∪ t := ext (take x, iff.intro (assume H, obtain i (Hi : x ∈ (bin_ext s t) i), from H, by cases i; apply or.inl Hi; apply or.inr Hi) (assume H, or.elim H (suppose x ∈ s, exists.intro 0 this) (suppose x ∈ t, exists.intro 1 this))) lemma Inter_bin_ext (s t : set X) : (⋂ i, bin_ext s t i) = s ∩ t := ext (take x, iff.intro (assume H, and.intro (H 0) (H 1)) (assume H, by intro i; cases i; apply and.elim_left H; apply and.elim_right H)) -- bUnion and bInter: a family of sets indexed by a set ("b" is for bounded) variable {Y : Type} theorem mem_bUnion {s : set X} {f : X → set Y} {x : X} {y : Y} (xs : x ∈ s) (yfx : y ∈ f x) : y ∈ ⋃ x ∈ s, f x := exists.intro x (and.intro xs yfx) theorem mem_bInter {s : set X} {f : X → set Y} {y : Y} (H : ∀₀ x ∈ s, y ∈ f x) : y ∈ ⋂ x ∈ s, f x := H theorem bUnion_subset {s : set X} {t : set Y} {f : X → set Y} (H : ∀₀ x ∈ s, f x ⊆ t) : (⋃ x ∈ s, f x) ⊆ t := take y, assume Hy, obtain x [xs yfx], from Hy, show y ∈ t, from H xs yfx theorem subset_bInter {s : set X} {t : set Y} {f : X → set Y} (H : ∀₀ x ∈ s, t ⊆ f x) : t ⊆ ⋂ x ∈ s, f x := take y, assume yt, take x, assume xs, H xs yt theorem subset_bUnion_of_mem {s : set X} {f : X → set Y} {x : X} (xs : x ∈ s) : f x ⊆ ⋃ x ∈ s, f x := take y, assume Hy, mem_bUnion xs Hy theorem bInter_subset_of_mem {s : set X} {f : X → set Y} {x : X} (xs : x ∈ s) : (⋂ x ∈ s, f x) ⊆ f x := take y, assume Hy, Hy x xs theorem bInter_empty (f : X → set Y) : (⋂ x ∈ (∅ : set X), f x) = univ := eq_univ_of_forall (take y x xine, absurd xine !not_mem_empty) theorem bInter_singleton (a : X) (f : X → set Y) : (⋂ x ∈ '{a}, f x) = f a := ext (take y, iff.intro (assume H, H a !mem_singleton) (assume H, λ x xa, by rewrite [eq_of_mem_singleton xa]; apply H)) theorem bInter_union (s t : set X) (f : X → set Y) : (⋂ x ∈ s ∪ t, f x) = (⋂ x ∈ s, f x) ∩ (⋂ x ∈ t, f x) := ext (take y, iff.intro (assume H, and.intro (λ x xs, H x (or.inl xs)) (λ x xt, H x (or.inr xt))) (assume H, λ x xst, or.elim (xst) (λ xs, and.left H x xs) (λ xt, and.right H x xt))) theorem bInter_insert (a : X) (s : set X) (f : X → set Y) : (⋂ x ∈ insert a s, f x) = f a ∩ (⋂ x ∈ s, f x) := by rewrite [insert_eq, bInter_union, bInter_singleton] theorem bInter_pair (a b : X) (f : X → set Y) : (⋂ x ∈ '{a, b}, f x) = f a ∩ f b := by rewrite [*bInter_insert, bInter_empty, inter_univ] theorem bUnion_empty (f : X → set Y) : (⋃ x ∈ (∅ : set X), f x) = ∅ := eq_empty_of_forall_not_mem (λ y H, obtain x [xine yfx], from H, !not_mem_empty xine) theorem bUnion_singleton (a : X) (f : X → set Y) : (⋃ x ∈ '{a}, f x) = f a := ext (take y, iff.intro (assume H, obtain x [xina yfx], from H, show y ∈ f a, by rewrite [-eq_of_mem_singleton xina]; exact yfx) (assume H, exists.intro a (and.intro !mem_singleton H))) theorem bUnion_union (s t : set X) (f : X → set Y) : (⋃ x ∈ s ∪ t, f x) = (⋃ x ∈ s, f x) ∪ (⋃ x ∈ t, f x) := ext (take y, iff.intro (assume H, obtain x [xst yfx], from H, or.elim xst (λ xs, or.inl (exists.intro x (and.intro xs yfx))) (λ xt, or.inr (exists.intro x (and.intro xt yfx)))) (assume H, or.elim H (assume H1, obtain x [xs yfx], from H1, exists.intro x (and.intro (or.inl xs) yfx)) (assume H1, obtain x [xt yfx], from H1, exists.intro x (and.intro (or.inr xt) yfx)))) theorem bUnion_insert (a : X) (s : set X) (f : X → set Y) : (⋃ x ∈ insert a s, f x) = f a ∪ (⋃ x ∈ s, f x) := by rewrite [insert_eq, bUnion_union, bUnion_singleton] theorem bUnion_pair (a b : X) (f : X → set Y) : (⋃ x ∈ '{a, b}, f x) = f a ∪ f b := by rewrite [*bUnion_insert, bUnion_empty, union_empty] end set
4cb4e705a82084c2ad544d1529bbfe8f721c3350
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/BoundedJoinLattice.lean
3c93d382b17e7d465de2be6a83f968ae895fa75d
[]
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
11,947
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 BoundedJoinLattice structure BoundedJoinLattice (A : Type) : Type := (plus : (A → (A → A))) (commutative_plus : (∀ {x y : A} , (plus x y) = (plus y x))) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) (idempotent_plus : (∀ {x : A} , (plus x x) = x)) (zero : A) (lunit_zero : (∀ {x : A} , (plus zero x) = x)) (runit_zero : (∀ {x : A} , (plus x zero) = x)) (times : (A → (A → A))) (commutative_times : (∀ {x y : A} , (times x y) = (times y x))) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (idempotent_times : (∀ {x : A} , (times x x) = x)) (leftAbsorp_times_plus : (∀ {x y : A} , (times x (plus x y)) = x)) (leftAbsorp_plus_times : (∀ {x y : A} , (plus x (times x y)) = x)) open BoundedJoinLattice structure Sig (AS : Type) : Type := (plusS : (AS → (AS → AS))) (zeroS : AS) (timesS : (AS → (AS → AS))) structure Product (A : Type) : Type := (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (zeroP : (Prod A A)) (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (commutative_plusP : (∀ {xP yP : (Prod A A)} , (plusP xP yP) = (plusP yP xP))) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) (idempotent_plusP : (∀ {xP : (Prod A A)} , (plusP xP xP) = xP)) (lunit_0P : (∀ {xP : (Prod A A)} , (plusP zeroP xP) = xP)) (runit_0P : (∀ {xP : (Prod A A)} , (plusP xP zeroP) = xP)) (commutative_timesP : (∀ {xP yP : (Prod A A)} , (timesP xP yP) = (timesP yP xP))) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) (idempotent_timesP : (∀ {xP : (Prod A A)} , (timesP xP xP) = xP)) (leftAbsorp_times_plusP : (∀ {xP yP : (Prod A A)} , (timesP xP (plusP xP yP)) = xP)) (leftAbsorp_plus_timesP : (∀ {xP yP : (Prod A A)} , (plusP xP (timesP xP yP)) = xP)) structure Hom {A1 : Type} {A2 : Type} (Bo1 : (BoundedJoinLattice A1)) (Bo2 : (BoundedJoinLattice A2)) : Type := (hom : (A1 → A2)) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Bo1) x1 x2)) = ((plus Bo2) (hom x1) (hom x2)))) (pres_zero : (hom (zero Bo1)) = (zero Bo2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Bo1) x1 x2)) = ((times Bo2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Bo1 : (BoundedJoinLattice A1)) (Bo2 : (BoundedJoinLattice A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Bo1) x1 x2) ((plus Bo2) y1 y2)))))) (interp_zero : (interp (zero Bo1) (zero Bo2))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Bo1) x1 x2) ((times Bo2) y1 y2)))))) inductive BoundedJoinLatticeTerm : Type | plusL : (BoundedJoinLatticeTerm → (BoundedJoinLatticeTerm → BoundedJoinLatticeTerm)) | zeroL : BoundedJoinLatticeTerm | timesL : (BoundedJoinLatticeTerm → (BoundedJoinLatticeTerm → BoundedJoinLatticeTerm)) open BoundedJoinLatticeTerm inductive ClBoundedJoinLatticeTerm (A : Type) : Type | sing : (A → ClBoundedJoinLatticeTerm) | plusCl : (ClBoundedJoinLatticeTerm → (ClBoundedJoinLatticeTerm → ClBoundedJoinLatticeTerm)) | zeroCl : ClBoundedJoinLatticeTerm | timesCl : (ClBoundedJoinLatticeTerm → (ClBoundedJoinLatticeTerm → ClBoundedJoinLatticeTerm)) open ClBoundedJoinLatticeTerm inductive OpBoundedJoinLatticeTerm (n : ℕ) : Type | v : ((fin n) → OpBoundedJoinLatticeTerm) | plusOL : (OpBoundedJoinLatticeTerm → (OpBoundedJoinLatticeTerm → OpBoundedJoinLatticeTerm)) | zeroOL : OpBoundedJoinLatticeTerm | timesOL : (OpBoundedJoinLatticeTerm → (OpBoundedJoinLatticeTerm → OpBoundedJoinLatticeTerm)) open OpBoundedJoinLatticeTerm inductive OpBoundedJoinLatticeTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpBoundedJoinLatticeTerm2) | sing2 : (A → OpBoundedJoinLatticeTerm2) | plusOL2 : (OpBoundedJoinLatticeTerm2 → (OpBoundedJoinLatticeTerm2 → OpBoundedJoinLatticeTerm2)) | zeroOL2 : OpBoundedJoinLatticeTerm2 | timesOL2 : (OpBoundedJoinLatticeTerm2 → (OpBoundedJoinLatticeTerm2 → OpBoundedJoinLatticeTerm2)) open OpBoundedJoinLatticeTerm2 def simplifyCl {A : Type} : ((ClBoundedJoinLatticeTerm A) → (ClBoundedJoinLatticeTerm A)) | (plusCl zeroCl x) := x | (plusCl x zeroCl) := x | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | zeroCl := zeroCl | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpBoundedJoinLatticeTerm n) → (OpBoundedJoinLatticeTerm n)) | (plusOL zeroOL x) := x | (plusOL x zeroOL) := x | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | zeroOL := zeroOL | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpBoundedJoinLatticeTerm2 n A) → (OpBoundedJoinLatticeTerm2 n A)) | (plusOL2 zeroOL2 x) := x | (plusOL2 x zeroOL2) := x | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | zeroOL2 := zeroOL2 | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((BoundedJoinLattice A) → (BoundedJoinLatticeTerm → A)) | Bo (plusL x1 x2) := ((plus Bo) (evalB Bo x1) (evalB Bo x2)) | Bo zeroL := (zero Bo) | Bo (timesL x1 x2) := ((times Bo) (evalB Bo x1) (evalB Bo x2)) def evalCl {A : Type} : ((BoundedJoinLattice A) → ((ClBoundedJoinLatticeTerm A) → A)) | Bo (sing x1) := x1 | Bo (plusCl x1 x2) := ((plus Bo) (evalCl Bo x1) (evalCl Bo x2)) | Bo zeroCl := (zero Bo) | Bo (timesCl x1 x2) := ((times Bo) (evalCl Bo x1) (evalCl Bo x2)) def evalOpB {A : Type} {n : ℕ} : ((BoundedJoinLattice A) → ((vector A n) → ((OpBoundedJoinLatticeTerm n) → A))) | Bo vars (v x1) := (nth vars x1) | Bo vars (plusOL x1 x2) := ((plus Bo) (evalOpB Bo vars x1) (evalOpB Bo vars x2)) | Bo vars zeroOL := (zero Bo) | Bo vars (timesOL x1 x2) := ((times Bo) (evalOpB Bo vars x1) (evalOpB Bo vars x2)) def evalOp {A : Type} {n : ℕ} : ((BoundedJoinLattice A) → ((vector A n) → ((OpBoundedJoinLatticeTerm2 n A) → A))) | Bo vars (v2 x1) := (nth vars x1) | Bo vars (sing2 x1) := x1 | Bo vars (plusOL2 x1 x2) := ((plus Bo) (evalOp Bo vars x1) (evalOp Bo vars x2)) | Bo vars zeroOL2 := (zero Bo) | Bo vars (timesOL2 x1 x2) := ((times Bo) (evalOp Bo vars x1) (evalOp Bo vars x2)) def inductionB {P : (BoundedJoinLatticeTerm → Type)} : ((∀ (x1 x2 : BoundedJoinLatticeTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((P zeroL) → ((∀ (x1 x2 : BoundedJoinLatticeTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → (∀ (x : BoundedJoinLatticeTerm) , (P x))))) | pplusl p0l ptimesl (plusL x1 x2) := (pplusl _ _ (inductionB pplusl p0l ptimesl x1) (inductionB pplusl p0l ptimesl x2)) | pplusl p0l ptimesl zeroL := p0l | pplusl p0l ptimesl (timesL x1 x2) := (ptimesl _ _ (inductionB pplusl p0l ptimesl x1) (inductionB pplusl p0l ptimesl x2)) def inductionCl {A : Type} {P : ((ClBoundedJoinLatticeTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClBoundedJoinLatticeTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((P zeroCl) → ((∀ (x1 x2 : (ClBoundedJoinLatticeTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → (∀ (x : (ClBoundedJoinLatticeTerm A)) , (P x)))))) | psing ppluscl p0cl ptimescl (sing x1) := (psing x1) | psing ppluscl p0cl ptimescl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ppluscl p0cl ptimescl x1) (inductionCl psing ppluscl p0cl ptimescl x2)) | psing ppluscl p0cl ptimescl zeroCl := p0cl | psing ppluscl p0cl ptimescl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ppluscl p0cl ptimescl x1) (inductionCl psing ppluscl p0cl ptimescl x2)) def inductionOpB {n : ℕ} {P : ((OpBoundedJoinLatticeTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpBoundedJoinLatticeTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((P zeroOL) → ((∀ (x1 x2 : (OpBoundedJoinLatticeTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → (∀ (x : (OpBoundedJoinLatticeTerm n)) , (P x)))))) | pv pplusol p0ol ptimesol (v x1) := (pv x1) | pv pplusol p0ol ptimesol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv pplusol p0ol ptimesol x1) (inductionOpB pv pplusol p0ol ptimesol x2)) | pv pplusol p0ol ptimesol zeroOL := p0ol | pv pplusol p0ol ptimesol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv pplusol p0ol ptimesol x1) (inductionOpB pv pplusol p0ol ptimesol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpBoundedJoinLatticeTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpBoundedJoinLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((P zeroOL2) → ((∀ (x1 x2 : (OpBoundedJoinLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → (∀ (x : (OpBoundedJoinLatticeTerm2 n A)) , (P x))))))) | pv2 psing2 pplusol2 p0ol2 ptimesol2 (v2 x1) := (pv2 x1) | pv2 psing2 pplusol2 p0ol2 ptimesol2 (sing2 x1) := (psing2 x1) | pv2 psing2 pplusol2 p0ol2 ptimesol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 pplusol2 p0ol2 ptimesol2 x1) (inductionOp pv2 psing2 pplusol2 p0ol2 ptimesol2 x2)) | pv2 psing2 pplusol2 p0ol2 ptimesol2 zeroOL2 := p0ol2 | pv2 psing2 pplusol2 p0ol2 ptimesol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 pplusol2 p0ol2 ptimesol2 x1) (inductionOp pv2 psing2 pplusol2 p0ol2 ptimesol2 x2)) def stageB : (BoundedJoinLatticeTerm → (Staged BoundedJoinLatticeTerm)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | zeroL := (Now zeroL) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClBoundedJoinLatticeTerm A) → (Staged (ClBoundedJoinLatticeTerm A))) | (sing x1) := (Now (sing x1)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | zeroCl := (Now zeroCl) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpBoundedJoinLatticeTerm n) → (Staged (OpBoundedJoinLatticeTerm n))) | (v x1) := (const (code (v x1))) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | zeroOL := (Now zeroOL) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpBoundedJoinLatticeTerm2 n A) → (Staged (OpBoundedJoinLatticeTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | zeroOL2 := (Now zeroOL2) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (zeroT : (Repr A)) (timesT : ((Repr A) → ((Repr A) → (Repr A)))) end BoundedJoinLattice
c6cbe369a2b7610499280f1656b105e373e4361e
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world02/level02.lean
d1257b65182564c6d023934302b8b8f2bd656bac
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
180
lean
lemma add_assoc (a b c : mynat) : (a + b) + c = a + (b + c) := begin induction c with h hd, rw add_zero, rw add_zero, refl, rw add_succ, rw add_succ, rw add_succ, rw hd, refl, end
e36f385a1cce350d9e1cdac5fc79992b7b56448b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/quotient.lean
559dbecec9c268d916d7e7a1f5bd9450f7c28647
[ "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
17,104
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 group_theory.quotient_group import linear_algebra.span /-! # Quotients by submodules * If `p` is a submodule of `M`, `M ⧸ 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 quotient_add_group /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `-x + y ∈ p`. Note this is equivalent to `y - x ∈ p`, but defined this way to be be defeq to the `add_subgroup` version, where commutativity can't be assumed. -/ def quotient_rel : setoid M := quotient_add_group.left_rel p.to_add_subgroup lemma quotient_rel_r_def {x y : M} : @setoid.r _ (p.quotient_rel) x y ↔ x - y ∈ p := iff.trans (by { rw [left_rel_apply, sub_eq_add_neg, neg_add, neg_neg], refl }) neg_mem_iff /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ instance has_quotient : has_quotient M (submodule R M) := ⟨λ p, 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 → M ⧸ 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 : M ⧸ p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : M ⧸ p) = mk x := rfl protected theorem eq' {x y : M} : (mk x : M ⧸ p) = mk y ↔ -x + y ∈ p := quotient_add_group.eq protected theorem eq {x y : M} : (mk x : M ⧸ p) = mk y ↔ x - y ∈ p := (p^.quotient.eq').trans (left_rel_apply.symm.trans p.quotient_rel_r_def) instance : has_zero (M ⧸ p) := ⟨mk 0⟩ instance : inhabited (M ⧸ p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : M ⧸ p) := rfl @[simp] theorem mk_eq_zero : (mk x : M ⧸ p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance add_comm_group : add_comm_group (M ⧸ p) := quotient_add_group.add_comm_group p.to_add_subgroup @[simp] theorem mk_add : (mk (x + y) : M ⧸ p) = mk x + mk y := rfl @[simp] theorem mk_neg : (mk (-x) : M ⧸ p) = -mk x := rfl @[simp] theorem mk_sub : (mk (x - y) : M ⧸ p) = mk x - mk y := rfl section has_smul variables {S : Type*} [has_smul S R] [has_smul S M] [is_scalar_tower S R M] (P : submodule R M) instance has_smul' : has_smul S (M ⧸ P) := ⟨λ a, quotient.map' ((•) a) $ λ x y h, left_rel_apply.mpr $ by simpa [smul_sub] using P.smul_mem (a • 1 : R) (left_rel_apply.mp h)⟩ /-- Shortcut to help the elaborator in the common case. -/ instance has_smul : has_smul R (M ⧸ P) := quotient.has_smul' P @[simp] theorem mk_smul (r : S) (x : M) : (mk (r • x) : M ⧸ p) = r • mk x := rfl instance smul_comm_class (T : Type*) [has_smul T R] [has_smul T M] [is_scalar_tower T R M] [smul_comm_class S T M] : smul_comm_class S T (M ⧸ P) := { smul_comm := λ x y, quotient.ind' $ by exact λ z, congr_arg mk (smul_comm _ _ _) } instance is_scalar_tower (T : Type*) [has_smul T R] [has_smul T M] [is_scalar_tower T R M] [has_smul S T] [is_scalar_tower S T M] : is_scalar_tower S T (M ⧸ P) := { smul_assoc := λ x y, quotient.ind' $ by exact λ z, congr_arg mk (smul_assoc _ _ _) } instance is_central_scalar [has_smul Sᵐᵒᵖ R] [has_smul Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] : is_central_scalar S (M ⧸ P) := { op_smul_eq_smul := λ x, quotient.ind' $ by exact λ z, congr_arg mk $ op_smul_eq_smul _ _ } end has_smul section module variables {S : Type*} instance mul_action' [monoid S] [has_smul S R] [mul_action S M] [is_scalar_tower S R M] (P : submodule R M) : mul_action S (M ⧸ P) := function.surjective.mul_action mk (surjective_quot_mk _) P^.quotient.mk_smul instance mul_action (P : submodule R M) : mul_action R (M ⧸ P) := quotient.mul_action' P instance distrib_mul_action' [monoid S] [has_smul S R] [distrib_mul_action S M] [is_scalar_tower S R M] (P : submodule R M) : distrib_mul_action S (M ⧸ 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 (M ⧸ P) := quotient.distrib_mul_action' P instance module' [semiring S] [has_smul S R] [module S M] [is_scalar_tower S R M] (P : submodule R M) : module S (M ⧸ P) := function.surjective.module _ ⟨mk, rfl, λ _ _, rfl⟩ (surjective_quot_mk _) P^.quotient.mk_smul instance module (P : submodule R M) : module R (M ⧸ 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_smul S R] [module S M] [is_scalar_tower S R M] (P : submodule R M) : (M ⧸ P.restrict_scalars S) ≃ₗ[S] M ⧸ P := { 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_smul 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_smul 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 (M ⧸ p) := 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 : M ⧸ 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] M ⧸ p := { 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 lemma mkq_surjective (A : submodule R M) : function.surjective A.mkq := by rintro ⟨x⟩; exact ⟨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 : M ⧸ p →ₛₗ[τ₁₂] 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) : M ⧸ p →ₛₗ[τ₁₂] M₂ := { map_smul' := by rintro a ⟨x⟩; exact f.map_smulₛₗ a x, ..quotient_add_group.lift p.to_add_subgroup f.to_add_monoid_hom h } @[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 /--Special case of `liftq` when `p` is the span of `x`. In this case, the condition on `f` simply becomes vanishing at `x`.-/ def liftq_span_singleton (x : M) (f : M →ₛₗ[τ₁₂] M₂) (h : f x = 0) : (M ⧸ R ∙ x) →ₛₗ[τ₁₂] M₂ := (R ∙ x).liftq f $ by rw [span_singleton_le_iff_mem, linear_map.mem_ker, h] @[simp] lemma liftq_span_singleton_apply (x : M) (f : M →ₛₗ[τ₁₂] M₂) (h : f x = 0) (y : M) : liftq_span_singleton x f h (quotient.mk y) = f y := rfl @[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 (M ⧸ p)) : 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_rfl @[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) : (M ⧸ p) →ₛₗ[τ₁₂] (M₂ ⧸ q) := 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 @[simp] lemma mapq_zero (h : p ≤ q.comap (0 : M →ₛₗ[τ₁₂] M₂) := by simp) : p.mapq q (0 : M →ₛₗ[τ₁₂] M₂) h = 0 := by { ext, simp, } /-- Given submodules `p ⊆ M`, `p₂ ⊆ M₂`, `p₃ ⊆ M₃` and maps `f : M → M₂`, `g : M₂ → M₃` inducing `mapq f : M ⧸ p → M₂ ⧸ p₂` and `mapq g : M₂ ⧸ p₂ → M₃ ⧸ p₃` then `mapq (g ∘ f) = (mapq g) ∘ (mapq f)`. -/ lemma mapq_comp {R₃ M₃ : Type*} [ring R₃] [add_comm_group M₃] [module R₃ M₃] (p₂ : submodule R₂ M₂) (p₃ : submodule R₃ M₃) {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) (hf : p ≤ p₂.comap f) (hg : p₂ ≤ p₃.comap g) (h := (hf.trans (comap_mono hg))) : p.mapq p₃ (g.comp f) h = (p₂.mapq p₃ g hg).comp (p.mapq p₂ f hf) := by { ext, simp, } @[simp] lemma mapq_id (h : p ≤ p.comap linear_map.id := by { rw comap_id, exact le_refl _ }) : p.mapq p linear_map.id h = linear_map.id := by { ext, simp, } lemma mapq_pow {f : M →ₗ[R] M} (h : p ≤ p.comap f) (k : ℕ) (h' : p ≤ p.comap (f^k) := p.le_comap_pow_of_le_comap h k) : p.mapq p (f^k) h' = (p.mapq p f h)^k := begin induction k with k ih, { simp [linear_map.one_eq_id], }, { simp only [linear_map.iterate_succ, ← ih], apply p.mapq_comp, }, end 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_rfl) theorem map_liftq [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (h) (q : submodule R (M ⧸ 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 (M ⧸ p) ≃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 (M ⧸ p) ↪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 (M ⧸ p)) : 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, ←linear_map.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₂] M₂ ⧸ f.range), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R₂] M₂ ⧸ f.range).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 = ⊥) : (M ⧸ p) ≃ₗ[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] M ⧸ p) = p.mkq := rfl /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = p') : (M ⧸ p) ≃ₗ[R] M ⧸ p' := { 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] (M ⧸ p) →ₗ[R] (M₂ ⧸ q) := { 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
56569c2804eb92dbb5a46a13575915779dafe273
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/omega/int/form.lean
4de2b5889b9a9ceffbe4cbf8a0ad64ac85bda275
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
4,162
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear integer arithmetic formulas in pre-normalized form. -/ import tactic.omega.int.preterm namespace omega namespace int /-- Intermediate shadow syntax for LNA formulas that includes unreified exprs -/ meta inductive exprform | eq : exprterm → exprterm → exprform | le : exprterm → exprterm → exprform | not : exprform → exprform | or : exprform → exprform → exprform | and : exprform → exprform → exprform /-- Intermediate shadow syntax for LIA formulas that includes non-canonical terms -/ @[derive has_reflect, derive inhabited] inductive preform | eq : preterm → preterm → preform | le : preterm → preterm → preform | not : preform → preform | or : preform → preform → preform | and : preform → preform → preform localized "notation x ` =* ` y := omega.int.preform.eq x y" in omega.int localized "notation x ` ≤* ` y := omega.int.preform.le x y" in omega.int localized "notation `¬* ` p := omega.int.preform.not p" in omega.int localized "notation p ` ∨* ` q := omega.int.preform.or p q" in omega.int localized "notation p ` ∧* ` q := omega.int.preform.and p q" in omega.int namespace preform /-- Evaluate a preform into prop using the valuation v. -/ @[simp] def holds (v : nat → int) : preform → Prop | (t =* s) := t.val v = s.val v | (t ≤* s) := t.val v ≤ s.val v | (¬* p) := ¬ p.holds | (p ∨* q) := p.holds ∨ q.holds | (p ∧* q) := p.holds ∧ q.holds end preform /-- univ_close p n := p closed by prepending n universal quantifiers -/ @[simp] def univ_close (p : preform) : (nat → int) → nat → Prop | v 0 := p.holds v | v (k+1) := ∀ i : int, univ_close (update_zero i v) k namespace preform /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preform → nat | (t =* s) := max t.fresh_index s.fresh_index | (t ≤* s) := max t.fresh_index s.fresh_index | (¬* p) := p.fresh_index | (p ∨* q) := max p.fresh_index q.fresh_index | (p ∧* q) := max p.fresh_index q.fresh_index /-- All valuations satisfy argument -/ def valid (p : preform) : Prop := ∀ v, holds v p /-- There exists some valuation that satisfies argument -/ def sat (p : preform) : Prop := ∃ v, holds v p /-- implies p q := under any valuation, q holds if p holds -/ def implies (p q : preform) : Prop := ∀ v, (holds v p → holds v q) /-- equiv p q := under any valuation, p holds iff q holds -/ def equiv (p q : preform) : Prop := ∀ v, (holds v p ↔ holds v q) lemma sat_of_implies_of_sat {p q : preform} : implies p q → sat p → sat q := begin intros h1 h2, apply exists_imp_exists h1 h2 end lemma sat_or {p q : preform} : sat (p ∨* q) ↔ sat p ∨ sat q := begin constructor; intro h1, { cases h1 with v h1, cases h1 with h1 h1; [left,right]; refine ⟨v,_⟩; assumption }, { cases h1 with h1 h1; cases h1 with v h1; refine ⟨v,_⟩; [left,right]; assumption } end /-- There does not exist any valuation that satisfies argument -/ def unsat (p : preform) : Prop := ¬ sat p def repr : preform → string | (t =* s) := "(" ++ t.repr ++ " = " ++ s.repr ++ ")" | (t ≤* s) := "(" ++ t.repr ++ " ≤ " ++ s.repr ++ ")" | (¬* p) := "¬" ++ p.repr | (p ∨* q) := "(" ++ p.repr ++ " ∨ " ++ q.repr ++ ")" | (p ∧* q) := "(" ++ p.repr ++ " ∧ " ++ q.repr ++ ")" instance has_repr : has_repr preform := ⟨repr⟩ meta instance has_to_format : has_to_format preform := ⟨λ x, x.repr⟩ end preform lemma univ_close_of_valid {p : preform} : ∀ {m v}, p.valid → univ_close p v m | 0 v h1 := h1 _ | (m+1) v h1 := λ i, univ_close_of_valid h1 lemma valid_of_unsat_not {p : preform} : (¬*p).unsat → p.valid := begin simp only [preform.sat, preform.unsat, preform.valid, preform.holds], rw not_exists_not, intro h, assumption end /-- Tactic for setting up proof by induction over preforms. -/ meta def preform.induce (t : tactic unit := tactic.skip) : tactic unit := `[ intro p, induction p with t s t s p ih p q ihp ihq p q ihp ihq; t] end int end omega
31d714426115c3f4c42889f2cfc42a086fa368ac
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/univIssue.lean
7991a2158d22cf273955b9ec116ff07d326db7ea
[ "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
307
lean
universe u v @[inline] def ex1 {σ : Type u} {m : Type u → Type v} [Functor m] {α : Type u} (x : StateT σ m α) (s : σ) : m α := Functor.map Prod.fst (x s) @[inline] def ex2 {σ : Type u} {m : Type u → Type v} [Functor m] {α : Type u} (x : StateT σ m α) (s : σ) : m α := Prod.fst <$> x s
5f5fdc8e1460f1666609792bc36b76849c8cdd23
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/list/defs.lean
6c8c0a3cf96a044433396c8b9c52cd8a3a09decb
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
41,499
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.option.defs import logic.basic import tactic.cache import data.rbmap.basic import data.rbtree.default_lt /-! ## Definitions on lists This file contains various definitions on lists. It does not contain proofs about these definitions, those are contained in other files in `data/list` -/ namespace list open function nat universes u v w x variables {α β γ δ ε ζ : Type*} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) /-- An auxiliary function for `split_on_p`. -/ def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a /-- `head' xs` returns the first element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "default" `nth` function: returns `d` instead of `none` in the case that the index is out of bounds. -/ def nthd (d : α) : Π (l : list α) (n : ℕ), α | [] _ := d | (x::xs) 0 := x | (x::xs) (n + 1) := nthd xs n /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ def inth [h : inhabited α] (l : list α) (n : nat) : α := nthd default l n /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) /-- Apply `f` to the last element of `l`, if it exists. -/ @[simp] def modify_last (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: modify_last xs /-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l` `insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/ def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] /-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l` elements `default`. -/ def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l /-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')` then `scanr f b l = b' :: l'` -/ def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 /-- Sum of a list. sum [a, b, c] = ((0 + a) + b) + c -/ -- Later this will be tagged with `to_additive`, but this can't be done yet because of import -- dependencies. def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0 /-- The alternating sum of a list. -/ def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G | [] := 0 | (g :: []) := g | (g :: h :: t) := g + -h + alternating_sum t /-- The alternating product of a list. -/ def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G | [] := 1 | (g :: []) := g | (g :: h :: t) := g * h⁻¹ * alternating_prod t /-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f` whilst partitioning the result it into a pair of lists, `list β × list γ`, partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list. `partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/ def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l /-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and fails otherwise. -/ def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α := list.mfirst $ λ a, tac a $> a /-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in `l`. This is a monadic version of `list.find`. -/ def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) : list α → m (option α) | [] := pure none | (x :: xs) := do ⟨px⟩ ← p x, if px then pure (some x) else mbfind' xs section variables {m : Type → Type v} [monad m] /-- A variant of `mbfind'` with more restrictive universe levels. -/ def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) := xs.mbfind' (functor.map ulift.up ∘ p) /-- `many p as` returns true iff `p` returns true for any element of `l`. `many` short-circuits, so if `p` returns true for any element of `l`, later elements are not checked. This is a monadic version of `list.any`. -/ -- Implementing this via `mbfind` would give us less universe polymorphism. def many {α : Type u} (p : α → m bool) : list α → m bool | [] := pure false | (x :: xs) := do px ← p x, if px then pure tt else many xs /-- `mall p as` returns true iff `p` returns true for all elements of `l`. `mall` short-circuits, so if `p` returns false for any element of `l`, later elements are not checked. This is a monadic version of `list.all`. -/ def mall {α : Type u} (p : α → m bool) (as : list α) : m bool := bnot <$> many (λ a, bnot <$> p a) as /-- `mbor xs` runs the actions in `xs`, returning true if any of them returns true. `mbor` short-circuits, so if an action returns true, later actions are not run. This is a monadic version of `list.bor`. -/ def mbor : list (m bool) → m bool := many id /-- `mband xs` runs the actions in `xs`, returning true if all of them return true. `mband` short-circuits, so if an action returns false, later actions are not run. This is a monadic version of `list.band`. -/ def mband : list (m bool) → m bool := mall id end /-- Auxiliary definition for `foldl_with_index`. -/ def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α | _ a [] := a | i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l /-- Fold a list from left to right as with `foldl`, but the combining function also receives each element's index. -/ def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α := foldl_with_index_aux f 0 a l /-- Auxiliary definition for `foldr_with_index`. -/ def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β | _ b [] := b | i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l) /-- Fold a list from right to left as with `foldr`, but the combining function also receives each element's index. -/ def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β := foldr_with_index_aux f 0 b l /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := foldr_with_index (λ i a is, if p a then i :: is else is) [] l /-- Returns the elements of `l` that satisfy `p` together with their indexes in `l`. The returned list is ordered by index. -/ def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) := foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l /-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example: ``` indexes_of a [a, b, a, a] = [0, 2, 3] ``` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) section mfold_with_index variables {m : Type v → Type w} [monad m] /-- Monadic variant of `foldl_with_index`. -/ def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β := as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b) /-- Monadic variant of `foldr_with_index`. -/ def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β := as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b) end mfold_with_index section mmap_with_index variables {m : Type v → Type w} [applicative m] /-- Auxiliary definition for `mmap_with_index`. -/ def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β) | _ [] := pure [] | i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as /-- Applicative variant of `map_with_index`. -/ def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) := mmap_with_index_aux f 0 as /-- Auxiliary definition for `mmap_with_index'`. -/ def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit | _ [] := pure ⟨⟩ | i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as /-- A variant of `mmap_with_index` specialised to applicative actions which return `unit`. -/ def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit := mmap_with_index'_aux f 0 as end mmap_with_index /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} /-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied. -/ inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ /-- `l.all₂ p` 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 all₂ (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ all₂ l /-- Auxiliary definition used to define `transpose`. `transpose_aux l L` takes each element of `l` and appends it to the start of each element of `L`. `transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations /-- An auxiliary function for defining `permutations`. `permutations_aux2 t ts r ys f` is equal to `(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`. permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id = ([1, 2, 3, 4, 5, 6], [[10, 1, 2, 3, 4, 5, 6], [1, 10, 2, 3, 4, 5, 6], [1, 2, 10, 3, 4, 5, 6]]) -/ def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas /-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for `l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/ @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } /-- An auxiliary function for defining `permutations`. `permutations_aux ts is` is the set of all permutations of `is ++ ts` that do not fix `ts`. -/ def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] /-- `permutations'_aux t ts` inserts `t` into every position in `ts`, including the last. This function is intended for use in specifications, so it is simpler than `permutations_aux2`, which plays roughly the same role in `permutations`. Note that `(permutations_aux2 t [] [] ts id).2` is similar to this function, but skips the last position: permutations'_aux 10 [1, 2, 3] = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]] (permutations_aux2 10 [] [] [1, 2, 3] id).2 = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/ @[simp] def permutations'_aux (t : α) : list α → list (list α) | [] := [[t]] | (y::ys) := (t :: y :: ys) :: (permutations'_aux ys).map (cons y) /-- List of all permutations of `l`. This version of `permutations` is less efficient but has simpler definitional equations. The permutations are in a different order, but are equal up to permutation, as shown by `list.permutations_perm_permutations'`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]] -/ @[simp] def permutations' : list α → list (list α) | [] := [[]] | (t::ts) := (permutations' ts).bind $ permutations'_aux t end permutations /-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/ def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l /-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate `p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/ def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') /-- `revzip l` returns a list of pairs of the elements of `l` paired with the elements of `l` in reverse order. `revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]` -/ def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr ` ×ˢ `:82 := list.product /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a /-- Auxliary definition used to define `of_fn`. `of_fn_aux f m h l` returns the first `m` elements of `of_fn f` appended to `l` -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) /-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i` `of_fun f = [f 0, f 1, ... , f(n - 1)]` -/ def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] /-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/ def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : i < n then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] pairwise.nil instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `dedup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] chain.nil instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `dedup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. dedup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def dedup [decidable_eq α] : list α → list α := pw_filter (≠) /-- Greedily create a sublist of `a :: l` such that, for every two adjacent elements `a, b`, `R a b` holds. Mostly used with ≠; for example, `destutter' (≠) 1 [2, 2, 1, 1] = [1, 2, 1]`, `destutter' (≠) 1, [2, 3, 3] = [1, 2, 3]`, `destutter' (<) 1 [2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/ def destutter' (R : α → α → Prop) [decidable_rel R] : α → list α → list α | a [] := [a] | a (h :: l) := if R a h then a :: destutter' h l else destutter' a l /-- Greedily create a sublist of `l` such that, for every two adjacent elements `a, b ∈ l`, `R a b` holds. Mostly used with ≠; for example, `destutter (≠) [1, 2, 2, 1, 1] = [1, 2, 1]`, `destutter (≠) [1, 2, 3, 3] = [1, 2, 3]`, `destutter (<) [1, 2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/ def destutter (R : α → α → Prop) [decidable_rel R] : list α → list α | (h :: l) := destutter' R h l | [] := [] /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n /-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/ def reduce_option {α} : list (option α) → list α := list.filter_map id /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise -/ @[simp] def ilast' {α} : α → list α → α | a [] := a | a (b::l) := ilast' b l /-- `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def last' {α} : list α → option α | [] := none | [a] := some a | (b::l) := last' l /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns both `a` and proofs of `a ∈ l` and `p a`. -/ def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns `a : α`, and properties are given by `choose_mem` and `choose_property`. -/ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose /-- Filters and maps elements of a list -/ def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) : list α → m (list β) | [] := return [] | (h :: t) := do b ← f h, t' ← t.mmap_filter, return $ match b with none := t' | (some x) := x::t' end /-- `mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list `[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`. -/ def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β) | [] := return [] | (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t /-- `mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order, `f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`. -/ def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit | [] := return () | (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : list α → F (list β) | [] := pure [] | (x :: xs) := list.cons <$> f x <*> traverse xs /-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`. If `l₁` is not a prefix of `l`, returns `none` -/ def get_rest [decidable_eq α] : list α → list α → option (list α) | l [] := some l | [] _ := none | (x::l) (y::l₁) := if x = y then get_rest l l₁ else none /-- `list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`. -/ def slice {α} : ℕ → ℕ → list α → list α | 0 n xs := xs.drop n | (succ n) m [] := [] | (succ n) m (x :: xs) := x :: slice n m xs /-- Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. Returns the results of the `f` applications and the remaining `bs`. ``` map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b']) ``` -/ @[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β) | [] bs := ([], bs) | (a :: as) [] := ((a :: as).map (λ a, f a none), []) | (a :: as) (b :: bs) := let rec := map₂_left' as bs in (f a (some b) :: rec.fst, rec.snd) /-- Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. Returns the results of the `f` applications and the remaining `as`. ``` map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2]) ``` -/ def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) := map₂_left' (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`. ``` zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b']) zip_left' = map₂_left' prod.mk ``` -/ def zip_left' : list α → list β → list (α × option β) × list β := map₂_left' prod.mk /-- Right-biased version of `list.zip`. `zip_right' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. Also returns the remaining `as`. ``` zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2]) zip_right' = map₂_right' prod.mk ``` -/ def zip_right' : list α → list β → list (option α × β) × list α := map₂_right' prod.mk /-- Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. ``` map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)] map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')] map₂_left f as bs = (map₂_left' f as bs).fst ``` -/ @[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ | [] _ := [] | (a :: as) [] := (a :: as).map (λ a, f a none) | (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs /-- Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. ``` map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')] map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] map₂_right f as bs = (map₂_right' f as bs).fst ``` -/ def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) : list γ := map₂_left (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. ``` zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)] zip_left [1] ['a', 'b'] = [(1, some 'a')] zip_left = map₂_left prod.mk ``` -/ def zip_left : list α → list β → list (α × option β) := map₂_left prod.mk /-- Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. ``` zip_right [1, 2] ['a'] = [(some 1, 'a')] zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] zip_right = map₂_right prod.mk ``` -/ def zip_right : list α → list β → list (option α × β) := map₂_right prod.mk /-- If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise it returns `none`. ``` all_some [some 1, some 2] = some [1, 2] all_some [some 1, none ] = none ``` -/ def all_some : list (option α) → option (list α) | [] := some [] | (some a :: as) := cons a <$> all_some as | (none :: as) := none /-- `fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there are not enough `ys` to replace all the `none`s, the remaining `none`s are dropped from `xs`. ``` fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3] ``` -/ def fill_nones {α} : list (option α) → list α → list α | [] _ := [] | (some a :: as) as' := a :: fill_nones as as' | (none :: as) [] := as.reduce_option | (none :: as) (a :: as') := a :: fill_nones as as' /-- `take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`, it first takes the `n₁` initial elements from `as`, then the next `n₂` ones, etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining elements of `as`. If `as` does not have at least as many elements as the sum of the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements. ``` take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e']) take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], []) ``` -/ def take_list {α} : list α → list ℕ → list (list α) × list α | xs [] := ([], xs) | xs (n :: ns) := let ⟨xs₁, xs₂⟩ := xs.split_at n in let ⟨xss, rest⟩ := take_list xs₂ ns in (xs₁ :: xss, rest) /-- `to_rbmap as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ def to_rbmap {α : Type*} : list α → rbmap ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α) /-- Auxliary definition used to define `to_chunks`. `to_chunks_aux n xs i` returns `(xs.take i, (xs.drop i).to_chunks (n+1))`, that is, the first `i` elements of `xs`, and the remaining elements chunked into sublists of length `n+1`. -/ def to_chunks_aux {α} (n : ℕ) : list α → ℕ → list α × list (list α) | [] i := ([], []) | (x::xs) 0 := let (l, L) := to_chunks_aux xs n in ([], (x::l)::L) | (x::xs) (i+1) := let (l, L) := to_chunks_aux xs i in (x::l, L) /-- `xs.to_chunks n` splits the list into sublists of size at most `n`, such that `(xs.to_chunks n).join = xs`. ``` [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]] ``` -/ def to_chunks {α} : ℕ → list α → list (list α) | _ [] := [] | 0 xs := [xs] | (n+1) (x::xs) := let (l, L) := to_chunks_aux n xs n in (x::l)::L /-- Asynchronous version of `list.map`. -/ meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β := ((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get /-! We add some n-ary versions of `list.zip_with` for functions with more than two arguments. These can also be written in terms of `list.zip` or `list.zip_with`. For example, `zip_with3 f xs ys zs` could also be written as `zip_with id (zip_with f xs ys) zs` or as `(zip xs $ zip ys zs).map $ λ ⟨x, y, z⟩, f x y z`. -/ /-- Ternary version of `list.zip_with`. -/ def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ | (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs | _ _ _ := [] /-- Quaternary version of `list.zip_with`. -/ def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε | (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us | _ _ _ _ := [] /-- Quinary version of `list.zip_with`. -/ def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ | (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs | _ _ _ _ _ := [] /-- Given a starting list `old`, a list of booleans and a replacement list `new`, read the items in `old` in succession and either replace them with the next element of `new` or not, according as to whether the corresponding boolean is `tt` or `ff`. -/ def replace_if : list α → list bool → list α → list α | l _ [] := l | [] _ _ := [] | l [] _ := l | (n::ns) (tf::bs) e@(c::cs) := if tf then c :: ns.replace_if bs cs else n :: ns.replace_if bs e /-- An auxiliary function for `list.map_with_prefix_suffix`. -/ def map_with_prefix_suffix_aux {α β} (f : list α → α → list α → β) : list α → list α → list β | prev [] := [] | prev (h::t) := f prev h t :: map_with_prefix_suffix_aux (prev.concat h) t /-- `list.map_with_prefix_suffix f l` maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f pref a suff`. Example: if `f : list ℕ → ℕ → list ℕ → β`, `list.map_with_prefix_suffix f [1, 2, 3]` will produce the list `[f [] 1 [2, 3], f [1] 2 [3], f [1, 2] 3 []]`. -/ def map_with_prefix_suffix {α β} (f : list α → α → list α → β) (l : list α) : list β := map_with_prefix_suffix_aux f [] l /-- `list.map_with_complement f l` is a variant of `list.map_with_prefix_suffix` that maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f a (pref ++ suff)`, i.e., the list input to `f` is `l` with `a` removed. Example: if `f : ℕ → list ℕ → β`, `list.map_with_complement f [1, 2, 3]` will produce the list `[f 1 [2, 3], f 2 [1, 3], f 3 [1, 2]]`. -/ def map_with_complement {α β} (f : α → list α → β) : list α → list β := map_with_prefix_suffix $ λ pref a suff, f a (pref ++ suff) end list
59efde0e870849a6e94d418c145386b5c14de623
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/integral_domain.lean
8c9618b8c8c800253c011d68b3590bb749765ee8
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,261
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes -/ import data.fintype.card import data.polynomial.ring_division import group_theory.specific_groups.cyclic import algebra.geom_sum /-! # Integral domains Assorted theorems about integral domains. ## Main theorems * `is_cyclic_of_subgroup_is_domain`: A finite subgroup of the units of an integral domain is cyclic. * `fintype.field_of_domain`: A finite integral domain is a field. ## TODO Prove Wedderburn's little theorem, which shows that all finite division rings are actually fields. ## Tags integral domain, finite integral domain, finite field -/ section open finset polynomial function open_locale big_operators nat section cancel_monoid_with_zero -- There doesn't seem to be a better home for these right now variables {M : Type*} [cancel_monoid_with_zero M] [fintype M] lemma mul_right_bijective_of_fintype₀ {a : M} (ha : a ≠ 0) : bijective (λ b, a * b) := fintype.injective_iff_bijective.1 $ mul_right_injective₀ ha lemma mul_left_bijective_of_fintype₀ {a : M} (ha : a ≠ 0) : bijective (λ b, b * a) := fintype.injective_iff_bijective.1 $ mul_left_injective₀ ha /-- Every finite nontrivial cancel_monoid_with_zero is a group_with_zero. -/ def fintype.group_with_zero_of_cancel (M : Type*) [cancel_monoid_with_zero M] [decidable_eq M] [fintype M] [nontrivial M] : group_with_zero M := { inv := λ a, if h : a = 0 then 0 else fintype.bij_inv (mul_right_bijective_of_fintype₀ h) 1, mul_inv_cancel := λ a ha, by { simp [has_inv.inv, dif_neg ha], exact fintype.right_inverse_bij_inv _ _ }, inv_zero := by { simp [has_inv.inv, dif_pos rfl] }, ..‹nontrivial M›, ..‹cancel_monoid_with_zero M› } end cancel_monoid_with_zero variables {R : Type*} {G : Type*} section ring variables [ring R] [is_domain R] [fintype R] /-- Every finite domain is a division ring. TODO: Prove Wedderburn's little theorem, which shows a finite domain is in fact commutative, hence a field. -/ def fintype.division_ring_of_is_domain (R : Type*) [ring R] [is_domain R] [decidable_eq R] [fintype R] : division_ring R := { ..show group_with_zero R, from fintype.group_with_zero_of_cancel R, ..‹ring R› } /-- Every finite commutative domain is a field. TODO: Prove Wedderburn's little theorem, which shows a finite domain is automatically commutative, dropping one assumption from this theorem. -/ def fintype.field_of_domain (R) [comm_ring R] [is_domain R] [decidable_eq R] [fintype R] : field R := { .. fintype.group_with_zero_of_cancel R, .. ‹comm_ring R› } lemma fintype.is_field_of_domain (R) [comm_ring R] [is_domain R] [fintype R] : is_field R := @field.to_is_field R $ @@fintype.field_of_domain R _ _ (classical.dec_eq R) _ end ring variables [comm_ring R] [is_domain R] [group G] [fintype G] lemma card_nth_roots_subgroup_units (f : G →* R) (hf : injective f) {n : ℕ} (hn : 0 < n) (g₀ : G) : ({g ∈ univ | g ^ n = g₀} : finset G).card ≤ (nth_roots n (f g₀)).card := begin haveI : decidable_eq R := classical.dec_eq _, refine le_trans _ (nth_roots n (f g₀)).to_finset_card_le, apply card_le_card_of_inj_on f, { intros g hg, rw [sep_def, mem_filter] at hg, rw [multiset.mem_to_finset, mem_nth_roots hn, ← f.map_pow, hg.2] }, { intros, apply hf, assumption } end /-- A finite subgroup of the unit group of an integral domain is cyclic. -/ lemma is_cyclic_of_subgroup_is_domain (f : G →* R) (hf : injective f) : is_cyclic G := begin classical, apply is_cyclic_of_card_pow_eq_one_le, intros n hn, convert (le_trans (card_nth_roots_subgroup_units f hf hn 1) (card_nth_roots n (f 1))) end /-- The unit group of a finite integral domain is cyclic. To support `ℤˣ` and other infinite monoids with finite groups of units, this requires only `fintype Rˣ` rather than deducing it from `fintype R`. -/ instance [fintype Rˣ] : is_cyclic Rˣ := is_cyclic_of_subgroup_is_domain (units.coe_hom R) $ units.ext section variables (S : subgroup Rˣ) [fintype S] /-- A finite subgroup of the units of an integral domain is cyclic. -/ instance subgroup_units_cyclic : is_cyclic S := begin refine is_cyclic_of_subgroup_is_domain ⟨(coe : S → R), _, _⟩ (units.ext.comp subtype.val_injective), { simp }, { intros, simp }, end end lemma card_fiber_eq_of_mem_range {H : Type*} [group H] [decidable_eq H] (f : G →* H) {x y : H} (hx : x ∈ set.range f) (hy : y ∈ set.range f) : (univ.filter $ λ g, f g = x).card = (univ.filter $ λ g, f g = y).card := begin rcases hx with ⟨x, rfl⟩, rcases hy with ⟨y, rfl⟩, refine card_congr (λ g _, g * x⁻¹ * y) _ _ (λ g hg, ⟨g * y⁻¹ * x, _⟩), { simp only [mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, monoid_hom.map_mul_inv, and_self, forall_true_iff] {contextual := tt} }, { simp only [mul_left_inj, imp_self, forall_2_true_iff], }, { simp only [true_and, mem_filter, mem_univ] at hg, simp only [hg, mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, exists_prop_of_true, monoid_hom.map_mul_inv, and_self, mul_inv_cancel_right, inv_mul_cancel_right], } end /-- In an integral domain, a sum indexed by a nontrivial homomorphism from a finite group is zero. -/ lemma sum_hom_units_eq_zero (f : G →* R) (hf : f ≠ 1) : ∑ g : G, f g = 0 := begin classical, obtain ⟨x, hx⟩ : ∃ x : monoid_hom.range f.to_hom_units, ∀ y : monoid_hom.range f.to_hom_units, y ∈ submonoid.powers x, from is_cyclic.exists_monoid_generator, have hx1 : x ≠ 1, { rintro rfl, apply hf, ext g, rw [monoid_hom.one_apply], cases hx ⟨f.to_hom_units g, g, rfl⟩ with n hn, rwa [subtype.ext_iff, units.ext_iff, subtype.coe_mk, monoid_hom.coe_to_hom_units, one_pow, eq_comm] at hn, }, replace hx1 : (x : R) - 1 ≠ 0, from λ h, hx1 (subtype.eq (units.ext (sub_eq_zero.1 h))), let c := (univ.filter (λ g, f.to_hom_units g = 1)).card, calc ∑ g : G, f g = ∑ g : G, f.to_hom_units g : rfl ... = ∑ u : Rˣ in univ.image f.to_hom_units, (univ.filter (λ g, f.to_hom_units g = u)).card • u : sum_comp (coe : Rˣ → R) f.to_hom_units ... = ∑ u : Rˣ in univ.image f.to_hom_units, c • u : sum_congr rfl (λ u hu, congr_arg2 _ _ rfl) -- remaining goal 1, proven below ... = ∑ b : monoid_hom.range f.to_hom_units, c • ↑b : finset.sum_subtype _ (by simp ) _ ... = c • ∑ b : monoid_hom.range f.to_hom_units, (b : R) : smul_sum.symm ... = c • 0 : congr_arg2 _ rfl _ -- remaining goal 2, proven below ... = 0 : smul_zero _, { -- remaining goal 1 show (univ.filter (λ (g : G), f.to_hom_units g = u)).card = c, apply card_fiber_eq_of_mem_range f.to_hom_units, { simpa only [mem_image, mem_univ, exists_prop_of_true, set.mem_range] using hu, }, { exact ⟨1, f.to_hom_units.map_one⟩ } }, -- remaining goal 2 show ∑ b : monoid_hom.range f.to_hom_units, (b : R) = 0, calc ∑ b : monoid_hom.range f.to_hom_units, (b : R) = ∑ n in range (order_of x), x ^ n : eq.symm $ sum_bij (λ n _, x ^ n) (by simp only [mem_univ, forall_true_iff]) (by simp only [implies_true_iff, eq_self_iff_true, subgroup.coe_pow, units.coe_pow, coe_coe]) (λ m n hm hn, pow_injective_of_lt_order_of _ (by simpa only [mem_range] using hm) (by simpa only [mem_range] using hn)) (λ b hb, let ⟨n, hn⟩ := hx b in ⟨n % order_of x, mem_range.2 (nat.mod_lt _ (order_of_pos _)), by rw [← pow_eq_mod_order_of, hn]⟩) ... = 0 : _, rw [← mul_left_inj' hx1, zero_mul, ← geom_sum, geom_sum_mul, coe_coe], norm_cast, simp [pow_order_of_eq_one], end /-- In an integral domain, a sum indexed by a homomorphism from a finite group is zero, unless the homomorphism is trivial, in which case the sum is equal to the cardinality of the group. -/ lemma sum_hom_units (f : G →* R) [decidable (f = 1)] : ∑ g : G, f g = if f = 1 then fintype.card G else 0 := begin split_ifs with h h, { simp [h, card_univ] }, { exact sum_hom_units_eq_zero f h } end end
9b60543f09940b66f29f512f6bbf0323389f0aa3
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/types/nat/dm_nat_test.lean
4eae03cb4ad5c5e3e1dcf0dd407693fb0ae73eac
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
337
lean
import .dm_nat open hidden def zro := dm_nat.zero def one := dm_nat.succ zro def two := dm_nat.succ one def three := dm_nat.succ (dm_nat.succ (dm_nat.succ dm_nat.zero)) def four := dm_nat.succ three def five := dm_nat.succ four -- etc #reduce one #reduce two #reduce three #reduce four #reduce successor four #reduce predecessor two
fc745e83e3823c1bb212cc4b8b9c61ffe6f2a459
97c8e5d8aca4afeebb5b335f26a492c53680efc8
/ground_zero/cubical/V.lean
f406d1f1d13f7d2ab9f1801745fe0c0e04a178c6
[]
no_license
jfrancese/lean
cf32f0d8d5520b6f0e9d3987deb95841c553c53c
06e7efaecce4093d97fb5ecc75479df2ef1dbbdb
refs/heads/master
1,587,915,151,351
1,551,012,140,000
1,551,012,140,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,367
lean
import ground_zero.cubical.path ground_zero.theorems.ua open ground_zero.HITs ground_zero.types /- V, Vproj * https://arxiv.org/abs/1712.01800 Part 6 ‘Rules’, page 66 ‘Univalence’ ua, uabeta -/ namespace ground_zero.cubical universes u v def V (i : I) {α β : Sort u} (e : α ≃ β) : Sort u := interval.rec α β (ground_zero.ua e) i def Vproj (i : I) {α β : Sort u} (e : α ≃ β) (m : α) : V i e := interval.hrec (λ i, V i e) m (e.fst m) (begin symmetry, transitivity, apply heq.inclusion, exact (ground_zero.ua.transport_rule e m)⁻¹, symmetry, apply heq.eq_subst_heq (ground_zero.ua e) end) i -- why it isn’t need to be marked as noncomputable?? def ua {α β : Sort u} (e : α ≃ β) : α ⇝ β := <i> V i e def uabeta {α β : Sort u} (e : α ≃ β) (m : α) : coe⁻¹ 0 1 (λ i, V i e) m ⇝ (e.fst m) := <i> coe⁻¹ i 1 (λ i, V i e) (Vproj i e m) def univalence.formation (α β : Sort u) := α ≃ β → α ⇝ β def univalence.intro {α β : Sort u} : univalence.formation α β := ua def univalence.elim {α β : Sort u} (p : α ⇝ β) : α ≃ β := Path.coe 0 1 (λ i, α ≃ p # i) (equiv.id α) def iso {α β : Sort u} (f : α → β) (g : β → α) (F : f ∘ g ~ id) (G : g ∘ f ~ id) : α ⇝ β := ua ⟨f, ground_zero.types.qinv.q2b f ⟨g, ⟨F, G⟩⟩⟩ end ground_zero.cubical
86b97be795f8d94c842438741495eee0e22614ce
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/types/nat/hott.hlean
48162995e8b0d097b7c2a89f7cc512eeb250faa2
[ "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
7,824
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about the natural numbers specific to HoTT -/ import .order types.pointed open is_trunc unit empty eq equiv algebra pointed namespace nat definition is_prop_le [instance] (n m : ℕ) : is_prop (n ≤ m) := begin have lem : Π{n m : ℕ} (p : n ≤ m) (q : n = m), p = q ▸ le.refl n, begin intros, cases p, { have H' : q = idp, by apply is_set.elim, cases H', reflexivity}, { cases q, exfalso, apply not_succ_le_self a} end, apply is_prop.mk, intro H1 H2, induction H2, { apply lem}, { cases H1, { exfalso, apply not_succ_le_self a}, { exact ap le.step !v_0}}, end definition is_prop_lt [instance] (n m : ℕ) : is_prop (n < m) := !is_prop_le definition le_equiv_succ_le_succ (n m : ℕ) : (n ≤ m) ≃ (succ n ≤ succ m) := equiv_of_is_prop succ_le_succ le_of_succ_le_succ definition le_succ_equiv_pred_le (n m : ℕ) : (n ≤ succ m) ≃ (pred n ≤ m) := equiv_of_is_prop pred_le_pred le_succ_of_pred_le theorem lt_by_cases_lt {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a < b) : lt.by_cases H1 H2 H3 = H1 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { esimp, exact ap H1 !is_prop.elim}, { exfalso, cases H' with H' H', apply lt.irrefl, exact H' ▸ H, exact lt.asymm H H'} end theorem lt_by_cases_eq {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a = b) : lt.by_cases H1 H2 H3 = H2 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { exfalso, apply lt.irrefl, exact H ▸ H'}, { cases H' with H' H', esimp, exact ap H2 !is_prop.elim, exfalso, apply lt.irrefl, exact H ▸ H'} end theorem lt_by_cases_ge {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a > b) : lt.by_cases H1 H2 H3 = H3 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { exfalso, exact lt.asymm H H'}, { cases H' with H' H', exfalso, apply lt.irrefl, exact H' ▸ H, esimp, exact ap H3 !is_prop.elim} end theorem lt_ge_by_cases_lt {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P) (H : n < m) : lt_ge_by_cases H1 H2 = H1 H := by apply lt_by_cases_lt theorem lt_ge_by_cases_ge {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P) (H : n ≥ m) : lt_ge_by_cases H1 H2 = H2 H := begin unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H', { exfalso, apply lt.irrefl, exact lt_of_le_of_lt H H'}, { cases H' with H' H'; all_goals (esimp; apply ap H2 !is_prop.elim)} end theorem lt_ge_by_cases_le {n m : ℕ} {P : Type} {H1 : n ≤ m → P} {H2 : n ≥ m → P} (H : n ≤ m) (Heq : Π(p : n = m), H1 (le_of_eq p) = H2 (le_of_eq p⁻¹)) : lt_ge_by_cases (λH', H1 (le_of_lt H')) H2 = H1 H := begin unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H', { esimp, apply ap H1 !is_prop.elim}, { cases H' with H' H', { esimp, induction H', esimp, symmetry, exact ap H1 !is_prop.elim ⬝ Heq idp ⬝ ap H2 !is_prop.elim}, { exfalso, apply lt.irrefl, apply lt_of_le_of_lt H H'}} end protected definition code [reducible] [unfold 1 2] : ℕ → ℕ → Type₀ | code 0 0 := unit | code 0 (succ m) := empty | code (succ n) 0 := empty | code (succ n) (succ m) := code n m protected definition refl : Πn, nat.code n n | refl 0 := star | refl (succ n) := refl n protected definition encode [unfold 3] {n m : ℕ} (p : n = m) : nat.code n m := p ▸ nat.refl n protected definition decode : Π(n m : ℕ), nat.code n m → n = m | decode 0 0 := λc, idp | decode 0 (succ l) := λc, empty.elim c _ | decode (succ k) 0 := λc, empty.elim c _ | decode (succ k) (succ l) := λc, ap succ (decode k l c) definition nat_eq_equiv (n m : ℕ) : (n = m) ≃ nat.code n m := equiv.MK nat.encode !nat.decode begin revert m, induction n, all_goals (intro m;induction m;all_goals intro c), all_goals try contradiction, induction c, reflexivity, xrewrite [↑nat.decode,-tr_compose,v_0], end begin intro p, induction p, esimp, induction n, reflexivity, rewrite [↑nat.decode,↑nat.refl,v_0] end definition pointed_nat [instance] [constructor] : pointed ℕ := pointed.mk 0 open sigma sum definition eq_even_or_eq_odd (n : ℕ) : (Σk, 2 * k = n) ⊎ (Σk, 2 * k + 1 = n) := begin induction n with n IH, { exact inl ⟨0, idp⟩}, { induction IH with H H: induction H with k p: induction p, { exact inr ⟨k, idp⟩}, { refine inl ⟨k+1, idp⟩}} end definition rec_on_even_odd {P : ℕ → Type} (n : ℕ) (H : Πk, P (2 * k)) (H2 : Πk, P (2 * k + 1)) : P n := begin cases eq_even_or_eq_odd n with v v: induction v with k p: induction p, { exact H k}, { exact H2 k} end /- this inequality comes up a couple of times when using the freudenthal suspension theorem -/ definition add_mul_le_mul_add (n m k : ℕ) : n + (succ m) * k ≤ (succ m) * (n + k) := calc n + (succ m) * k ≤ (m * n + n) + (succ m) * k : add_le_add_right !le_add_left _ ... = (succ m) * n + (succ m) * k : by rewrite -succ_mul ... = (succ m) * (n + k) : !left_distrib⁻¹ /- Some operations work only for successors. For example fin (succ n) has a 0 and a 1, but fin 0 doesn't. However, we want a bit more, because sometimes we want a zero of (fin a) where a is either - equal to a successor, but not definitionally a successor (e.g. (0 : fin (3 + n))) - definitionally equal to a successor, but not in a way that type class inference can infer. (e.g. (0 : fin 4). Note that 4 is bit0 (bit0 one), but (bit0 x) (defined as x + x), is not always a successor) To solve this we use an auxillary class `is_succ` which can solve whether a number is a successor. -/ inductive is_succ [class] : ℕ → Type := | mk : Π(n : ℕ), is_succ (succ n) attribute is_succ.mk [instance] definition is_succ_add_right [instance] (n m : ℕ) [H : is_succ m] : is_succ (n+m) := by induction H with m; constructor definition is_succ_add_left [instance] (n m : ℕ) [H : is_succ n] : is_succ (n+m) := by induction H with n; cases m with m: constructor definition is_succ_bit0 (n : ℕ) [H : is_succ n] : is_succ (bit0 n) := by exact _ -- level 2 is useful for abelian homotopy groups, which only exist at level 2 and higher inductive is_at_least_two [class] : ℕ → Type := | mk : Π(n : ℕ), is_at_least_two (succ (succ n)) attribute is_at_least_two.mk [instance] definition is_at_least_two_add_right [instance] (n m : ℕ) [H : is_at_least_two m] : is_at_least_two (n+m) := by induction H with m; constructor definition is_at_least_two_add_left [instance] (n m : ℕ) [H : is_at_least_two n] : is_at_least_two (n+m) := by induction H with n; cases m with m: try cases m with m: constructor definition is_at_least_two_add_both [instance] [priority 900] (n m : ℕ) [H : is_succ n] [K : is_succ m] : is_at_least_two (n+m) := by induction H with n; induction K with m; cases m with m: constructor definition is_at_least_two_bit0 (n : ℕ) [H : is_succ n] : is_at_least_two (bit0 n) := by exact _ definition is_at_least_two_bit1 (n : ℕ) [H : is_succ n] : is_at_least_two (bit1 n) := by exact _ end nat
84ae70f1d53b9cf1f212b11d4e3a926f27a0c4f8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/average.lean
05d85570cef2be852d7f05759cde56cdf92d25fd
[ "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
35,002
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Yaël Dillies -/ import measure_theory.integral.set_integral /-! # Integral average of a function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `measure_theory.average μ f` (notation: `⨍ x, f x ∂μ`) to be the average value of `f` with respect to measure `μ`. It is defined as `∫ x, f x ∂((μ univ)⁻¹ • μ)`, so it is equal to zero if `f` is not integrable or if `μ` is an infinite measure. If `μ` is a probability measure, then the average of any function is equal to its integral. For the average on a set, we use `⨍ x in s, f x ∂μ` (notation for `⨍ x, f x ∂(μ.restrict s)`). For average w.r.t. the volume, one can omit `∂volume`. Both have a version for the Lebesgue integral rather than Bochner. We prove several version of the first moment method: An integrable function is below/above its average on a set of positive measure. ## Implementation notes The average is defined as an integral over `(μ univ)⁻¹ • μ` so that all theorems about Bochner integrals work for the average without modifications. For theorems that require integrability of a function, we provide a convenience lemma `measure_theory.integrable.to_average`. ## Tags integral, center mass, average value -/ open ennreal measure_theory measure_theory.measure metric set filter topological_space function open_locale topology big_operators ennreal convex variables {α E F : Type*} {m0 : measurable_space α} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] [normed_add_comm_group F] [normed_space ℝ F] [complete_space F] {μ ν : measure α} {s t : set α} /-! ### Average value of a function w.r.t. a measure The (Bochner, Lebesgue) average value of a function `f` w.r.t. a measure `μ` (notation: `⨍ x, f x ∂μ`, `⨍⁻ x, f x ∂μ`) is defined as the (Bochner, Lebesgue) integral divided by the total measure, so it is equal to zero if `μ` is an infinite measure, and (typically) equal to infinity if `f` is not integrable. If `μ` is a probability measure, then the average of any function is equal to its integral. -/ namespace measure_theory section ennreal variables (μ) {f g : α → ℝ≥0∞} include m0 /-- Average value of an `ℝ≥0∞`-valued function `f` w.r.t. a measure `μ`, notation: `⨍⁻ x, f x ∂μ`. It is defined as `μ univ⁻¹ * ∫⁻ x, f x ∂μ`, so it is equal to zero if `μ` is an infinite measure. If `μ` is a probability measure, then the average of any function is equal to its integral. For the average on a set, use `⨍⁻ x in s, f x ∂μ` (defined as `⨍⁻ x, f x ∂(μ.restrict s)`). For average w.r.t. the volume, one can omit `∂volume`. -/ noncomputable def laverage (f : α → ℝ≥0∞) := ∫⁻ x, f x ∂((μ univ)⁻¹ • μ) notation `⨍⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := laverage μ r notation `⨍⁻` binders `, ` r:(scoped:60 f, laverage volume f) := r notation `⨍⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := laverage (measure.restrict μ s) r notation `⨍⁻` binders ` in ` s `, ` r:(scoped:60 f, laverage (measure.restrict volume s) f) := r @[simp] lemma laverage_zero : ⨍⁻ x, (0 : ℝ≥0∞) ∂μ = 0 := by rw [laverage, lintegral_zero] @[simp] lemma laverage_zero_measure (f : α → ℝ≥0∞) : ⨍⁻ x, f x ∂(0 : measure α) = 0 := by simp [laverage] lemma laverage_eq' (f : α → ℝ≥0∞) : ⨍⁻ x, f x ∂μ = ∫⁻ x, f x ∂((μ univ)⁻¹ • μ) := rfl lemma laverage_eq (f : α → ℝ≥0∞) : ⨍⁻ x, f x ∂μ = ∫⁻ x, f x ∂μ / μ univ := by rw [laverage_eq', lintegral_smul_measure, ennreal.div_eq_inv_mul] lemma laverage_eq_lintegral [is_probability_measure μ] (f : α → ℝ≥0∞) : ⨍⁻ x, f x ∂μ = ∫⁻ x, f x ∂μ := by rw [laverage, measure_univ, inv_one, one_smul] @[simp] lemma measure_mul_laverage [is_finite_measure μ] (f : α → ℝ≥0∞) : μ univ * ⨍⁻ x, f x ∂μ = ∫⁻ x, f x ∂μ := begin cases eq_or_ne μ 0 with hμ hμ, { rw [hμ, lintegral_zero_measure, laverage_zero_measure, mul_zero] }, { rw [laverage_eq, ennreal.mul_div_cancel' (measure_univ_ne_zero.2 hμ) (measure_ne_top _ _)] } end lemma set_laverage_eq (f : α → ℝ≥0∞) (s : set α) : ⨍⁻ x in s, f x ∂μ = ∫⁻ x in s, f x ∂μ / μ s := by rw [laverage_eq, restrict_apply_univ] lemma set_laverage_eq' (f : α → ℝ≥0∞) (s : set α) : ⨍⁻ x in s, f x ∂μ = ∫⁻ x, f x ∂((μ s)⁻¹ • μ.restrict s) := by simp only [laverage_eq', restrict_apply_univ] variable {μ} lemma laverage_congr {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) : ⨍⁻ x, f x ∂μ = ⨍⁻ x, g x ∂μ := by simp only [laverage_eq, lintegral_congr_ae h] lemma set_laverage_congr (h : s =ᵐ[μ] t) : ⨍⁻ x in s, f x ∂μ = ⨍⁻ x in t, f x ∂μ := by simp only [set_laverage_eq, set_lintegral_congr h, measure_congr h] lemma set_laverage_congr_fun (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ⨍⁻ x in s, f x ∂μ = ⨍⁻ x in s, g x ∂μ := by simp only [laverage_eq, set_lintegral_congr_fun hs h] lemma laverage_lt_top (hf : ∫⁻ x, f x ∂μ ≠ ∞) : ⨍⁻ x, f x ∂μ < ∞ := begin obtain rfl | hμ := eq_or_ne μ 0, { simp }, { rw laverage_eq, exact div_lt_top hf (measure_univ_ne_zero.2 hμ) } end lemma set_laverage_lt_top : ∫⁻ x in s, f x ∂μ ≠ ∞ → ⨍⁻ x in s, f x ∂μ < ∞ := laverage_lt_top lemma laverage_add_measure : ⨍⁻ x, f x ∂(μ + ν) = μ univ / (μ univ + ν univ) * ⨍⁻ x, f x ∂μ + ν univ / (μ univ + ν univ) * ⨍⁻ x, f x ∂ν := begin by_cases hμ : is_finite_measure μ, swap, { rw not_is_finite_measure_iff at hμ, simp [laverage_eq, hμ] }, by_cases hν : is_finite_measure ν, swap, { rw not_is_finite_measure_iff at hν, simp [laverage_eq, hν] }, haveI := hμ, haveI := hν, simp only [←ennreal.mul_div_right_comm, measure_mul_laverage, ←ennreal.add_div, ←lintegral_add_measure, ←measure.add_apply, ←laverage_eq], end lemma measure_mul_set_laverage (f : α → ℝ≥0∞) (h : μ s ≠ ∞) : μ s * ⨍⁻ x in s, f x ∂μ = ∫⁻ x in s, f x ∂μ := by { haveI := fact.mk h.lt_top, rw [← measure_mul_laverage, restrict_apply_univ] } lemma laverage_union (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) : ⨍⁻ x in s ∪ t, f x ∂μ = μ s / (μ s + μ t) * ⨍⁻ x in s, f x ∂μ + μ t / (μ s + μ t) * ⨍⁻ x in t, f x ∂μ := by rw [restrict_union₀ hd ht, laverage_add_measure, restrict_apply_univ, restrict_apply_univ] lemma laverage_union_mem_open_segment (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hs₀ : μ s ≠ 0) (ht₀ : μ t ≠ 0) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) : ⨍⁻ x in s ∪ t, f x ∂μ ∈ open_segment ℝ≥0∞ (⨍⁻ x in s, f x ∂μ) (⨍⁻ x in t, f x ∂μ) := begin refine ⟨μ s / (μ s + μ t), μ t / (μ s + μ t), ennreal.div_pos hs₀ $ add_ne_top.2 ⟨hsμ, htμ⟩, ennreal.div_pos ht₀ $ add_ne_top.2 ⟨hsμ, htμ⟩, _, (laverage_union hd ht).symm⟩, rw [←ennreal.add_div, ennreal.div_self (add_eq_zero.not.2 $ λ h, hs₀ h.1) (add_ne_top.2 ⟨hsμ, htμ⟩)], end lemma laverage_union_mem_segment (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) : ⨍⁻ x in s ∪ t, f x ∂μ ∈ [⨍⁻ x in s, f x ∂μ -[ℝ≥0∞] ⨍⁻ x in t, f x ∂μ] := begin by_cases hs₀ : μ s = 0, { rw ← ae_eq_empty at hs₀, rw [restrict_congr_set (hs₀.union eventually_eq.rfl), empty_union], exact right_mem_segment _ _ _ }, { refine ⟨μ s / (μ s + μ t), μ t / (μ s + μ t), zero_le _, zero_le _, _, (laverage_union hd ht).symm⟩, rw [←ennreal.add_div, ennreal.div_self (add_eq_zero.not.2 $ λ h, hs₀ h.1) (add_ne_top.2 ⟨hsμ, htμ⟩)] } end lemma laverage_mem_open_segment_compl_self [is_finite_measure μ] (hs : null_measurable_set s μ) (hs₀ : μ s ≠ 0) (hsc₀ : μ sᶜ ≠ 0) : ⨍⁻ x, f x ∂μ ∈ open_segment ℝ≥0∞ (⨍⁻ x in s, f x ∂μ) (⨍⁻ x in sᶜ, f x ∂μ) := by simpa only [union_compl_self, restrict_univ] using laverage_union_mem_open_segment ae_disjoint_compl_right hs.compl hs₀ hsc₀ (measure_ne_top _ _) (measure_ne_top _ _) @[simp] lemma laverage_const (μ : measure α) [is_finite_measure μ] [h : μ.ae.ne_bot] (c : ℝ≥0∞) : ⨍⁻ x, c ∂μ = c := by simp only [laverage_eq, lintegral_const, measure.restrict_apply, measurable_set.univ, univ_inter, div_eq_mul_inv, mul_assoc, ennreal.mul_inv_cancel, mul_one, measure_ne_top μ univ, ne.def, measure_univ_ne_zero, ae_ne_bot.1 h, not_false_iff] lemma set_laverage_const (hs₀ : μ s ≠ 0) (hs : μ s ≠ ∞) (c : ℝ≥0∞) : ⨍⁻ x in s, c ∂μ = c := by simp only [set_laverage_eq, lintegral_const, measure.restrict_apply, measurable_set.univ, univ_inter, div_eq_mul_inv, mul_assoc, ennreal.mul_inv_cancel hs₀ hs, mul_one] @[simp] lemma laverage_one [is_finite_measure μ] [h : μ.ae.ne_bot] : ⨍⁻ x, (1 : ℝ≥0∞) ∂μ = 1 := laverage_const _ _ lemma set_laverage_one (hs₀ : μ s ≠ 0) (hs : μ s ≠ ∞) : ⨍⁻ x in s, (1 : ℝ≥0∞) ∂μ = 1 := set_laverage_const hs₀ hs _ @[simp] lemma lintegral_laverage (μ : measure α) [is_finite_measure μ] (f : α → ℝ≥0∞) : ∫⁻ x, ⨍⁻ a, f a ∂μ ∂μ = ∫⁻ x, f x ∂μ := begin unfreezingI { obtain rfl | hμ := eq_or_ne μ 0 }, { simp }, { rw [lintegral_const, laverage_eq, ennreal.div_mul_cancel (measure_univ_ne_zero.2 hμ) (measure_ne_top _ _)] } end lemma set_lintegral_set_laverage (μ : measure α) [is_finite_measure μ] (f : α → ℝ≥0∞) (s : set α) : ∫⁻ x in s, ⨍⁻ a in s, f a ∂μ ∂μ = ∫⁻ x in s, f x ∂μ := lintegral_laverage _ _ end ennreal section normed_add_comm_group variables (μ) {f g : α → E} include m0 /-- Average value of a function `f` w.r.t. a measure `μ`, notation: `⨍ x, f x ∂μ`. It is defined as `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ`, so it is equal to zero if `f` is not integrable or if `μ` is an infinite measure. If `μ` is a probability measure, then the average of any function is equal to its integral. For the average on a set, use `⨍ x in s, f x ∂μ` (defined as `⨍ x, f x ∂(μ.restrict s)`). For average w.r.t. the volume, one can omit `∂volume`. -/ noncomputable def average (f : α → E) := ∫ x, f x ∂((μ univ)⁻¹ • μ) notation `⨍` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := average μ r notation `⨍` binders `, ` r:(scoped:60 f, average volume f) := r notation `⨍` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := average (measure.restrict μ s) r notation `⨍` binders ` in ` s `, ` r:(scoped:60 f, average (measure.restrict volume s) f) := r @[simp] lemma average_zero : ⨍ x, (0 : E) ∂μ = 0 := by rw [average, integral_zero] @[simp] lemma average_zero_measure (f : α → E) : ⨍ x, f x ∂(0 : measure α) = 0 := by rw [average, smul_zero, integral_zero_measure] @[simp] lemma average_neg (f : α → E) : ⨍ x, -f x ∂μ = -⨍ x, f x ∂μ := integral_neg f lemma average_eq' (f : α → E) : ⨍ x, f x ∂μ = ∫ x, f x ∂((μ univ)⁻¹ • μ) := rfl lemma average_eq (f : α → E) : ⨍ x, f x ∂μ = (μ univ).to_real⁻¹ • ∫ x, f x ∂μ := by rw [average_eq', integral_smul_measure, ennreal.to_real_inv] lemma average_eq_integral [is_probability_measure μ] (f : α → E) : ⨍ x, f x ∂μ = ∫ x, f x ∂μ := by rw [average, measure_univ, inv_one, one_smul] @[simp] lemma measure_smul_average [is_finite_measure μ] (f : α → E) : (μ univ).to_real • ⨍ x, f x ∂μ = ∫ x, f x ∂μ := begin cases eq_or_ne μ 0 with hμ hμ, { rw [hμ, integral_zero_measure, average_zero_measure, smul_zero] }, { rw [average_eq, smul_inv_smul₀], refine (ennreal.to_real_pos _ $ measure_ne_top _ _).ne', rwa [ne.def, measure_univ_eq_zero] } end lemma set_average_eq (f : α → E) (s : set α) : ⨍ x in s, f x ∂μ = (μ s).to_real⁻¹ • ∫ x in s, f x ∂μ := by rw [average_eq, restrict_apply_univ] lemma set_average_eq' (f : α → E) (s : set α) : ⨍ x in s, f x ∂μ = ∫ x, f x ∂((μ s)⁻¹ • μ.restrict s) := by simp only [average_eq', restrict_apply_univ] variable {μ} lemma average_congr {f g : α → E} (h : f =ᵐ[μ] g) : ⨍ x, f x ∂μ = ⨍ x, g x ∂μ := by simp only [average_eq, integral_congr_ae h] lemma set_average_congr (h : s =ᵐ[μ] t) : ⨍ x in s, f x ∂μ = ⨍ x in t, f x ∂μ := by simp only [set_average_eq, set_integral_congr_set_ae h, measure_congr h] lemma set_average_congr_fun (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ⨍ x in s, f x ∂μ = ⨍ x in s, g x ∂μ := by simp only [average_eq, set_integral_congr_ae hs h] lemma average_add_measure [is_finite_measure μ] {ν : measure α} [is_finite_measure ν] {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ⨍ x, f x ∂(μ + ν) = ((μ univ).to_real / ((μ univ).to_real + (ν univ).to_real)) • ⨍ x, f x ∂μ + ((ν univ).to_real / ((μ univ).to_real + (ν univ).to_real)) • ⨍ x, f x ∂ν := begin simp only [div_eq_inv_mul, mul_smul, measure_smul_average, ← smul_add, ← integral_add_measure hμ hν, ← ennreal.to_real_add (measure_ne_top μ _) (measure_ne_top ν _)], rw [average_eq, measure.add_apply] end lemma average_pair {f : α → E} {g : α → F} (hfi : integrable f μ) (hgi : integrable g μ) : ⨍ x, (f x, g x) ∂μ = (⨍ x, f x ∂μ, ⨍ x, g x ∂μ) := integral_pair hfi.to_average hgi.to_average lemma measure_smul_set_average (f : α → E) {s : set α} (h : μ s ≠ ∞) : (μ s).to_real • ⨍ x in s, f x ∂μ = ∫ x in s, f x ∂μ := by { haveI := fact.mk h.lt_top, rw [← measure_smul_average, restrict_apply_univ] } lemma average_union {f : α → E} {s t : set α} (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ⨍ x in s ∪ t, f x ∂μ = ((μ s).to_real / ((μ s).to_real + (μ t).to_real)) • ⨍ x in s, f x ∂μ + ((μ t).to_real / ((μ s).to_real + (μ t).to_real)) • ⨍ x in t, f x ∂μ := begin haveI := fact.mk hsμ.lt_top, haveI := fact.mk htμ.lt_top, rw [restrict_union₀ hd ht, average_add_measure hfs hft, restrict_apply_univ, restrict_apply_univ] end lemma average_union_mem_open_segment {f : α → E} {s t : set α} (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hs₀ : μ s ≠ 0) (ht₀ : μ t ≠ 0) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ⨍ x in s ∪ t, f x ∂μ ∈ open_segment ℝ (⨍ x in s, f x ∂μ) (⨍ x in t, f x ∂μ) := begin replace hs₀ : 0 < (μ s).to_real, from ennreal.to_real_pos hs₀ hsμ, replace ht₀ : 0 < (μ t).to_real, from ennreal.to_real_pos ht₀ htμ, refine mem_open_segment_iff_div.mpr ⟨(μ s).to_real, (μ t).to_real, hs₀, ht₀, (average_union hd ht hsμ htμ hfs hft).symm⟩ end lemma average_union_mem_segment {f : α → E} {s t : set α} (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ⨍ x in s ∪ t, f x ∂μ ∈ [⨍ x in s, f x ∂μ -[ℝ] ⨍ x in t, f x ∂μ] := begin by_cases hse : μ s = 0, { rw ← ae_eq_empty at hse, rw [restrict_congr_set (hse.union eventually_eq.rfl), empty_union], exact right_mem_segment _ _ _ }, { refine mem_segment_iff_div.mpr ⟨(μ s).to_real, (μ t).to_real, ennreal.to_real_nonneg, ennreal.to_real_nonneg, _, (average_union hd ht hsμ htμ hfs hft).symm⟩, calc 0 < (μ s).to_real : ennreal.to_real_pos hse hsμ ... ≤ _ : le_add_of_nonneg_right ennreal.to_real_nonneg } end lemma average_mem_open_segment_compl_self [is_finite_measure μ] {f : α → E} {s : set α} (hs : null_measurable_set s μ) (hs₀ : μ s ≠ 0) (hsc₀ : μ sᶜ ≠ 0) (hfi : integrable f μ) : ⨍ x, f x ∂μ ∈ open_segment ℝ (⨍ x in s, f x ∂μ) (⨍ x in sᶜ, f x ∂μ) := by simpa only [union_compl_self, restrict_univ] using average_union_mem_open_segment ae_disjoint_compl_right hs.compl hs₀ hsc₀ (measure_ne_top _ _) (measure_ne_top _ _) hfi.integrable_on hfi.integrable_on @[simp] lemma average_const (μ : measure α) [is_finite_measure μ] [h : μ.ae.ne_bot] (c : E) : ⨍ x, c ∂μ = c := by simp only [average_eq, integral_const, measure.restrict_apply, measurable_set.univ, one_smul, univ_inter, smul_smul, ← ennreal.to_real_inv, ← ennreal.to_real_mul, ennreal.inv_mul_cancel, measure_ne_top μ univ, ne.def, measure_univ_eq_zero, ae_ne_bot.1 h, not_false_iff, ennreal.one_to_real] lemma set_average_const {s : set α} (hs₀ : μ s ≠ 0) (hs : μ s ≠ ∞) (c : E) : ⨍ x in s, c ∂μ = c := by simp only [set_average_eq, integral_const, measure.restrict_apply, measurable_set.univ, univ_inter, smul_smul, ← ennreal.to_real_inv, ← ennreal.to_real_mul, ennreal.inv_mul_cancel hs₀ hs, ennreal.one_to_real, one_smul] @[simp] lemma integral_average (μ : measure α) [is_finite_measure μ] (f : α → E) : ∫ x, ⨍ a, f a ∂μ ∂μ = ∫ x, f x ∂μ := begin unfreezingI { obtain rfl | hμ := eq_or_ne μ 0 }, { simp only [integral_zero_measure] }, { rw [integral_const, average_eq, smul_inv_smul₀ (to_real_ne_zero.2 ⟨measure_univ_ne_zero.2 hμ, measure_ne_top _ _⟩)] } end lemma set_integral_set_average (μ : measure α) [is_finite_measure μ] (f : α → E) (s : set α) : ∫ x in s, ⨍ a in s, f a ∂μ ∂μ = ∫ x in s, f x ∂μ := integral_average _ _ lemma integral_sub_average (μ : measure α) [is_finite_measure μ] (f : α → E) : ∫ x, f x - ⨍ a, f a ∂μ ∂μ = 0 := begin by_cases hf : integrable f μ, { rw [integral_sub hf (integrable_const _), integral_average, sub_self] }, refine integral_undef (λ h, hf _), convert h.add (integrable_const _), exact (sub_add_cancel _ _).symm, end lemma set_integral_sub_set_average (hs : μ s ≠ ∞) (f : α → E) : ∫ x in s, f x - ⨍ a in s, f a ∂μ ∂μ = 0 := by haveI haveI : fact (μ s < ∞) := ⟨lt_top_iff_ne_top.2 hs⟩; exact integral_sub_average _ _ lemma integral_average_sub [is_finite_measure μ] (hf : integrable f μ) : ∫ x, ⨍ a, f a ∂μ - f x ∂μ = 0 := by rw [integral_sub (integrable_const _) hf, integral_average, sub_self] lemma set_integral_set_average_sub (hs : μ s ≠ ∞) (hf : integrable_on f s μ) : ∫ x in s, ⨍ a in s, f a ∂μ - f x ∂μ = 0 := by haveI haveI : fact (μ s < ∞) := ⟨lt_top_iff_ne_top.2 hs⟩; exact integral_average_sub hf end normed_add_comm_group lemma of_real_average {f : α → ℝ} (hf : integrable f μ) (hf₀ : 0 ≤ᵐ[μ] f) : ennreal.of_real (⨍ x, f x ∂μ) = (∫⁻ x, ennreal.of_real (f x) ∂μ) / μ univ := begin obtain rfl | hμ := eq_or_ne μ 0, { simp }, { rw [average_eq, smul_eq_mul, ←to_real_inv, of_real_mul (to_real_nonneg), of_real_to_real (inv_ne_top.2 $ measure_univ_ne_zero.2 hμ), of_real_integral_eq_lintegral_of_real hf hf₀, ennreal.div_eq_inv_mul] } end lemma of_real_set_average {f : α → ℝ} (hf : integrable_on f s μ) (hf₀ : 0 ≤ᵐ[μ.restrict s] f) : ennreal.of_real (⨍ x in s, f x ∂μ) = (∫⁻ x in s, ennreal.of_real (f x) ∂μ) / μ s := by simpa using of_real_average hf hf₀ lemma to_real_laverage {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf' : ∀ᵐ x ∂μ, f x ≠ ∞) : (⨍⁻ x, f x ∂μ).to_real = ⨍ x, (f x).to_real ∂μ := begin obtain rfl | hμ := eq_or_ne μ 0, { simp }, { rw [average_eq, laverage_eq, smul_eq_mul, to_real_div, div_eq_inv_mul, ←integral_to_real hf (hf'.mono $ λ _, lt_top_iff_ne_top.2)] } end lemma to_real_set_laverage {f : α → ℝ≥0∞} (hf : ae_measurable f (μ.restrict s)) (hf' : ∀ᵐ x ∂(μ.restrict s), f x ≠ ∞) : (∫⁻ x in s, f x ∂μ / μ s).to_real = ⨍ x in s, (f x).to_real ∂μ := by simpa [laverage_eq] using to_real_laverage hf hf' /-! ### First moment method -/ section first_moment_real variables {N : set α} {f : α → ℝ} /-- **First moment method**. An integrable function is smaller than its mean on a set of positive measure. -/ lemma measure_le_set_average_pos (hμ : μ s ≠ 0) (hμ₁ : μ s ≠ ∞) (hf : integrable_on f s μ) : 0 < μ {x ∈ s | f x ≤ ⨍ a in s, f a ∂μ} := begin refine pos_iff_ne_zero.2 (λ H, _), replace H : (μ.restrict s) {x | f x ≤ ⨍ a in s, f a ∂μ} = 0, { rwa [restrict_apply₀, inter_comm], exact ae_strongly_measurable.null_measurable_set_le hf.1 ae_strongly_measurable_const }, haveI : is_finite_measure (μ.restrict s) := ⟨by simpa only [measure.restrict_apply, measurable_set.univ, univ_inter] using hμ₁.lt_top⟩, refine (integral_sub_average (μ.restrict s) f).not_gt _, refine (set_integral_pos_iff_support_of_nonneg_ae _ _).2 _, { refine eq_bot_mono (measure_mono (λ x hx, _)) H, simp only [pi.zero_apply, sub_nonneg, mem_compl_iff, mem_set_of_eq, not_le] at hx, exact hx.le }, { exact hf.sub (integrable_on_const.2 $ or.inr $ lt_top_iff_ne_top.2 hμ₁) }, { rwa [pos_iff_ne_zero, inter_comm, ←diff_compl, ←diff_inter_self_eq_diff, measure_diff_null], refine eq_bot_mono (measure_mono _) (measure_inter_eq_zero_of_restrict H), exact inter_subset_inter_left _ (λ a ha, (sub_eq_zero.1 $ of_not_not ha).le) } end /-- **First moment method**. An integrable function is greater than its mean on a set of positive measure. -/ lemma measure_set_average_le_pos (hμ : μ s ≠ 0) (hμ₁ : μ s ≠ ∞) (hf : integrable_on f s μ) : 0 < μ {x ∈ s | ⨍ a in s, f a ∂μ ≤ f x} := by simpa [integral_neg, neg_div] using measure_le_set_average_pos hμ hμ₁ hf.neg /-- **First moment method**. The minimum of an integrable function is smaller than its mean. -/ lemma exists_le_set_average (hμ : μ s ≠ 0) (hμ₁ : μ s ≠ ∞) (hf : integrable_on f s μ) : ∃ x ∈ s, f x ≤ ⨍ a in s, f a ∂μ := let ⟨x, hx, h⟩ := nonempty_of_measure_ne_zero (measure_le_set_average_pos hμ hμ₁ hf).ne' in ⟨x, hx, h⟩ /-- **First moment method**. The maximum of an integrable function is greater than its mean. -/ lemma exists_set_average_le (hμ : μ s ≠ 0) (hμ₁ : μ s ≠ ∞) (hf : integrable_on f s μ) : ∃ x ∈ s, ⨍ a in s, f a ∂μ ≤ f x := let ⟨x, hx, h⟩ := nonempty_of_measure_ne_zero (measure_set_average_le_pos hμ hμ₁ hf).ne' in ⟨x, hx, h⟩ section finite_measure variables [is_finite_measure μ] /-- **First moment method**. An integrable function is smaller than its mean on a set of positive measure. -/ lemma measure_le_average_pos (hμ : μ ≠ 0) (hf : integrable f μ) : 0 < μ {x | f x ≤ ⨍ a, f a ∂μ} := by simpa using measure_le_set_average_pos (measure.measure_univ_ne_zero.2 hμ) (measure_ne_top _ _) hf.integrable_on /-- **First moment method**. An integrable function is greater than its mean on a set of positive measure. -/ lemma measure_average_le_pos (hμ : μ ≠ 0) (hf : integrable f μ) : 0 < μ {x | ⨍ a, f a ∂μ ≤ f x} := by simpa using measure_set_average_le_pos (measure.measure_univ_ne_zero.2 hμ) (measure_ne_top _ _) hf.integrable_on /-- **First moment method**. The minimum of an integrable function is smaller than its mean. -/ lemma exists_le_average (hμ : μ ≠ 0) (hf : integrable f μ) : ∃ x, f x ≤ ⨍ a, f a ∂μ := let ⟨x, hx⟩ := nonempty_of_measure_ne_zero (measure_le_average_pos hμ hf).ne' in ⟨x, hx⟩ /-- **First moment method**. The maximum of an integrable function is greater than its mean. -/ lemma exists_average_le (hμ : μ ≠ 0) (hf : integrable f μ) : ∃ x, ⨍ a, f a ∂μ ≤ f x := let ⟨x, hx⟩ := nonempty_of_measure_ne_zero (measure_average_le_pos hμ hf).ne' in ⟨x, hx⟩ /-- **First moment method**. The minimum of an integrable function is smaller than its mean, while avoiding a null set. -/ lemma exists_not_mem_null_le_average (hμ : μ ≠ 0) (hf : integrable f μ) (hN : μ N = 0) : ∃ x ∉ N, f x ≤ ⨍ a, f a ∂μ := begin have := measure_le_average_pos hμ hf, rw ←measure_diff_null hN at this, obtain ⟨x, hx, hxN⟩ := nonempty_of_measure_ne_zero this.ne', exact ⟨x, hxN, hx⟩, end /-- **First moment method**. The maximum of an integrable function is greater than its mean, while avoiding a null set. -/ lemma exists_not_mem_null_average_le (hμ : μ ≠ 0) (hf : integrable f μ) (hN : μ N = 0) : ∃ x ∉ N, ⨍ a, f a ∂μ ≤ f x := by simpa [integral_neg, neg_div] using exists_not_mem_null_le_average hμ hf.neg hN end finite_measure section probability_measure variables [is_probability_measure μ] /-- **First moment method**. An integrable function is smaller than its integral on a set of positive measure. -/ lemma measure_le_integral_pos (hf : integrable f μ) : 0 < μ {x | f x ≤ ∫ a, f a ∂μ} := by simpa only [average_eq_integral] using measure_le_average_pos (is_probability_measure.ne_zero μ) hf /-- **First moment method**. An integrable function is greater than its integral on a set of positive measure. -/ lemma measure_integral_le_pos (hf : integrable f μ) : 0 < μ {x | ∫ a, f a ∂μ ≤ f x} := by simpa only [average_eq_integral] using measure_average_le_pos (is_probability_measure.ne_zero μ) hf /-- **First moment method**. The minimum of an integrable function is smaller than its integral. -/ lemma exists_le_integral (hf : integrable f μ) : ∃ x, f x ≤ ∫ a, f a ∂μ := by simpa only [average_eq_integral] using exists_le_average (is_probability_measure.ne_zero μ) hf /-- **First moment method**. The maximum of an integrable function is greater than its integral. -/ lemma exists_integral_le (hf : integrable f μ) : ∃ x, ∫ a, f a ∂μ ≤ f x := by simpa only [average_eq_integral] using exists_average_le (is_probability_measure.ne_zero μ) hf /-- **First moment method**. The minimum of an integrable function is smaller than its integral, while avoiding a null set. -/ lemma exists_not_mem_null_le_integral (hf : integrable f μ) (hN : μ N = 0) : ∃ x ∉ N, f x ≤ ∫ a, f a ∂μ := by simpa only [average_eq_integral] using exists_not_mem_null_le_average (is_probability_measure.ne_zero μ) hf hN /-- **First moment method**. The maximum of an integrable function is greater than its integral, while avoiding a null set. -/ lemma exists_not_mem_null_integral_le (hf : integrable f μ) (hN : μ N = 0) : ∃ x ∉ N, ∫ a, f a ∂μ ≤ f x := by simpa only [average_eq_integral] using exists_not_mem_null_average_le (is_probability_measure.ne_zero μ) hf hN end probability_measure end first_moment_real section first_moment_ennreal variables {N : set α} {f : α → ℝ≥0∞} /-- **First moment method**. A measurable function is smaller than its mean on a set of positive measure. -/ lemma measure_le_set_laverage_pos (hμ : μ s ≠ 0) (hμ₁ : μ s ≠ ∞) (hf : ae_measurable f (μ.restrict s)) : 0 < μ {x ∈ s | f x ≤ ⨍⁻ a in s, f a ∂μ} := begin obtain h | h := eq_or_ne (∫⁻ a in s, f a ∂μ) ∞, { simpa [mul_top, hμ₁, laverage, h, top_div_of_ne_top hμ₁, pos_iff_ne_zero] using hμ }, have := measure_le_set_average_pos hμ hμ₁ (integrable_to_real_of_lintegral_ne_top hf h), rw [←set_of_inter_eq_sep, ←measure.restrict_apply₀ (hf.ae_strongly_measurable.null_measurable_set_le ae_strongly_measurable_const)], rw [←set_of_inter_eq_sep, ←measure.restrict_apply₀ (hf.ennreal_to_real.ae_strongly_measurable.null_measurable_set_le ae_strongly_measurable_const), ←measure_diff_null (measure_eq_top_of_lintegral_ne_top hf h)] at this, refine this.trans_le (measure_mono _), rintro x ⟨hfx, hx⟩, dsimp at hfx, rwa [←to_real_laverage hf, to_real_le_to_real hx (set_laverage_lt_top h).ne] at hfx, { simp_rw [ae_iff, not_ne_iff], exact measure_eq_top_of_lintegral_ne_top hf h } end /-- **First moment method**. A measurable function is greater than its mean on a set of positive measure. -/ lemma measure_set_laverage_le_pos (hμ : μ s ≠ 0) (hs : null_measurable_set s μ) (hint : ∫⁻ a in s, f a ∂μ ≠ ∞) : 0 < μ {x ∈ s | ⨍⁻ a in s, f a ∂μ ≤ f x} := begin obtain hμ₁ | hμ₁ := eq_or_ne (μ s) ∞, { simp [set_laverage_eq, hμ₁] }, obtain ⟨g, hg, hgf, hfg⟩ := exists_measurable_le_lintegral_eq (μ.restrict s) f, have hfg' : ⨍⁻ a in s, f a ∂μ = ⨍⁻ a in s, g a ∂μ, { simp_rw [laverage_eq, hfg] }, rw hfg at hint, have := measure_set_average_le_pos hμ hμ₁ (integrable_to_real_of_lintegral_ne_top hg.ae_measurable hint), simp_rw [←set_of_inter_eq_sep, ←measure.restrict_apply₀' hs, hfg'], rw [←set_of_inter_eq_sep, ←measure.restrict_apply₀' hs, ←measure_diff_null (measure_eq_top_of_lintegral_ne_top hg.ae_measurable hint)] at this, refine this.trans_le (measure_mono _), rintro x ⟨hfx, hx⟩, dsimp at hfx, rw [←to_real_laverage hg.ae_measurable, to_real_le_to_real (set_laverage_lt_top hint).ne hx] at hfx, exact hfx.trans (hgf _), { simp_rw [ae_iff, not_ne_iff], exact measure_eq_top_of_lintegral_ne_top hg.ae_measurable hint } end /-- **First moment method**. The minimum of a measurable function is smaller than its mean. -/ lemma exists_le_set_laverage (hμ : μ s ≠ 0) (hμ₁ : μ s ≠ ∞) (hf : ae_measurable f (μ.restrict s)) : ∃ x ∈ s, f x ≤ ⨍⁻ a in s, f a ∂μ := let ⟨x, hx, h⟩ := nonempty_of_measure_ne_zero (measure_le_set_laverage_pos hμ hμ₁ hf).ne' in ⟨x, hx, h⟩ /-- **First moment method**. The maximum of a measurable function is greater than its mean. -/ lemma exists_set_laverage_le (hμ : μ s ≠ 0) (hs : null_measurable_set s μ) (hint : ∫⁻ a in s, f a ∂μ ≠ ∞) : ∃ x ∈ s, ⨍⁻ a in s, f a ∂μ ≤ f x := let ⟨x, hx, h⟩ := nonempty_of_measure_ne_zero (measure_set_laverage_le_pos hμ hs hint).ne' in ⟨x, hx, h⟩ /-- **First moment method**. A measurable function is greater than its mean on a set of positive measure. -/ lemma measure_laverage_le_pos (hμ : μ ≠ 0) (hint : ∫⁻ a, f a ∂μ ≠ ∞) : 0 < μ {x | ⨍⁻ a, f a ∂μ ≤ f x} := by simpa [hint] using @measure_set_laverage_le_pos _ _ _ _ f (measure_univ_ne_zero.2 hμ) null_measurable_set_univ /-- **First moment method**. The maximum of a measurable function is greater than its mean. -/ lemma exists_laverage_le (hμ : μ ≠ 0) (hint : ∫⁻ a, f a ∂μ ≠ ∞) : ∃ x, ⨍⁻ a, f a ∂μ ≤ f x := let ⟨x, hx⟩ := nonempty_of_measure_ne_zero (measure_laverage_le_pos hμ hint).ne' in ⟨x, hx⟩ /-- **First moment method**. The maximum of a measurable function is greater than its mean, while avoiding a null set. -/ lemma exists_not_mem_null_laverage_le (hμ : μ ≠ 0) (hint : ∫⁻ (a : α), f a ∂μ ≠ ∞) (hN : μ N = 0) : ∃ x ∉ N, ⨍⁻ a, f a ∂μ ≤ f x := begin have := measure_laverage_le_pos hμ hint, rw ←measure_diff_null hN at this, obtain ⟨x, hx, hxN⟩ := nonempty_of_measure_ne_zero this.ne', exact ⟨x, hxN, hx⟩, end section finite_measure variables [is_finite_measure μ] /-- **First moment method**. A measurable function is smaller than its mean on a set of positive measure. -/ lemma measure_le_laverage_pos (hμ : μ ≠ 0) (hf : ae_measurable f μ) : 0 < μ {x | f x ≤ ⨍⁻ a, f a ∂μ} := by simpa using measure_le_set_laverage_pos (measure_univ_ne_zero.2 hμ) (measure_ne_top _ _) hf.restrict /-- **First moment method**. The minimum of a measurable function is smaller than its mean. -/ lemma exists_le_laverage (hμ : μ ≠ 0) (hf : ae_measurable f μ) : ∃ x, f x ≤ ⨍⁻ a, f a ∂μ := let ⟨x, hx⟩ := nonempty_of_measure_ne_zero (measure_le_laverage_pos hμ hf).ne' in ⟨x, hx⟩ /-- **First moment method**. The minimum of a measurable function is smaller than its mean, while avoiding a null set. -/ lemma exists_not_mem_null_le_laverage (hμ : μ ≠ 0) (hf : ae_measurable f μ) (hN : μ N = 0) : ∃ x ∉ N, f x ≤ ⨍⁻ a, f a ∂μ := begin have := measure_le_laverage_pos hμ hf, rw ←measure_diff_null hN at this, obtain ⟨x, hx, hxN⟩ := nonempty_of_measure_ne_zero this.ne', exact ⟨x, hxN, hx⟩, end end finite_measure section probability_measure variables [is_probability_measure μ] /-- **First moment method**. A measurable function is smaller than its integral on a set of positive measure. -/ lemma measure_le_lintegral_pos (hf : ae_measurable f μ) : 0 < μ {x | f x ≤ ∫⁻ a, f a ∂μ} := by simpa only [laverage_eq_lintegral] using measure_le_laverage_pos (is_probability_measure.ne_zero μ) hf /-- **First moment method**. A measurable function is greater than its integral on a set of positive measure. -/ lemma measure_lintegral_le_pos (hint : ∫⁻ a, f a ∂μ ≠ ∞) : 0 < μ {x | ∫⁻ a, f a ∂μ ≤ f x} := by simpa only [laverage_eq_lintegral] using measure_laverage_le_pos (is_probability_measure.ne_zero μ) hint /-- **First moment method**. The minimum of a measurable function is smaller than its integral. -/ lemma exists_le_lintegral (hf : ae_measurable f μ) : ∃ x, f x ≤ ∫⁻ a, f a ∂μ := by simpa only [laverage_eq_lintegral] using exists_le_laverage (is_probability_measure.ne_zero μ) hf /-- **First moment method**. The maximum of a measurable function is greater than its integral. -/ lemma exists_lintegral_le (hint : ∫⁻ a, f a ∂μ ≠ ∞) : ∃ x, ∫⁻ a, f a ∂μ ≤ f x := by simpa only [laverage_eq_lintegral] using exists_laverage_le (is_probability_measure.ne_zero μ) hint /-- **First moment method**. The minimum of a measurable function is smaller than its integral, while avoiding a null set. -/ lemma exists_not_mem_null_le_lintegral (hf : ae_measurable f μ) (hN : μ N = 0) : ∃ x ∉ N, f x ≤ ∫⁻ a, f a ∂μ := by simpa only [laverage_eq_lintegral] using exists_not_mem_null_le_laverage (is_probability_measure.ne_zero μ) hf hN /-- **First moment method**. The maximum of a measurable function is greater than its integral, while avoiding a null set. -/ lemma exists_not_mem_null_lintegral_le (hint : ∫⁻ a, f a ∂μ ≠ ∞) (hN : μ N = 0) : ∃ x ∉ N, ∫⁻ a, f a ∂μ ≤ f x := by simpa only [laverage_eq_lintegral] using exists_not_mem_null_laverage_le (is_probability_measure.ne_zero μ) hint hN end probability_measure end first_moment_ennreal end measure_theory
2f4193f33a01ab2734b1fa6952c8db620cd1aef5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/category/Mon/adjunctions.lean
ecd1b0e332b0e025f96c6b12c02d2c6e198cd07d
[ "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
1,661
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import algebra.category.Mon.basic import algebra.category.Semigroup.basic import algebra.group.with_one /-! # Adjunctions regarding the category of monoids This file proves the adjunction between adjoining a unit to a semigroup and the forgetful functor from monoids to semigroups. ## TODO * free-forgetful adjunction for monoids * adjunctions related to commutative monoids -/ universe u open category_theory /-- The functor of adjoining a neutral element `one` to a semigroup. -/ @[to_additive "The functor of adjoining a neutral element `zero` to a semigroup", simps] def adjoin_one : Semigroup.{u} ⥤ Mon.{u} := { obj := λ S, Mon.of (with_one S), map := λ X Y, with_one.map, map_id' := λ X, with_one.map_id, map_comp' := λ X Y Z, with_one.map_comp } @[to_additive has_forget_to_AddSemigroup] instance has_forget_to_Semigroup : has_forget₂ Mon Semigroup := { forget₂ := { obj := λ M, Semigroup.of M, map := λ M N, monoid_hom.to_mul_hom }, } /-- The adjoin_one-forgetful adjunction from `Semigroup` to `Mon`.-/ @[to_additive "The adjoin_one-forgetful adjunction from `AddSemigroup` to `AddMon`"] def adjoin_one_adj : adjoin_one ⊣ forget₂ Mon.{u} Semigroup.{u} := adjunction.mk_of_hom_equiv { hom_equiv := λ S M, with_one.lift.symm, hom_equiv_naturality_left_symm' := begin intros S T M f g, ext, simp only [equiv.symm_symm, adjoin_one_map, coe_comp], simp_rw with_one.map, apply with_one.cases_on x, { refl }, { simp } end }
aee397601497b9f51c4a3b3b5c959d1933fec1ec
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/big_operators/enat_auto.lean
1ec22d7a73e650c8426468b345c75207452022fe
[]
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
688
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.basic import Mathlib.data.nat.enat import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Big operators in `enat` A simple lemma about sums in `enat`. -/ namespace finset theorem sum_nat_coe_enat {α : Type u_1} (s : finset α) (f : α → ℕ) : (finset.sum s fun (x : α) => ↑(f x)) = ↑(finset.sum s fun (x : α) => f x) := Eq.symm (add_monoid_hom.map_sum enat.coe_hom (fun (x : α) => f x) s) end Mathlib
f5f042d9a7a3b401dc2bb213d2499465ab42ecef
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/LevelDefEq.lean
0e93b64579c9ad8791e4a59a13b7e6e97cd22082
[ "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,820
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectMVars import Lean.Meta.Basic import Lean.Meta.InferType import Lean.Meta.DecLevel namespace Lean.Meta /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => visit u || visit v | _ => false where visit : Level → Bool | Level.max u v _ => visit u || visit v | u => u != lvl && lvl.occurs u /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff mvarId v <| mkMaxArgsDiff mvarId u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax' acc l else acc | l, acc => mkLevelMax' acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do assert! v.isMax let n ← mkFreshLevelMVar assignLevelMVar mvarId <| mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := do let ref ← getRef let ctx ← read trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs, ref := ref, ctx? := ctx.defEqCtx? } private def isMVarWithGreaterDepth (v : Level) (mvarId : MVarId) : MetaM Bool := match v with | Level.mvar mvarId' _ => return (← getLevelMVarDepth mvarId') > (← getLevelMVarDepth mvarId) | _ => return false mutual private partial def solve (u v : Level) : MetaM LBool := do match u, v with | Level.mvar mvarId _, _ => if (← isReadOnlyLevelMVar mvarId) then return LBool.undef else if (← getConfig).ignoreLevelMVarDepth && (← isMVarWithGreaterDepth v mvarId) then -- If both `u` and `v` are both metavariables, but depth of v is greater, then we assign `v := u`. -- This can only happen when `ignoreLevelDepth` is set to true. assignLevelMVar v.mvarId! u return LBool.true else if !u.occurs v then assignLevelMVar u.mvarId! v return LBool.true else if v.isMax && !strictOccursMax u v then solveSelfMax u.mvarId! v return LBool.true else return LBool.undef | _, Level.mvar .. => LBool.undef -- Let `solve v u` to handle this case | Level.zero _, Level.max v₁ v₂ _ => Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂) | Level.zero _, Level.imax _ v₂ _ => Bool.toLBool <$> isLevelDefEqAux levelZero v₂ | Level.zero _, Level.succ .. => return LBool.false | Level.succ u _, v => if v.isParam then return LBool.false else if u.isMVar && u.occurs v then return LBool.undef else match (← Meta.decLevel? v) with | some v => Bool.toLBool <$> isLevelDefEqAux u v | none => return LBool.undef | _, _ => return LBool.undef @[export lean_is_level_def_eq] partial def isLevelDefEqAuxImpl : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => do if lhs.getLevelOffset == rhs.getLevelOffset then return lhs.getOffset == rhs.getOffset else trace[Meta.isLevelDefEq.step] "{lhs} =?= {rhs}" let lhs' ← instantiateLevelMVars lhs let lhs' := lhs'.normalize let rhs' ← instantiateLevelMVars rhs let rhs' := rhs'.normalize if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else let r ← solve lhs rhs; if r != LBool.undef then return r == LBool.true else let r ← solve rhs lhs; if r != LBool.undef then return r == LBool.true else do let mctx ← getMCtx if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then let ctx ← read if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" Meta.throwIsDefEqStuck else return false else postponeIsLevelDefEq lhs rhs return true end builtin_initialize registerTraceClass `Meta.isLevelDefEq registerTraceClass `Meta.isLevelDefEq.step end Lean.Meta
0bdf34e3f9a3c215f9205c186b1cb6fb3218dee5
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_529.lean
8f849184a28d9fa1e1926d8ad065e2764aada538
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
233
lean
variables p q : Prop -- BEGIN example (h : p ∧ q) : q := begin have h₂ : q, from h.right, -- We have `h₂ : q` by right and elimination on `h`. show q, from h₂, -- We show `q` by reiteration on `h₂`. end -- END
ceb0c2c179601018db7d2c21619cc95b4541d9a9
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Elab/Match.lean
81394db4c75fd3e9d1ced46709bdee5fe7387daf
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
58,797
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectFVars import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Meta.SortLocalDecls import Lean.Meta.GeneralizeVars import Lean.Elab.SyntheticMVars import Lean.Elab.App import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /- This modules assumes "match"-expressions use the following syntax. ```lean def matchDiscr := leading_parser optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView where ref : Syntax patterns : Array Syntax rhs : Syntax deriving Inhabited private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx <| elabTerm newStx expectedType? private def mkUserNameFor (e : Expr) : TermElabM Name := do match e with /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/ | Expr.fvar fvarId _ => mkFreshUserName ((← getLocalDecl fvarId).userName) | _ => mkFreshBinderName /-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/ def isAuxDiscrName (n : Name) : Bool := n.hasMacroScopes && n.eraseMacroScopes == `_discr /- We treat `@x` as atomic to avoid unnecessary extra local declarations from being inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier. Thus this is kind of discriminant is quite common. Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression. This can happen due to error recovery. Example ``` example : (p ∨ p) → p := fun h => match ``` If we don't abort, the elaborator loops because we will keep trying to expand ``` match ``` into ``` let d := <Syntax.missing>; match ``` Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/ def isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do match discr with | `($x:ident) => isLocalIdent? x | `(@$x:ident) => isLocalIdent? x | _ => if discr.isMissing then throwAbortTerm else return none -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isAtomicDiscr? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then return e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else instantiateMVars localDecl.value | _ => throwErrorAt discr "unexpected discriminant" structure ElabMatchTypeAndDiscrsResult where discrs : Array Expr matchType : Expr /- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case. See `isMatchUnit?`. -/ isDep : Bool alts : Array MatchAltView private partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do let numDiscrs := discrStxs.size if matchOptType.isNone then elabDiscrs 0 #[] else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let (discrs, isDep) ← elabDiscrsWitMatchType matchType expectedType return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews } where /- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user. -/ elabDiscrsWitMatchType (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr × Bool) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType let mut isDep := false for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d trace[Elab.match] "discr #{i} {discr} : {d}" if b.hasLooseBVars then isDep := true matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" return (discrs, isDep) markIsDep (r : ElabMatchTypeAndDiscrsResult) := { r with isDep := true } /- Elaborate discriminants inferring the match-type -/ elabDiscrs (i : Nat) (discrs : Array Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do if h : i < discrStxs.size then let discrStx := discrStxs.get ⟨i, h⟩ let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let discrs := discrs.push discr let userName ← mkUserNameFor discr if discrStx[0].isNone then let mut result ← elabDiscrs (i + 1) discrs let matchTypeBody ← kabstract result.matchType discr if matchTypeBody.hasLooseBVars then result := markIsDep result return { result with matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody } else let discrs := discrs.push (← mkEqRefl discr) let result ← elabDiscrs (i + 1) discrs let result := markIsDep result let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody ← kabstract result.matchType discr let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody return { result with matchType := matchType alts := result.alts.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx } } else return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType } def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } private def getMatchGeneralizing? : Syntax → Option Bool | `(match (generalizing := true) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true | `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false | _ => none /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) => alts.filterMap fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => some { ref := alt, patterns := patterns, rhs := rhs } | _ => none | _ => #[] inductive PatternVar where | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ private def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind open Meta.Match (mkInaccessible inaccessible?) /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return mkInaccessible e /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State where found : NameSet := {} vars : Array PatternVar := #[] abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwInvalidPattern {α} : M α := throwError "invalid pattern" /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context where funId : Syntax ctorVal? : Option ConstructorVal -- It is `some`, if constructor application explicit : Bool ellipsis : Bool paramDecls : Array (Name × BinderInfo) -- parameters names and binder information paramDeclIdx : Nat := 0 namedArgs : Array NamedArg args : List Arg newArgs : Array Syntax := #[] deriving Inhabited private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) return Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.2.isExplicit else false private def getNextParam (ctx : Context) : (Name × BinderInfo) × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" if (← get).found.contains id then throwError "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } return idStx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax private def doubleQuotedNameToPattern (stx : Syntax) : TermElabM Syntax := do match stx[1].isNameLit? with | some val => nameToPattern (← resolveGlobalConstNoOverloadWithInfo stx[1] val) | none => throwIllFormedSyntax partial def collect (stx : Syntax) : M Syntax := withRef stx <| withFreshMacroScope do let k := stx.getKind if k == identKind then processId stx else if k == ``Lean.Parser.Term.app then processCtorApp stx else if k == ``Lean.Parser.Term.anonymousCtor then let elems ← stx[1].getArgs.mapSepElemsM collect return stx.setArg 1 <| mkNullNode elems else if k == ``Lean.Parser.Term.structInst then /- ``` leading_parser "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let withMod := stx[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields ← stx[2].getArgs.mapM fun p => do -- p is of the form (group (structInstField >> optional ", ")) let field := p[0] -- leading_parser structInstLVal >> " := " >> termParser let newVal ← collect field[2] let field := field.setArg 2 newVal pure <| field.setArg 0 field return stx.setArg 2 <| mkNullNode fields else if k == ``Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r } return r else if k == ``Lean.Parser.Term.paren then let arg := stx[1] if arg.isNone then return stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == ``Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t return stx.setArg 1 arg else return stx else if k == ``Lean.Parser.Term.explicitUniv then processCtor stx[0] else if k == ``Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> trailing_parser "@" >> termParser -/ let id := stx[0] discard <| processVar id let pat := stx[2] let pat ← collect pat `(_root_.namedPattern $id $pat) else if k == ``Lean.Parser.Term.binop then let lhs ← collect stx[2] let rhs ← collect stx[3] return stx.setArg 2 lhs |>.setArg 3 rhs else if k == ``Lean.Parser.Term.inaccessible then return stx else if k == strLitKind then return stx else if k == numLitKind then return stx else if k == scientificLitKind then return stx else if k == charLitKind then return stx else if k == ``Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == ``Lean.Parser.Term.doubleQuotedName then /- Similar to previous case -/ doubleQuotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern where processCtorApp (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← expandApp stx true processCtorAppCore f namedArgs args ellipsis processCtor (stx : Syntax) : M Syntax := do processCtorAppCore stx #[] #[] false /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ processId (stx : Syntax) : M Syntax := do match (← resolveId? stx "pattern" (withInfo := true)) with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => processCtor stx | some _ => if hasMatchPatternAttribute (← getEnv) fName then processCtor stx else processVar stx | none => throwCtorExpected | _ => processVar stx pushNewArg (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := do match arg with | Arg.stx stx => let stx ← if accessible then collect stx else pure stx return { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! processExplicitArg (accessible : Bool) (ctx : Context) : M Context := do match ctx.args with | [] => if ctx.ellipsis then pushNewArg accessible ctx (Arg.stx (← `(_))) else throwError "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => pushNewArg accessible { ctx with args := args } arg processImplicitArg (accessible : Bool) (ctx : Context) : M Context := do if ctx.explicit then processExplicitArg accessible ctx else pushNewArg accessible ctx (Arg.stx (← `(_))) processCtorAppContext (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.1 with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg accessible ctx arg.val processCtorAppContext ctx | none => let ctx ← match d.2 with | BinderInfo.implicit => processImplicitArg accessible ctx | BinderInfo.instImplicit => processImplicitArg accessible ctx | _ => processExplicitArg accessible ctx processCtorAppContext ctx processCtorAppCore (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId "pattern" (withInfo := true) | throwCtorExpected let fInfo ← getConstInfo fName let paramDecls ← forallTelescopeReducing fInfo.type fun xs _ => xs.mapM fun x => do let d ← getFVarLocalDecl x return (d.userName, d.binderInfo) match fInfo with | ConstantInfo.ctorInfo val => processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => if hasMatchPatternAttribute (← getEnv) fName then processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match] "collecting variables at pattern: {p}" collect p return { alt with patterns := patterns } end CollectPatternVars private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} return (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used by the main `match` elaborator, but in the precheck hook and other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM <| expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} return s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do discard <| CollectPatternVars.collect (← liftMacroM <| expandMacros pattern) let (_, s) ← collect.run {} return s.vars def getPatternVarNames (pvars : Array PatternVar) : Array Name := pvars.filterMap fun | PatternVar.localVar x => some x | _ => none open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do discrs.forM precheck for (pats, rhs) in patss.zip rhss do let vars ← try getPatternsVars pats catch | _ => return -- can happen in case of pattern antiquotations Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs | _ => throwUnsupportedSyntax /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl where /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) discard <| mkFreshExprMVarWithId mvarId type | _ => pure () k decls loop 0 #[] /- Remark: when performing dependent pattern matching, we often had to write code such as ```lean def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n := match n, xs with | _, nil => nil | _, cons a as => cons (f a) (map' f as) ``` We had to include `n` and the `_`s because the type of `xs` depends on `n`. Moreover, `nil` and `cons a as` have different types. This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure". The procedure is based on the observation that we get a type error whenenver we forget to include `_`s and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant is an indexed family, and add their indices as new discriminants. The current implementation, adds indices as they are found, and does not try to "sort" the new discriminants. If the refinement process fails, we report the original error message. -/ /- Auxiliary structure for storing an type mismatch exception when processing the pattern #`idx` of some alternative. -/ structure PatternElabException where ex : Exception patternIdx : Nat -- Discriminant that sh pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch /-- This method is part of the "discriminant refinement" procedure. It in invoked when the type of the `pattern` does not match the expected type. The expected type is based on the motive computed using the `match` discriminants. It tries to compute a path to an index of the discriminant type. For example, suppose the user has written ``` inductive Mem (a : α) : List α → Prop where | head {as} : Mem a (a::as) | tail {as} : Mem a as → Mem a (a'::as) infix:50 " ∈ " => Mem example (a b : Nat) (h : a ∈ [b]) : b = a := match h with | Mem.head => rfl ``` The motive for the match is `a ∈ [b] → b = a`, and get a type mismatch between the type of `Mem.head` and `a ∈ [b]`. This procedure return the path `[2, 1]` to the index `b`. We use it to produce the following refinement ``` example (a b : Nat) (h : a ∈ [b]) : b = a := match b, h with | _, Mem.head => rfl ``` which produces the new motive `(x : Nat) → a ∈ [x] → x = a` After this refinement step, the `match` is elaborated successfully. This method relies on the fact that the dependent pattern matcher compiler solves equations between indices of indexed inductive families. The following kinds of equations are supported by this compiler: - `x = t` - `t = x` - `ctor ... = ctor ...` where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor. Our procedure ensures that "information" is not lost, and will *not* succeed in an example such as ``` example (a b : Nat) (f : Nat → Nat) (h : f a ∈ [f b]) : f b = f a := match h with | Mem.head => rfl ``` and will not add `f b` as a new discriminant. We may add an option in the future to enable this more liberal form of refinement. -/ private partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do goType (← instantiateMVars (← inferType pattern)) expected where checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do guard d.isApp guard <| t.getAppNumArgs == d.getAppNumArgs let tFn := t.getAppFn let dFn := d.getAppFn guard <| tFn.isConst && dFn.isConst guard (← isDefEq tFn dFn) -- Visitor for inductive types goType (t d : Expr) : OptionT MetaM (List Nat) := do trace[Meta.debug] "type {t} =?= {d}" let t ← whnf t let d ← whnf d checkCompatibleApps t d matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goType tArg dArg) for i in [info.numParams : tArgs.size] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure -- Visitor for indexed families goIndex (t d : Expr) : OptionT MetaM (List Nat) := do let t ← whnfD t let d ← whnfD d if t.isFVar || d.isFVar then return [] -- Found refinement path else trace[Meta.debug] "index {t} =?= {d}" checkCompatibleApps t d matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do failure for i in [info.numParams : tArgs.size] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure private partial def eraseIndices (type : Expr) : MetaM Expr := do let type' ← whnfD type matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do let args := type'.getAppArgs let params ← args[:info.numParams].toArray.mapM eraseIndices let result := mkAppN type'.getAppFn params let resultType ← inferType result let (newIndices, _, _) ← forallMetaTelescopeReducing resultType (some (args.size - info.numParams)) return mkAppN result newIndices private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) := withReader (fun ctx => { ctx with implicitLambda := false }) do let mut patterns := #[] let mut matchType := matchType for idx in [:patternStxs.size] do let patternStx := patternStxs[idx] matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← do let s ← saveState try liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d catch ex : Exception => restoreState s match (← liftM <| commitIfNoErrors? <| withoutErrToSorry do elabTermAndSynthesize patternStx (← eraseIndices d)) with | some pattern => match ← findDiscrRefinementPath pattern d |>.run with | some path => trace[Meta.debug] "refinement path: {path}" restoreState s -- Wrap the type mismatch exception for the "discriminant refinement" feature. throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path } | none => restoreState s; throw ex | none => throw ex matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" return (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match] "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match] "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d₁ may occur after d₂ when d₂ depends on d₁. -/ sortLocalDecls decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State where found : NameSet := {} localDecls : Array LocalDecl newLocals : NameSet := {} abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get return s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => return Pattern.inaccessible val | none => let fvarId ← mkFreshId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← mkFreshBinderName let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } return Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do return (← get).localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then return Pattern.inaccessible e else markAsVisited fvarId return Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else return Pattern.inaccessible e | _ => return Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM main) | none => if e.isAppOfArity `namedPattern 3 then let p ← main <| e.getArg! 2 match e.getArg! 1 with | Expr.fvar fvarId _ => return Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then return Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless (← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwInvalidPattern e let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM main return Pattern.ctor v.name us params.toList fields.toList end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : ExceptT PatternElabException TermElabM α := do let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType id (α := TermElabM α) do let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM (instantiateMVars ·) withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType private def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match] "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match] "rhs: {rhs}" return (altLHS, rhs) /-- Collect problematic index for the "discriminant refinement feature". This method is invoked when we detect a type mismatch at a pattern #`idx` of some alternative. -/ private partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do go (← inferType discr) pathToIndex |>.run where go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do match path with | [] => return e | i::path => let e ← whnfD e guard <| e.isApp && i < e.getAppNumArgs go (e.getArg! i) path /-- "Generalize" variables that depend on the discriminants. Remarks and limitations: - If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`. Motivation: users should have control about the actual `match`-expressions in their programs. - We currently do not generalize let-decls. - We abort generalization if the new `matchType` is type incorrect. - Only discriminants that are free variables are considered during specialization. - We "generalize" by adding new discriminants and pattern variables. We do not "clear" the generalized variables, but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode. -/ private def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr × Expr × Array MatchAltView × Bool) := do let gen ← match generalizing? with | some g => pure g | _ => isProp matchType if !gen then return (discrs, matchType, altViews, false) else let ysFVarIds ← getFVarsToGeneralize discrs /- let-decls are currently being ignored by the generalizer. -/ let ysFVarIds ← ysFVarIds.filterM fun fvarId => return !(← getLocalDecl fvarId).isLet if ysFVarIds.isEmpty then return (discrs, matchType, altViews, false) else let ys := ysFVarIds.map mkFVar -- trace[Meta.debug] "ys: {ys}, discrs: {discrs}" let matchType' ← forallBoundedTelescope matchType discrs.size fun ds type => do let type ← mkForallFVars ys type let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar let type := type.replaceFVars discrs' ds' mkForallFVars ds type -- trace[Meta.debug] "matchType': {matchType'}" if (← isTypeCorrect matchType') then let discrs := discrs ++ ys let altViews ← altViews.mapM fun altView => do let patternVars ← getPatternsVars altView.patterns -- We traverse backwards because we want to keep the most recent names. -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`, -- since it is already shadowed by the second. let ysUserNames ← ys.foldrM (init := #[]) fun ys ysUserNames => do let yDecl ← getLocalDecl ys.fvarId! let mut yUserName := yDecl.userName if ysUserNames.contains yUserName then yUserName ← mkFreshUserName yUserName -- Explicitly provided pattern variables shadow `y` else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then yUserName ← mkFreshUserName yUserName return ysUserNames.push yUserName let ysIds ← ysUserNames.reverse.mapM fun n => return mkIdentFrom (← getRef) n return { altView with patterns := altView.patterns ++ ysIds } return (discrs, matchType', altViews, true) else return (discrs, matchType, altViews, true) private partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do loop discrs matchType altViews none where /- "Discriminant refinement" main loop. `first?` contains the first error message we found before updated the `discrs`. -/ loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception)) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do let s ← saveState let (discrs', matchType', altViews', refined) ← generalize discrs matchType altViews generalizing? match ← altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run with | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined) | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } => trace[Meta.debug] "pathToIndex: {toString pathToIndex}" let some index ← getIndexToInclude? discrs[patternIdx] pathToIndex | throwEx (← updateFirst first? ex) trace[Meta.debug] "index: {index}" if (← discrs.anyM fun discr => isDefEq discr index) then throwEx (← updateFirst first? ex) let first ← updateFirst first? ex s.restore let indices ← collectDeps #[index] discrs let matchType ← try updateMatchType indices matchType catch ex => throwEx first let altViews ← addWildcardPatterns indices.size altViews let discrs := indices ++ discrs loop discrs matchType altViews first throwEx {α} (p : SavedState × Exception) : TermElabM α := do p.1.restore; throw p.2 updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do match first? with | none => return (← saveState, ex) | some first => return first containsFVar (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => e.isFVar && e.fvarId! == fvarId /- Update `indices` by including any free variable `x` s.t. - Type of some `discr` depends on `x`. - Type of `x` depends on some free variable in `indices`. If we don't include these extra variables in indices, then `updateMatchType` will generate a type incorrect term. For example, suppose `discr` contains `h : @HEq α a α b`, and `indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`. `updateMatchType indices matchType` produces the type `(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect because we have `a : α`. The method `collectDeps` will include `a` into `indices`. This method does not handle dependencies among non-free variables. We rely on the type checking method `check` at `updateMatchType`. Remark: `indices : Array Expr` does not need to be an array anymore. We should cleanup this code, and use `index : Expr` instead. -/ collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do let mut s : CollectFVars.State := {} for discr in discrs do s := collectFVars s (← instantiateMVars (← inferType discr)) let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar let indicesFVar := indicesFVar.map Expr.fvarId! let mut toAdd := #[] for fvarId in s.fvarSet.toList do unless containsFVar discrs fvarId || containsFVar indices fvarId do let localDecl ← getLocalDecl fvarId let mctx ← getMCtx for indexFVarId in indicesFVar do if mctx.localDeclDependsOn localDecl indexFVarId then toAdd := toAdd.push fvarId let lctx ← getLCtx let indicesFVar := (indicesFVar ++ toAdd).qsort fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index return indicesFVar.map mkFVar ++ indicesNonFVar updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do let matchType ← indices.foldrM (init := matchType) fun index matchType => do let indexType ← inferType index let matchTypeBody ← kabstract matchType index let userName ← mkUserNameFor index return Lean.mkForall userName BinderInfo.default indexType matchTypeBody check matchType return matchType addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do let hole := mkHole (← getRef) let wildcards := mkArray num hole return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns } def mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult := Meta.Match.mkMatcher input register_builtin_option match.ignoreUnusedAlts : Bool := { defValue := false descr := "if true, do not generate error if an alternative is not used" } def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do withHeadRefOnly <| logError m!"missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 /-- If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]` Otherwise, return none. -/ private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do assert! altLHSS.length == rhss.size match altLHSS with | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] => /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/ match rhss[0] with | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b | _ => return none | _ => return none private def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let mut generalizing? := generalizing? if !matchOptType.isNone then if generalizing? == some true then throwError "the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided" generalizing? := some false let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews trace[Elab.match] "matchType: {matchType}" let (discrs, matchType, alts, refined) ← elabMatchAltViews generalizing? discrs matchType matchAlts let isDep := isDep || refined /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 /- Remark: we try to postpone before throwing an error. The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed. The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here. Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here. ``` def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) := (ps.filter fun (p : Prod _ _) => match p with | (x, y) => x == 0) ++ ps ``` When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α` However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`. -/ withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS return (discrs, matchType, altLHSS, isDep, rhss) if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then return r else let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher { matcherName, matchType, numDiscrs, lhss := altLHSS } matcherResult.addMatcher let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors altLHSS matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match] "result: {r}" return r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[2].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[3] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1] if allLocal then return none else -- We use `foundFVars` to make sure the discriminants are distinct variables. -- See: code for computing "matchType" at `elabMatchTypeAndDiscrs` let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : NameSet) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 2 discrs) | discr :: discrs => -- Recall that -- matchDiscr := leading_parser optional (ident >> ":") >> termParser let term := discr[1] let addAux : TermElabM Syntax := withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) foundFVars `(let _discr := $term; $r) match (← isAtomicDiscr? term) with | some x => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux | none => addAux return some (← loop discrs.toList #[] {}) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user return none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isAtomicDiscr? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match] "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => return expectedType | none => mkFreshTypeMVar /- ``` leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let gen? := getMatchGeneralizing? stx let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux gen? discrStxs altViews matchOptType expectedType private def isPatternVar (stx : Syntax) : TermElabM Bool := do match (← resolveId? stx "pattern") with | none => isAtomicIdent stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => return false | some _ => return !hasMatchPatternAttribute (← getEnv) fName | _ => isAtomicIdent stx | _ => isAtomicIdent stx where isAtomicIdent (stx : Syntax) : Bool := stx.isIdent && stx.getId.eraseMacroScopes.isAtomic -- leading_parser "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do match stx with | `(match $discr:term with | $y:ident => $rhs:term) => if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType? | _ => elabMatchDefault stx expectedType? where elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? builtin_initialize registerTraceClass `Elab.match -- leading_parser:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do match stx with | `(nomatch $discrExpr) => match ← isLocalIdent? discrExpr with | some _ => let expectedType ← waitExpectedType expectedType? let discr := Syntax.node ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux none #[discr] #[] mkNullNode expectedType | _ => let stxNew ← `(let _discr := $discrExpr; nomatch _discr) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax end Lean.Elab.Term
c7dc7062349ded88bf49dbcdc09e593a48bdde8f
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/zmod/basic.lean
4e4bee6c4326ec60c97567736e755d38e0e4e95e
[ "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
28,945
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq import algebra.char_p import data.nat.totient import ring_theory.ideal.operations /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat nat.modeq int /-- Negation on `fin n` -/ def has_neg (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, begin have npos : 0 < n := lt_of_le_of_lt (nat.zero_le _) a.2, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 npos, have := int.mod_lt (-(a.1 : ℤ)) h, rw [(abs_of_nonneg (int.coe_nat_nonneg n))] at this, rwa [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)] end⟩⟩ /-- Additive commutative semigroup structure on `fin (n+1)`. -/ def add_comm_semigroup (n : ℕ) : add_comm_semigroup (fin (n+1)) := { add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % (n+1) + c) ≡ (a + (b + c) % (n+1)) [MOD (n+1)], from calc ((a + b) % (n+1) + c) ≡ a + b + c [MOD (n+1)] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD (n+1)] : by rw add_assoc ... ≡ (a + (b + c) % (n+1)) [MOD (n+1)] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % (n+1) = (b + a) % (n+1), by rw add_comm), ..fin.has_add } /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ def comm_semigroup (n : ℕ) : comm_semigroup (fin (n+1)) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc ... ≡ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm), ..fin.has_mul } local attribute [instance] fin.add_comm_semigroup fin.comm_semigroup private lemma one_mul_aux (n : ℕ) (a : fin (n+1)) : (1 : fin (n+1)) * a = a := begin cases n with n, { exact subsingleton.elim _ _ }, { have h₁ : (a : ℕ) % n.succ.succ = a := nat.mod_eq_of_lt a.2, apply fin.ext, simp only [coe_mul, coe_one, h₁, one_mul], } end private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add ... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) /-- Commutative ring structure on `fin (n+1)`. -/ def comm_ring (n : ℕ) : comm_ring (fin (n+1)) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % (n+1) = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % (n+1)).to_nat + a) % (n+1) = 0, from int.coe_nat_inj begin have npos : 0 < n+1 := lt_of_le_of_lt (nat.zero_le _) ha, have hn : ((n+1) : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 npos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.has_zero, ..fin.has_one, ..fin.has_neg (n+1), ..fin.add_comm_semigroup n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type | 0 := ℤ | (n+1) := fin (n+1) namespace zmod instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n) | 0 _ := false.elim $ nat.not_lt_zero 0 ‹0 < 0› | (n+1) _ := fin.fintype (n+1) lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { exact fintype.card_fin (n+1) } end instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance has_repr : Π (n : ℕ), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ instance comm_ring : Π (n : ℕ), comm_ring (zmod n) | 0 := int.comm_ring | (n+1) := fin.comm_ring n instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩ /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val : Π {n : ℕ}, zmod n → ℕ | 0 := int.nat_abs | (n+1) := (coe : fin (n + 1) → ℕ) lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, exact fin.is_lt a end @[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0 | 0 := rfl | (n+1) := rfl lemma val_cast_nat {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n := begin casesI n, { rw [nat.mod_zero, int.nat_cast_eq_coe_nat], exact int.nat_abs_of_nat a, }, rw ← fin.of_nat_eq_coe, refl end instance (n : ℕ) : char_p (zmod n) n := { cast_eq_zero_iff := begin intro k, cases n, { simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], }, rw [fin.eq_iff_veq], show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _, rw [val_cast_nat, val_zero, nat.dvd_iff_mod_eq_zero], end } @[simp] lemma cast_self (n : ℕ) : (n : zmod n) = 0 := char_p.cast_eq_zero (zmod n) n @[simp] lemma cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 := by rw [← nat.cast_add_one, cast_self (n + 1)] section universal_property variables {n : ℕ} {R : Type*} section variables [has_zero R] [has_one R] [has_add R] [has_neg R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast : Π {n : ℕ}, zmod n → R | 0 := int.cast | (n+1) := λ i, i.val -- see Note [coercion into rings] @[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩ @[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 := by { cases n; refl } end lemma nat_cast_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) := begin assume i, casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { change fin (n + 1) at i, refine ⟨i, _⟩, rw [fin.ext_iff, fin.coe_coe_eq_self] } end lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) := begin assume i, cases n, { exact ⟨i, int.cast_id i⟩ }, { rcases nat_cast_surjective i with ⟨k, rfl⟩, refine ⟨k, _⟩, norm_cast } end lemma cast_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a := begin rcases nat_cast_surjective a with ⟨k, rfl⟩, symmetry, rw [val_cast_nat, ← sub_eq_zero, ← nat.cast_sub, char_p.cast_eq_zero_iff (zmod n) n], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end @[simp, norm_cast] lemma cast_id : ∀ n (i : zmod n), ↑i = i | 0 i := int.cast_id i | (n+1) i := cast_val i variables [ring R] @[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, refl end section char_dvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variables {n} {m : ℕ} [char_p R m] @[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 := begin casesI n, { exact int.cast_one }, show ((1 % (n+1) : ℕ) : R) = 1, cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim }, rw nat.mod_eq_of_lt, { exact nat.cast_one }, exact nat.lt_of_sub_eq_succ rfl end lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b := begin casesI n, { apply int.cast_add }, simp only [coe_coe], symmetry, erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b := begin casesI n, { apply int.cast_mul }, simp only [coe_coe], symmetry, erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/ def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R := { to_fun := coe, map_zero' := cast_zero, map_one' := cast_one h, map_add' := cast_add h, map_mul' := cast_mul h } @[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl @[simp, norm_cast] lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b := (cast_hom h R).map_sub a b @[simp, norm_cast] lemma cast_neg (h : m ∣ n) (a : zmod n) : ((-a : zmod n) : R) = -a := (cast_hom h R).map_neg a @[simp, norm_cast] lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := (cast_hom h R).map_pow a k @[simp, norm_cast] lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k := (cast_hom h R).map_nat_cast k @[simp, norm_cast] lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k := (cast_hom h R).map_int_cast k end char_dvd section char_eq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [char_p R n] @[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 := cast_one (dvd_refl _) @[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b := cast_add (dvd_refl _) a b @[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b := cast_mul (dvd_refl _) a b @[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b := cast_sub (dvd_refl _) a b @[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := cast_pow (dvd_refl _) a k @[simp, norm_cast] lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k := cast_nat_cast (dvd_refl _) k @[simp, norm_cast] lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k := cast_int_cast (dvd_refl _) k instance (R : Type*) [comm_ring R] [char_p R n] : algebra (zmod n) R := (zmod.cast_hom (dvd_refl n) R).to_algebra variables (R) lemma cast_hom_injective : function.injective (zmod.cast_hom (dvd_refl n) R) := begin rw ring_hom.injective_iff, intro x, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective x, rw [ring_hom.map_int_cast, char_p.int_cast_eq_zero_iff R n, char_p.int_cast_eq_zero_iff (zmod n) n], exact id end lemma cast_hom_bijective [fintype R] (h : fintype.card R = n) : function.bijective (zmod.cast_hom (dvd_refl n) R) := begin haveI : fact (0 < n) := begin rw [nat.pos_iff_ne_zero], unfreezingI { rintro rfl }, exact fintype.card_eq_zero_iff.mp h 0 end, rw [fintype.bijective_iff_injective_and_card, zmod.card, h, eq_self_iff_true, and_true], apply zmod.cast_hom_injective end /-- The unique ring isomorphism between `zmod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ noncomputable def ring_equiv [fintype R] (h : fintype.card R = n) : zmod n ≃+* R := ring_equiv.of_bijective _ (zmod.cast_hom_bijective R h) end char_eq end universal_property lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] := char_p.int_coe_eq_int_coe_iff (zmod c) c a b lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] := begin convert zmod.int_coe_eq_int_coe_iff a b c, simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd], end lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a := begin change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a, rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff], end lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a := begin change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a, rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff], end @[push_cast, simp] lemma cast_mod_int (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) := begin rw zmod.int_coe_eq_int_coe_iff, apply int.modeq.mod_modeq, end local attribute [semireducible] int.nonneg @[simp] lemma coe_to_nat (p : ℕ) : ∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z | (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat] | -[1+n] h := false.elim h lemma val_injective (n : ℕ) [fact (0 < n)] : function.injective (zmod.val : zmod n → ℕ) := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹_› }, assume a b h, ext, exact h end lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n := by rw [← nat.cast_one, val_cast_nat] lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 := by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt ‹1 < n› } lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { apply fin.val_add } end lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n := begin cases n, { rw nat.mod_zero, apply int.nat_abs_mul }, { apply fin.val_mul } end instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) := ⟨⟨0, 1, assume h, zero_ne_one $ calc 0 = (0 : zmod n).val : by rw val_zero ... = (1 : zmod n).val : congr_arg zmod.val h ... = 1 : val_one n ⟩⟩ /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : Π (n : ℕ), zmod n → zmod n | 0 i := int.sign i | (n+1) i := nat.gcd_a i.val (n+1) instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩ lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0 | 0 := int.sign_zero | (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0, by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl } lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * a⁻¹ = nat.gcd a.val n := begin cases n, { calc a * a⁻¹ = a * int.sign a : rfl ... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat] ... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl }, { set k := n.succ, calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [cast_self, zero_mul, add_zero] ... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) : by { push_cast, rw cast_val, refl } ... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, } end @[simp] lemma cast_mod_nat (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := begin cases n, { simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], }, { rw [fin.ext_iff, nat.modeq, ← val_cast_nat, ← val_cast_nat], exact iff.rfl, } end lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (x * x⁻¹ : zmod n) = 1 := begin rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h, rw [mul_inv_eq_gcd, val_cast_nat, h, nat.cast_one], end /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] lemma cast_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (u : zmod n).val n := begin cases n, { rcases int.units_eq_one_or u with rfl|rfl; exact dec_trivial }, apply nat.modeq.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val, have := units.ext_iff.1 (mul_right_inv u), rw [units.coe_one] at this, rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this, rw [← cast_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))], rw [units.coe_mul, val_mul, cast_mod_nat], end @[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) : (u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) := begin have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u), rw [← mul_inv_eq_gcd, nat.cast_one] at this, let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩, have h : u = u', { apply units.ext, refl }, rw h, refl end lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * a⁻¹ = 1 := begin rcases h with ⟨u, rfl⟩, rw [inv_coe_unit, u.mul_inv], end lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} := { to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩, inv_fun := λ x, unit_of_coprime x.1.val x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (cast_val _), right_inv := λ ⟨_, _⟩, by simp } section totient open_locale nat @[simp] lemma card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = φ n := calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} }, { intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_cast_nat, nat.mod_eq_of_lt hb.1], } } end end totient instance subsingleton_units : subsingleton (units (zmod 2)) := ⟨λ x y, begin cases x with x xi, cases y with y yi, revert x y xi yi, exact dec_trivial end⟩ lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val := begin haveI npos : fact (0 < n) := by { apply (nat.eq_zero_or_pos n).resolve_left, unfreezingI { rintro rfl }, simpa [fact] using hn, }, have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, { conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos]}, rw [← nat.two_mul_odd_div_two hn, two_mul, ← nat.succ_add, nat.add_sub_cancel], }, have hxn : (n : ℕ) - x.val < n, { rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self], rw ← zmod.cast_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) }, by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self, ← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.val_lt), zmod.val_cast_nat, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] } end lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha, by rwa [← h, ← not_lt, not_iff_self] at this lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] : (-1 : zmod n) ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := begin cases a, { simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] }, { simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] } end @[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0 | 0 a := int.nat_abs_eq_zero | (n+1) a := by { rw fin.ext_iff, exact iff.rfl } lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_cast_nat, nat.mod_eq_of_lt h] lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n := begin have : ((-a).val + a.val) % n = (n - a.val + a.val) % n, { rw [←val_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], }, calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt) ... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this end lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val := begin rw neg_val', by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] }, rw if_neg h, apply nat.mod_eq_of_lt, apply nat.sub_lt ‹0 < n›, contrapose! h, rwa [nat.le_zero_iff, val_eq_zero] at h, end /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs : Π {n : ℕ}, zmod n → ℤ | 0 x := x | n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n @[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refl } end @[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x | 0 x := int.cast_id x | k@(n+1) x := begin rw val_min_abs_def_pos, split_ifs, { rw [int.cast_coe_nat, cast_val] }, { rw [int.cast_sub, int.cast_coe_nat, cast_val, int.cast_coe_nat, cast_self, sub_zero], } end lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := begin rw zmod.val_min_abs_def_pos, split_ifs with h, { exact h }, have : (x.val - n : ℤ) ≤ 0, { rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, }, rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x), { rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring }, norm_cast, calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _ ... ≤ x.val : by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) } end @[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0 | 0 := by simp only [val_min_abs_def_zero] | (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero] @[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := begin cases n, { simp }, split, { simp only [val_min_abs_def_pos, int.coe_nat_succ], split_ifs with h h; assume h0, { apply val_injective, rwa [int.coe_nat_eq_zero] at h0, }, { apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } }, { rintro rfl, rw val_min_abs_zero } end lemma cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := begin have : (a.val : ℤ) - n ≤ 0, by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, }, rw [zmod.val_min_abs_def_pos], split_ifs, { rw [int.nat_abs_of_nat, cast_val] }, { rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub], rw [int.cast_coe_nat, int.cast_coe_nat, cast_self, sub_zero, cast_val], } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := begin cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], }, by_cases ha0 : a = 0, { rw [ha0, neg_zero] }, by_cases haa : -a = a, { rw [haa] }, suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, { rw [val_min_abs_def_pos, val_min_abs_def_pos], rw ← not_le at hpa, simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)], split_ifs, all_goals { rw [← int.nat_abs_neg], congr' 1, ring } }, suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a, by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this], cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { assume h, apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h), contrapose! haa, rw [← zmod.cast_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add], rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)], rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] } lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) : (q : zmod p) ≠ 0 := by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, nat.coprime_primes hp hq] end zmod namespace zmod variables (p : ℕ) [fact p.prime] private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 := begin obtain ⟨k, rfl⟩ := nat_cast_surjective a, apply coe_mul_inv_eq_one, apply nat.coprime.symm, rwa [nat.prime.coprime_iff_not_dvd ‹p.prime›, ← char_p.cast_eq_zero_iff (zmod p)] end /-- Field structure on `zmod p` if `p` is prime. -/ instance : field (zmod p) := { mul_inv_cancel := mul_inv_cancel_aux p, inv_zero := inv_zero p, .. zmod.comm_ring p, .. zmod.has_inv p, .. zmod.nontrivial p } end zmod lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g := begin ext a, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a, let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)), show φ k = ψ k, rw φ.ext_int ψ, end namespace zmod variables {n : ℕ} {R : Type*} instance subsingleton_ring_hom [semiring R] : subsingleton ((zmod n) →+* R) := ⟨ring_hom.ext_zmod⟩ instance subsingleton_ring_equiv [semiring R] : subsingleton (zmod n ≃+* R) := ⟨λ f g, by { rw ring_equiv.coe_ring_hom_inj_iff, apply ring_hom.ext_zmod _ _ }⟩ lemma ring_hom_surjective [ring R] (f : R →+* (zmod n)) : function.surjective f := begin intros k, rcases zmod.int_cast_surjective k with ⟨n, rfl⟩, refine ⟨n, f.map_int_cast n⟩ end lemma ring_hom_eq_of_ker_eq [comm_ring R] (f g : R →+* (zmod n)) (h : f.ker = g.ker) : f = g := by rw [← f.lift_of_surjective_comp (zmod.ring_hom_surjective f) g (le_of_eq h), ring_hom.ext_zmod (f.lift_of_surjective _ _ _) (ring_hom.id _), ring_hom.id_comp] end zmod
3596643a402d0599c69e2e77c25203010f7ddd75
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/opposite.lean
9a3786f567a47236a4b1d36668e5c60866e2d91a
[ "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,441
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import data.opposite import data.set.image /-! # The opposite of a set > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The opposite of a set `s` is simply the set obtained by taking the opposite of each member of `s`. -/ variables {α : Type*} open opposite namespace set /-- The opposite of a set `s` is the set obtained by taking the opposite of each member of `s`. -/ protected def op (s : set α) : set αᵒᵖ := unop ⁻¹' s /-- The unop of a set `s` is the set obtained by taking the unop of each member of `s`. -/ protected def unop (s : set αᵒᵖ) : set α := op ⁻¹' s @[simp] lemma mem_op {s : set α} {a : αᵒᵖ} : a ∈ s.op ↔ unop a ∈ s := iff.rfl @[simp] lemma op_mem_op {s : set α} {a : α} : op a ∈ s.op ↔ a ∈ s := by rw [mem_op, unop_op] @[simp] lemma mem_unop {s : set αᵒᵖ} {a : α} : a ∈ s.unop ↔ op a ∈ s := iff.rfl @[simp] lemma unop_mem_unop {s : set αᵒᵖ} {a : αᵒᵖ} : unop a ∈ s.unop ↔ a ∈ s := by rw [mem_unop, op_unop] @[simp] lemma op_unop (s : set α) : s.op.unop = s := ext (by simp only [mem_unop, op_mem_op, iff_self, implies_true_iff]) @[simp] lemma unop_op (s : set αᵒᵖ) : s.unop.op = s := ext (by simp only [mem_op, unop_mem_unop, iff_self, implies_true_iff]) /-- The members of the opposite of a set are in bijection with the members of the set itself. -/ @[simps] def op_equiv_self (s : set α) : s.op ≃ s := ⟨λ x, ⟨unop x, x.2⟩, λ x, ⟨op x, x.2⟩, λ x, by simp, λ x, by simp⟩ /-- Taking opposites as an equivalence of powersets. -/ @[simps] def op_equiv : set α ≃ set αᵒᵖ := ⟨set.op, set.unop, op_unop, unop_op⟩ @[simp] lemma singleton_op (x : α) : ({x} : set α).op = {op x} := ext $ λ y, by simpa only [mem_op, mem_singleton_iff] using unop_eq_iff_eq_op @[simp] lemma singleton_unop (x : αᵒᵖ) : ({x} : set αᵒᵖ).unop = {unop x} := ext $ λ y, by simpa only [mem_unop, mem_singleton_iff] using op_eq_iff_eq_unop @[simp] lemma singleton_op_unop (x : α) : ({op x} : set αᵒᵖ).unop = {x} := by simp only [singleton_unop, opposite.unop_op] @[simp] lemma singleton_unop_op (x : αᵒᵖ) : ({unop x} : set α).op = {x} := by simp only [singleton_op, opposite.op_unop] end set
34a9dc43bfcdb7d9254b86ecc5adbc49b94004ee
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/card.lean
81345e7f233c9310db131c321c75935ea3503dff
[ "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
40,940
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.fintype.basic import data.finset.card import data.list.nodup_equiv_fin import tactic.positivity import tactic.wlog /-! # Cardinalities of finite types ## Main declarations * `fintype.card α`: Cardinality of a fintype. Equal to `finset.univ.card`. * `fintype.trunc_equiv_fin`: A fintype `α` is computably equivalent to `fin (card α)`. The `trunc`-free, noncomputable version is `fintype.equiv_fin`. * `fintype.trunc_equiv_of_card_eq` `fintype.equiv_of_card_eq`: Two fintypes of same cardinality are equivalent. See above. * `fin.equiv_iff_eq`: `fin m ≃ fin n` iff `m = n`. * `infinite.nat_embedding`: An embedding of `ℕ` into an infinite type. We also provide the following versions of the pigeonholes principle. * `fintype.exists_ne_map_eq_of_card_lt` and `is_empty_of_card_lt`: Finitely many pigeons and pigeonholes. Weak formulation. * `finite.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes. Weak formulation. * `finite.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong formulation. Some more pigeonhole-like statements can be found in `data.fintype.card_embedding`. Types which have an injection from/a surjection to an `infinite` type are themselves `infinite`. See `infinite.of_injective` and `infinite.of_surjective`. -/ open function open_locale nat universes u v variables {α β γ : Type*} open finset function namespace fintype /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) an equivalence between `α` and `fin (card α)`. Since it is not unique and depends on which permutation of the universe list is used, the equivalence is wrapped in `trunc` to preserve computability. See `fintype.equiv_fin` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. See `fintype.trunc_fin_bijection` for a version without `[decidable_eq α]`. -/ def trunc_equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) := by { unfold card finset.card, exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (nd.nth_le_equiv_of_forall_mem_list _ h).symm) mem_univ_val univ.2 } /-- There is (noncomputably) an equivalence between `α` and `fin (card α)`. See `fintype.trunc_equiv_fin` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) := by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out } /-- There is (computably) a bijection between `fin (card α)` and `α`. Since it is not unique and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. See `fintype.trunc_equiv_fin` for a version that gives an equivalence given `[decidable_eq α]`. -/ def trunc_fin_bijection (α) [fintype α] : trunc {f : fin (card α) → α // bijective f} := by { dunfold card finset.card, exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (nd.nth_le_bijection_of_forall_mem_list _ h)) mem_univ_val univ.2 } theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by { rw ← subtype_card s H, congr } @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ←card_of_finset s H; congr end fintype namespace fintype theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr @[congr] lemma card_congr' {α β} [fintype α] [fintype β] (h : α = β) : card α = card β := card_congr (by rw h) section variables [fintype α] [fintype β] /-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`. See `fintype.equiv_fin_of_card_eq` for the noncomputable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) : trunc (α ≃ fin n) := (trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv) /-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`. See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) : α ≃ fin n := by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out } /-- Two `fintype`s with the same cardinality are (computably) in bijection. See `fintype.equiv_of_card_eq` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) : trunc (α ≃ β) := (trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm)) /-- Two `fintype`s with the same cardinality are (noncomputably) in bijection. See `fintype.trunc_equiv_of_card_eq` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β := by { letI := classical.dec_eq α, letI := classical.dec_eq β, exact (trunc_equiv_of_card_eq h).out } end theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty }, λ ⟨f⟩, card_congr f⟩ /-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or `fintype.card_unique`. -/ @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl @[simp] theorem card_unique [unique α] [h : fintype α] : fintype.card α = 1 := subsingleton.elim (of_subsingleton default) h ▸ card_of_subsingleton _ /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `fintype.card_eq_zero_iff`. -/ @[simp] theorem card_of_is_empty [is_empty α] : fintype.card α = 0 := rfl end fintype namespace set variables {s t : set α} -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ] lemma finset.card_eq_iff_eq_univ [fintype α] (s : finset α) : s.card = fintype.card α ↔ s = finset.univ := ⟨s.eq_univ_of_card, by { rintro rfl, exact finset.card_univ, }⟩ lemma finset.card_le_univ [fintype α] (s : finset α) : s.card ≤ fintype.card α := card_le_of_subset (subset_univ s) lemma finset.card_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) : s.card < fintype.card α := card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩ lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) : s.card < fintype.card α ↔ s ≠ finset.univ := s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ) lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) : sᶜ.card < fintype.card α ↔ s.nonempty := sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) : sᶜ.card = fintype.card α - s.card := finset.card_univ_diff s lemma fintype.card_compl_set [fintype α] (s : set α) [fintype s] [fintype ↥sᶜ] : fintype.card ↥sᶜ = fintype.card α - fintype.card s := begin classical, rw [← set.to_finset_card, ← set.to_finset_card, ← finset.card_compl, set.to_finset_compl] end @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] /-- `fin` as a map from `ℕ` to `Type` is injective. Note that since this is a statement about equality of types, using it should be avoided if possible. -/ lemma fin_injective : function.injective fin := λ m n h, (fintype.card_fin m).symm.trans $ (fintype.card_congr $ equiv.cast h).trans (fintype.card_fin n) /-- A reversed version of `fin.cast_eq_cast` that is easier to rewrite with. -/ theorem fin.cast_eq_cast' {n m : ℕ} (h : fin n = fin m) : cast h = ⇑(fin.cast $ fin_injective h) := (fin.cast_eq_cast _).symm lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n := by simpa only [fintype.card_fin] using s.card_le_univ lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n := ⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩ @[simp] lemma fintype.card_subtype_eq (y : α) [fintype {x // x = y}] : fintype.card {x // x = y} = 1 := fintype.card_unique @[simp] lemma fintype.card_subtype_eq' (y : α) [fintype {x // y = x}] : fintype.card {x // y = x} = 1 := fintype.card_unique @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ @[simp] theorem fintype.card_plift (α : Type*) [fintype α] : fintype.card (plift α) = fintype.card α := fintype.of_equiv_card _ @[simp] lemma fintype.card_order_dual (α : Type*) [fintype α] : fintype.card αᵒᵈ = fintype.card α := rfl @[simp] lemma fintype.card_lex (α : Type*) [fintype α] : fintype.card (lex α) = fintype.card α := rfl /-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses that `sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/ noncomputable def fintype.sum_left {α β} [fintype (α ⊕ β)] : fintype α := fintype.of_injective (sum.inl : α → α ⊕ β) sum.inl_injective /-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses that `sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/ noncomputable def fintype.sum_right {α β} [fintype (α ⊕ β)] : fintype β := fintype.of_injective (sum.inr : β → α ⊕ β) sum.inr_injective /-! ### Relation to `finite` In this section we prove that `α : Type*` is `finite` if and only if `fintype α` is nonempty. -/ @[nolint fintype_finite] protected lemma fintype.finite {α : Type*} (h : fintype α) : finite α := ⟨fintype.equiv_fin α⟩ /-- For efficiency reasons, we want `finite` instances to have higher priority than ones coming from `fintype` instances. -/ @[nolint fintype_finite, priority 900] instance finite.of_fintype (α : Type*) [fintype α] : finite α := fintype.finite ‹_› lemma finite_iff_nonempty_fintype (α : Type*) : finite α ↔ nonempty (fintype α) := ⟨λ h, let ⟨k, ⟨e⟩⟩ := @finite.exists_equiv_fin α h in ⟨fintype.of_equiv _ e.symm⟩, λ ⟨_⟩, by exactI infer_instance⟩ lemma nonempty_fintype (α : Type*) [finite α] : nonempty (fintype α) := (finite_iff_nonempty_fintype α).mp ‹_› /-- Noncomputably get a `fintype` instance from a `finite` instance. This is not an instance because we want `fintype` instances to be useful for computations. -/ noncomputable def fintype.of_finite (α : Type*) [finite α] : fintype α := (nonempty_fintype α).some lemma finite.of_injective {α β : Sort*} [finite β] (f : α → β) (H : injective f) : finite α := begin casesI nonempty_fintype (plift β), rw [← equiv.injective_comp equiv.plift f, ← equiv.comp_injective _ equiv.plift.symm] at H, haveI := fintype.of_injective _ H, exact finite.of_equiv _ equiv.plift, end lemma finite.of_surjective {α β : Sort*} [finite α] (f : α → β) (H : surjective f) : finite β := finite.of_injective _ $ injective_surj_inv H lemma finite.exists_univ_list (α) [finite α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := by { casesI nonempty_fintype α, obtain ⟨l, e⟩ := quotient.exists_rep (@univ α _).1, have := and.intro univ.2 mem_univ_val, exact ⟨_, by rwa ←e at this⟩ } lemma list.nodup.length_le_card {α : Type*} [fintype α] {l : list α} (h : l.nodup) : l.length ≤ fintype.card α := by { classical, exact list.to_finset_card_of_nodup h ▸ l.to_finset.card_le_univ } namespace fintype variables [fintype α] [fintype β] lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β := finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2 lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : card α < card β := calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm ... < card β : finset.card_lt_univ_of_not_mem $ by rwa [← mem_coe, coe_map, coe_univ, set.image_univ] lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f) (h' : ¬function.surjective f) : card α < card β := let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α := card_le_of_injective _ (function.injective_surj_inv h) lemma card_range_le {α β : Type*} (f : α → β) [fintype α] [fintype (set.range f)] : fintype.card (set.range f) ≤ fintype.card α := fintype.card_le_of_surjective (λ a, ⟨f a, by simp⟩) (λ ⟨_, a, ha⟩, ⟨a, by simpa using ha⟩) lemma card_range {α β F : Type*} [embedding_like F α β] (f : F) [fintype α] [fintype (set.range f)] : fintype.card (set.range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.of_injective _ $ embedding_like.injective f /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x)) in ⟨x, y, h⟩ lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [←card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff : card α = 0 ↔ is_empty α := by rw [card, finset.card_eq_zero, univ_eq_empty_iff] lemma card_eq_zero [is_empty α] : card α = 0 := card_eq_zero_iff.2 ‹_› lemma card_eq_one_iff_nonempty_unique : card α = 1 ↔ nonempty (unique α) := ⟨λ h, let ⟨d, h⟩ := fintype.card_eq_one_iff.mp h in ⟨{ default := d, uniq := h}⟩, λ ⟨h⟩, by exactI fintype.card_unique⟩ /-- A `fintype` with cardinality zero is equivalent to `empty`. -/ def card_eq_zero_equiv_equiv_empty : card α = 0 ≃ (α ≃ empty) := (equiv.of_iff card_eq_zero_iff).trans (equiv.equiv_empty_equiv α).symm lemma card_pos_iff : 0 < card α ↔ nonempty α := pos_iff_ne_zero.trans $ not_iff_comm.mp $ not_nonempty_iff.trans card_eq_zero_iff.symm lemma card_pos [h : nonempty α] : 0 < card α := card_pos_iff.mpr h lemma card_ne_zero [nonempty α] : card α ≠ 0 := ne_of_gt card_pos lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm).elim a, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_rfl⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α := card_le_one_iff.trans subsingleton_iff.symm lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α := begin classical, rw ←not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] end lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } lemma card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 := fintype.card_eq_one_iff.2 ⟨i,h⟩ lemma one_lt_card [h : nontrivial α] : 1 < fintype.card α := fintype.one_lt_card_iff_nontrivial.mpr h lemma one_lt_card_iff : 1 < card α ↔ ∃ a b : α, a ≠ b := one_lt_card_iff_nontrivial.trans nontrivial_iff lemma two_lt_card_iff : 2 < card α ↔ ∃ a b c : α, a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp_rw [←finset.card_univ, two_lt_card_iff, mem_univ, true_and] lemma card_of_bijective {f : α → β} (hf : bijective f) : card α = card β := card_congr (equiv.of_bijective f hf) end fintype namespace finite variables [finite α] lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; casesI nonempty_fintype α; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_rfl), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma injective_iff_surjective_of_equiv {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ alias injective_iff_bijective ↔ _root_.function.injective.bijective_of_finite _ alias surjective_iff_bijective ↔ _root_.function.surjective.bijective_of_finite _ alias injective_iff_surjective_of_equiv ↔ _root_.function.injective.surjective_of_fintype _root_.function.surjective.injective_of_fintype end finite namespace fintype variables [fintype α] [fintype β] lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := ⟨λ h, ⟨h.1, card_of_bijective h⟩, λ h, ⟨h.1, h.1.surjective_of_fintype $ equiv_of_card_eq h.2⟩⟩ lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := ⟨λ h, ⟨h.2, card_of_bijective h⟩, λ h, ⟨h.1.injective_of_fintype $ equiv_of_card_eq h.2, h.1⟩⟩ lemma _root_.function.left_inverse.right_inverse_of_card_le {f : α → β} {g : β → α} (hfg : left_inverse f g) (hcard : card α ≤ card β) : right_inverse f g := have hsurj : surjective f, from surjective_iff_has_right_inverse.2 ⟨g, hfg⟩, right_inverse_of_injective_of_left_inverse ((bijective_iff_surjective_and_card _).2 ⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩ ).1 hfg lemma _root_.function.right_inverse.left_inverse_of_card_le {f : α → β} {g : β → α} (hfg : right_inverse f g) (hcard : card β ≤ card α) : left_inverse f g := function.left_inverse.right_inverse_of_card_le hfg hcard end fintype namespace equiv variables [fintype α] [fintype β] open fintype /-- Construct an equivalence from functions that are inverse to each other. -/ @[simps] def of_left_inverse_of_card_le (hβα : card β ≤ card α) (f : α → β) (g : β → α) (h : left_inverse g f) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := h, right_inv := h.right_inverse_of_card_le hβα } /-- Construct an equivalence from functions that are inverse to each other. -/ @[simps] def of_right_inverse_of_card_le (hαβ : card α ≤ card β) (f : α → β) (g : β → α) (h : right_inverse g f) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := h.left_inverse_of_card_le hαβ, right_inv := h } end equiv @[simp] lemma fintype.card_coe (s : finset α) [fintype s] : fintype.card s = s.card := fintype.card_of_finset' s (λ _, iff.rfl) /-- Noncomputable equivalence between a finset `s` coerced to a type and `fin s.card`. -/ noncomputable def finset.equiv_fin (s : finset α) : s ≃ fin s.card := fintype.equiv_fin_of_card_eq (fintype.card_coe _) /-- Noncomputable equivalence between a finset `s` as a fintype and `fin n`, when there is a proof that `s.card = n`. -/ noncomputable def finset.equiv_fin_of_card_eq {s : finset α} {n : ℕ} (h : s.card = n) : s ≃ fin n := fintype.equiv_fin_of_card_eq ((fintype.card_coe _).trans h) /-- Noncomputable equivalence between two finsets `s` and `t` as fintypes when there is a proof that `s.card = t.card`.-/ noncomputable def finset.equiv_of_card_eq {s t : finset α} (h : s.card = t.card) : s ≃ t := fintype.equiv_of_card_eq ((fintype.card_coe _).trans (h.trans (fintype.card_coe _).symm)) @[simp] lemma fintype.card_Prop : fintype.card Prop = 2 := rfl lemma set_fintype_card_le_univ [fintype α] (s : set α) [fintype ↥s] : fintype.card ↥s ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype s) lemma set_fintype_card_eq_univ_iff [fintype α] (s : set α) [fintype ↥s] : fintype.card s = fintype.card α ↔ s = set.univ := by rw [←set.to_finset_card, finset.card_eq_iff_eq_univ, ←set.to_finset_univ, set.to_finset_inj] namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding [finite α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e e.2.bijective_of_finite @[simp] lemma equiv_of_fintype_self_embedding_to_embedding [finite α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } /-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`. This is a formulation of the pigeonhole principle. Note this cannot be an instance as it needs `h`. -/ @[simp] lemma is_empty_of_card_lt [fintype α] [fintype β] (h : fintype.card β < fintype.card α) : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_card_lt f h in ne $ f.injective feq⟩ /-- A constructive embedding of a fintype `α` in another fintype `β` when `card α ≤ card β`. -/ def trunc_of_card_le [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] (h : fintype.card α ≤ fintype.card β) : trunc (α ↪ β) := (fintype.trunc_equiv_fin α).bind $ λ ea, (fintype.trunc_equiv_fin β).map $ λ eb, ea.to_embedding.trans ((fin.cast_le h).to_embedding.trans eb.symm.to_embedding) lemma nonempty_of_card_le [fintype α] [fintype β] (h : fintype.card α ≤ fintype.card β) : nonempty (α ↪ β) := by { classical, exact (trunc_of_card_le h).nonempty } lemma nonempty_iff_card_le [fintype α] [fintype β] : nonempty (α ↪ β) ↔ fintype.card α ≤ fintype.card β := ⟨λ ⟨e⟩, fintype.card_le_of_embedding e, nonempty_of_card_le⟩ lemma exists_of_card_le_finset [fintype α] {s : finset β} (h : fintype.card α ≤ s.card) : ∃ (f : α ↪ β), set.range f ⊆ s := begin rw ← fintype.card_coe at h, rcases nonempty_of_card_le h with ⟨f⟩, exact ⟨f.trans (embedding.subtype _), by simp [set.range_subset_iff]⟩ end end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [←e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β) (h : function.surjective f) (h' : ¬function.injective f) : card β < card α := card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg, have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩, h' $ h.injective_of_fintype (equiv.of_bijective _ w).symm end fintype theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype lemma fintype.card_subtype [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} = ((finset.univ : finset α).filter p).card := begin refine fintype.card_of_subtype _ _, simp end @[simp] lemma fintype.card_subtype_compl [fintype α] (p : α → Prop) [fintype {x // p x}] [fintype {x // ¬ p x}] : fintype.card {x // ¬ p x} = fintype.card α - fintype.card {x // p x} := begin classical, rw [fintype.card_of_subtype (set.to_finset pᶜ), set.to_finset_compl p, finset.card_compl, fintype.card_of_subtype (set.to_finset p)]; intro; simp only [set.mem_to_finset, set.mem_compl_iff]; refl, end theorem fintype.card_subtype_mono (p q : α → Prop) (h : p ≤ q) [fintype {x // p x}] [fintype {x // q x}] : fintype.card {x // p x} ≤ fintype.card {x // q x} := fintype.card_le_of_embedding (subtype.imp_embedding _ _ h) /-- If two subtypes of a fintype have equal cardinality, so do their complements. -/ lemma fintype.card_compl_eq_card_compl [finite α] (p q : α → Prop) [fintype {x // p x}] [fintype {x // ¬ p x}] [fintype {x // q x}] [fintype {x // ¬ q x}] (h : fintype.card {x // p x} = fintype.card {x // q x}) : fintype.card {x // ¬ p x} = fintype.card {x // ¬ q x} := by { casesI nonempty_fintype α, simp only [fintype.card_subtype_compl, h] } theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype.card (quotient s) ≤ fintype.card α := fintype.card_le_of_surjective _ (surjective_quotient_mk _) theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)] {x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α := fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w, h1 (w $ quotient.eq.mpr h2) lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin symmetry, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end namespace finite variables [finite α] lemma well_founded_of_trans_of_irrefl (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; casesI nonempty_fintype α; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded_lt [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ lemma preorder.well_founded_gt [preorder α] : well_founded ((>) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[priority 10] instance linear_order.is_well_order_lt [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded_lt } @[priority 10] instance linear_order.is_well_order_gt [linear_order α] : is_well_order α (>) := { wf := preorder.well_founded_gt } end finite @[nolint fintype_finite] protected lemma fintype.false [infinite α] (h : fintype α) : false := not_finite α @[simp] lemma is_empty_fintype {α : Type*} : is_empty (fintype α) ↔ infinite α := ⟨λ ⟨h⟩, ⟨λ h', (@nonempty_fintype α h').elim h⟩, λ ⟨h⟩, ⟨λ h', h h'.finite⟩⟩ /-- A non-infinite type is a fintype. -/ noncomputable def fintype_of_not_infinite {α : Type*} (h : ¬ infinite α) : fintype α := @fintype.of_finite _ (not_infinite_iff_finite.mp h) section open_locale classical /-- Any type is (classically) either a `fintype`, or `infinite`. One can obtain the relevant typeclasses via `cases fintype_or_infinite α; resetI`. -/ noncomputable def fintype_or_infinite (α : Type*) : psum (fintype α) (infinite α) := if h : infinite α then psum.inr h else psum.inl (fintype_of_not_infinite h) end lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) := begin obtain ⟨c, hcs : c ∈ s⟩ := h, have : well_founded (@has_lt.lt {x // x ∈ s} _) := finite.well_founded_of_trans_of_irrefl _, obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩, exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩, end lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) := @finset.exists_minimal αᵒᵈ _ s h namespace infinite lemma of_not_fintype (h : fintype α → false) : infinite α := is_empty_fintype.mp ⟨h⟩ /-- If `s : set α` is a proper subset of `α` and `f : α → s` is injective, then `α` is infinite. -/ lemma of_injective_to_set {s : set α} (hs : s ≠ set.univ) {f : α → s} (hf : injective f) : infinite α := of_not_fintype $ λ h, begin resetI, classical, refine lt_irrefl (fintype.card α) _, calc fintype.card α ≤ fintype.card s : fintype.card_le_of_injective f hf ... = s.to_finset.card : s.to_finset_card.symm ... < fintype.card α : finset.card_lt_card $ by rwa [set.to_finset_ssubset_univ, set.ssubset_univ_iff] end /-- If `s : set α` is a proper subset of `α` and `f : s → α` is surjective, then `α` is infinite. -/ lemma of_surjective_from_set {s : set α} (hs : s ≠ set.univ) {f : s → α} (hf : surjective f) : infinite α := of_injective_to_set hs (injective_surj_inv hf) lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := not_forall.1 $ λ h, fintype.false ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance (α : Type*) [H : infinite α] : nontrivial α := ⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ protected lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective {α β} [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI (finite.of_injective f hf).false⟩ lemma of_surjective {α β} [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by exactI (finite.of_surjective f hf).false⟩ end infinite instance infinite.set [infinite α] : infinite (set α) := infinite.of_injective singleton (λ a b, set.singleton_eq_singleton_iff.1) instance [infinite α] : infinite (finset α) := infinite.of_injective singleton finset.singleton_injective instance [infinite α] : infinite (option α) := infinite.of_injective some (option.some_injective α) instance sum.infinite_of_left [infinite α] : infinite (α ⊕ β) := infinite.of_injective sum.inl sum.inl_injective instance sum.infinite_of_right [infinite β] : infinite (α ⊕ β) := infinite.of_injective sum.inr sum.inr_injective instance prod.infinite_of_right [nonempty α] [infinite β] : infinite (α × β) := infinite.of_surjective prod.snd prod.snd_surjective instance prod.infinite_of_left [infinite α] [nonempty β] : infinite (α × β) := infinite.of_surjective prod.fst prod.fst_surjective namespace infinite private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin rintro m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ /-- See `infinite.exists_superset_card_eq` for a version that, for a `s : finset α`, provides a superset `t : finset α`, `s ⊆ t` such that `t.card` is fixed. -/ lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) : ∃ s : finset α, s.card = n := ⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩ /-- See `infinite.exists_subset_card_eq` for a version that provides an arbitrary `s : finset α` for any cardinality. -/ lemma exists_superset_card_eq [infinite α] (s : finset α) (n : ℕ) (hn : s.card ≤ n) : ∃ t : finset α, s ⊆ t ∧ t.card = n := begin induction n with n IH generalizing s, { exact ⟨s, subset_refl _, nat.eq_zero_of_le_zero hn⟩ }, { cases hn.eq_or_lt with hn' hn', { exact ⟨s, subset_refl _, hn'⟩ }, obtain ⟨t, hs, ht⟩ := IH _ (nat.le_of_lt_succ hn'), obtain ⟨x, hx⟩ := exists_not_mem_finset t, refine ⟨finset.cons x t hx, hs.trans (finset.subset_cons _), _⟩, simp [hx, ht] } end end infinite /-- If every finset in a type has bounded cardinality, that type is finite. -/ noncomputable def fintype_of_finset_card_le {ι : Type*} (n : ℕ) (w : ∀ s : finset ι, s.card ≤ n) : fintype ι := begin apply fintype_of_not_infinite, introI i, obtain ⟨s, c⟩ := infinite.exists_subset_card_eq ι (n+1), specialize w s, rw c at w, exact nat.not_succ_le_self n w, end lemma not_injective_infinite_finite {α β} [infinite α] [finite β] (f : α → β) : ¬ injective f := λ hf, (finite.of_injective f hf).false /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `fintype.exists_ne_map_eq_of_card_lt`, `finite.exists_infinite_fiber`. -/ lemma finite.exists_ne_map_eq_of_infinite {α β} [infinite α] [finite β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := by simpa only [injective, not_forall, not_imp, and.comm] using not_injective_infinite_finite f instance function.embedding.is_empty {α β} [infinite α] [finite β] : is_empty (α ↪ β) := ⟨λ f, not_injective_infinite_finite f f.2⟩ /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `finite.exists_ne_map_eq_of_infinite` -/ lemma finite.exists_infinite_fiber [infinite α] [finite β] (f : α → β) : ∃ y : β, infinite (f ⁻¹' {y}) := begin classical, by_contra' hf, casesI nonempty_fintype β, haveI := λ y, fintype_of_not_infinite $ hf y, let key : fintype α := { elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact key.false, end lemma not_surjective_finite_infinite {α β} [finite α] [infinite β] (f : α → β) : ¬ surjective f := λ hf, (infinite.of_surjective f hf).not_finite ‹_› section trunc /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } end trunc /-- A custom induction principle for fintypes. The base case is a subsingleton type, and the induction step is for non-trivial types, and one can assume the hypothesis for smaller types (via `fintype.card`). The major premise is `fintype α`, so to use this with the `induction` tactic you have to give a name to that instance and use that name. -/ @[elab_as_eliminator] lemma fintype.induction_subsingleton_or_nontrivial {P : Π α [fintype α], Prop} (α : Type*) [fintype α] (hbase : ∀ α [fintype α] [subsingleton α], by exactI P α) (hstep : ∀ α [fintype α] [nontrivial α], by exactI ∀ (ih : ∀ β [fintype β], by exactI ∀ (h : fintype.card β < fintype.card α), P β), P α) : P α := begin obtain ⟨ n, hn ⟩ : ∃ n, fintype.card α = n := ⟨fintype.card α, rfl⟩, unfreezingI { induction n using nat.strong_induction_on with n ih generalizing α }, casesI (subsingleton_or_nontrivial α) with hsing hnontriv, { apply hbase, }, { apply hstep, introsI β _ hlt, rw hn at hlt, exact (ih (fintype.card β) hlt _ rfl), } end namespace tactic open positivity private lemma card_univ_pos (α : Type*) [fintype α] [nonempty α] : 0 < (finset.univ : finset α).card := finset.univ_nonempty.card_pos /-- Extension for the `positivity` tactic: `finset.card s` is positive if `s` is nonempty. -/ @[positivity] meta def positivity_finset_card : expr → tactic strictness | `(finset.card %%s) := do -- TODO: Partial decision procedure for `finset.nonempty` p ← to_expr ``(finset.nonempty %%s) >>= find_assumption, positive <$> mk_app ``finset.nonempty.card_pos [p] | `(@fintype.card %%α %%i) := positive <$> mk_mapp ``fintype.card_pos [α, i, none] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `finset.card s` or `fintype.card α`" end tactic
26758d7e18ab29823409454088ca70f9c4f26a3b
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/data/bounded_list.lean
8f0be6d54d845f8261d639c2698d23d9a10f6d72
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,526
lean
import galois.tactic universe variables u v def bounded_list (α : Type u) (n : ℕ) := { l : list α // l.length ≤ n } namespace bounded_list /-- Two bounded_lists are equal if the underlying lists are equal. -/ theorem eq (α : Type u) (n : ℕ) : ∀ {t₀ t₁ : bounded_list α n}, t₀^.val = t₁^.val → t₀ = t₁ | ⟨l, p₀⟩ ⟨.(l), p₁⟩ rfl := rfl /-- Return tt if a bounded list is not empty. -/ @[reducible] def empty {α : Type u} {n : ℕ} (l : bounded_list α n) : bool := l.val.empty /-- Return singleton bounded_list -/ def single {α : Type u} (x : α) : bounded_list α 1 := ⟨[x], dec_trivial⟩ -- Empty bounded_list def nil {α : Type u} : bounded_list α 0 := ⟨ [], dec_trivial ⟩ -- Prepend an element to a bounded list. def cons {α : Type u} {n : ℕ} (x : α) : bounded_list α n → bounded_list α (n+1) | ⟨l, p⟩ := let q : (l.cons x).length ≤ n+1 := begin simp [nat.add_succ], apply nat.succ_le_succ, exact p, end in ⟨ l.cons x, q ⟩ -- A bounded_list of length n can be extended to a list of length n + k def extend {α : Type u} {n : ℕ} : bounded_list α n → Π (k : ℕ), bounded_list α (n + k) | ⟨l, p⟩ k := ⟨ l, le_trans p (nat.le_add_right n k) ⟩ -- Map over elements in a list. def map {α β : Type u} {n : ℕ} (f : α → β) : bounded_list α n → bounded_list β n | ⟨l, p⟩ := ⟨ l.map f, begin simp [list.length_map], exact p, end⟩ def append {A : Type u} {n m : ℕ} : bounded_list A n → bounded_list A m → bounded_list A (n + m) | ⟨ xs, pxs ⟩ ⟨ ys, pys ⟩ := ⟨ xs ++ ys, begin rw list.length_append, apply add_le_add; assumption end ⟩ inductive length_succ_cons_ind {A : Type u} (xs : list A) (n : ℕ) : Prop | smaller : xs.length ≤ n → length_succ_cons_ind | same : ∀ (x : A) (xs' : list A), xs = x :: xs' → xs'.length = n → length_succ_cons_ind lemma list.length_le_zero_nil {A : Type u} {xs : list A} (H : xs.length ≤ 0) : xs = list.nil := begin apply list.eq_nil_of_length_eq_zero, apply nat.eq_zero_of_le_zero, assumption, end lemma length_succ_cons {A : Type u} {xs : list A} {n : ℕ} (H : xs.length ≤ n.succ) : length_succ_cons_ind xs n := begin rw le_iff_lt_or_eq at H, induction H with H H, { apply_in H nat.le_of_lt_succ, apply length_succ_cons_ind.smaller, assumption }, { cases xs, try { contradiction }, apply length_succ_cons_ind.same, reflexivity, dsimp at H, injection H, } end /-- Given a list and a bound this returns a bounded list if the length is small enough. œ-/ def of_list {α : Type u} (l : list α) (m : ℕ ) : option (bounded_list α m) := if p : l.length ≤ m then option.some (⟨l, p⟩) else option.none /-- Concatenate a bounded list of bounded lists all together. -/ lemma concat {A : Type u} {n m : ℕ} : bounded_list (bounded_list A m) n → bounded_list A (m * n) | ⟨ xss, pxss ⟩ := ⟨ (xss.map subtype.val).join , begin clear concat, revert xss, induction n; intros, { apply_in pxss list.length_le_zero_nil, subst xss, simp [list.join], }, { apply_in pxss length_succ_cons, induction pxss, { specialize (ih_1 _ a_1), apply le_trans, assumption, apply nat.mul_le_mul_left, apply nat.le_succ, }, { subst xss, dsimp [list.map, list.join], rw list.length_append, rw nat.mul_succ, rw nat.add_comm, apply add_le_add, apply ih_1, subst a, apply x.property, } } end ⟩ end bounded_list
a463020abb6368225108e839aab4ba3a8e0021ef
d78da34857deb99eac819e7889eae59fdccec754
/src/magma.lean
e46595a2ca82d106ba7cbd2808a181cdcfd559e3
[]
no_license
wudcscheme/conceptual-mathematics-in-lean
6ef168b69fb28eb25223db10ebb4b2fefad4dbdb
cc7877f528bfaf99a024844744e023acbfcadb1d
refs/heads/master
1,678,885,284,910
1,601,437,497,000
1,601,663,206,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,151
lean
import category_theory.category import category_theory.concrete_category.bundled import data.real.basic namespace magma universe u open category_theory class magma (carrier: Type*) extends has_mul carrier def Magma := bundled magma instance mag_has_mul (m: Magma) : has_mul m.α := ⟨ m.str.mul ⟩ section magma_homs structure magma_hom (A: Magma) (B: Magma) := (to_fun : A.α → B.α) (preserves : ∀ x y : A.α, to_fun (x * y) = to_fun x * to_fun y . obviously) infixr ` m→ `:25 := magma_hom variables {A B C: Magma} instance : has_coe_to_fun (A m→ B) := ⟨_, magma_hom.to_fun⟩ lemma to_fun_eq_coe (f : A m→ B) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : A.α → B.α) (pre) : ⇑(magma_hom.mk f pre) = f := rfl lemma coe_inj ⦃f g : A m→ B⦄ (h : (f : A.α → B.α) = g) : f = g := begin cases f; cases g; cases h; refl, end @[ext] lemma magma_hom_ext ⦃f g : A m→ B⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) def magma_id : A m→ A := ⟨id, by simp⟩ def magma_hom_comp (f: A m→ B) (g: B m→ C) : A m→ C := { to_fun := g.to_fun ∘ f.to_fun, preserves := by { intros x y, simp, rw f.preserves, rw g.preserves } } end magma_homs instance : has_hom Magma := ⟨λ m n, m m→ n⟩ instance : category_struct Magma := ⟨@magma_id, @magma_hom_comp⟩ -- see here for explanation of the universe parameter -- https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Why.20can't.20infer.20instance instance : category Magma.{u} := {} section magmas def RPos := {x: ℝ // x > 0} def RNonneg := {x: ℝ // x >= 0} def rpos_mul (a b: RPos) : RPos := {val := a.val * b.val, property := real.mul_pos a.property b.property} def rnonneg_mul (a b: RNonneg) : RNonneg := {val := a.val * b.val, property := mul_nonneg a.property b.property} def r_plus_magma : magma ℝ := {mul := (+)} def r_times_magma: magma ℝ := {mul := (*)} def rpos_mul_magma: magma RPos := {mul := rpos_mul} def rnonneg_mul_magma: magma RNonneg := {mul := rnonneg_mul} def r_plus_Magma : Magma := ⟨ ℝ, r_plus_magma ⟩ end magmas end magma