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
47d5661cba886f542d113dfbb38ee8fb7fa7ab1d
c86b74188c4b7a462728b1abd659ab4e5828dd61
/stage0/src/Std/Data/HashMap.lean
b0d76a8eabd66b1fb97323fd0d4c575df216c2ce
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,720
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Std.Data.AssocList namespace Std universes u v w def HashMapBucket (α : Type u) (β : Type v) := { b : Array (AssocList α β) // b.size > 0 } def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β := ⟨ data.val.uset i d h, by erw [Array.size_set]; exact data.property ⟩ structure HashMapImp (α : Type u) (β : Type v) where size : Nat buckets : HashMapBucket α β def mkHashMapImp {α : Type u} {β : Type v} (nbuckets := 8) : HashMapImp α β := let n := if nbuckets = 0 then 8 else nbuckets; { size := 0, buckets := ⟨ mkArray n AssocList.nil, by simp; cases nbuckets; decide; apply Nat.zeroLtSucc; done ⟩ } namespace HashMapImp variable {α : Type u} {β : Type v} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u % n, USize.modn_lt _ h⟩ @[inline] def reinsertAux (hashFn : α → UInt64) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β := let ⟨i, h⟩ := mkIdx data.property (hashFn a |>.toUSize) data.update i (AssocList.cons a b (data.val.uget i h)) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ := data.val.foldlM (init := d) fun d b => b.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ := foldBuckets m.buckets d f @[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (f : α → β → m PUnit) : m PUnit := data.val.forM fun b => b.forM f @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMapImp α β) : m PUnit := forBucketsM h.buckets f def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize) (buckets.val.uget i h).findEntry? a def find? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize) (buckets.val.uget i h).find? a def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize) (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : AssocList α β := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx AssocList.nil let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β := let nbuckets := buckets.val.size * 2 have : nbuckets > 0 := Nat.mulPos buckets.property (by decide) let new_buckets : HashMapBucket α β := ⟨mkArray nbuckets AssocList.nil, by simp; assumption⟩ { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size, buckets.update i (bkt.replace a b) h⟩ else let size' := size + 1 let buckets' := buckets.update i (AssocList.cons a b bkt) h if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where | mkWff : ∀ n, WellFormed (mkHashMapImp n) | insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashMapImp def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := { m : HashMapImp α β // m.WellFormed } open Std.HashMapImp def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (nbuckets := 8) : HashMap α β := ⟨ mkHashMapImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashMap variable {α : Type u} {β : Type v} [BEq α] [Hashable α] instance : Inhabited (HashMap α β) where default := mkHashMap instance : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ @[inline] def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a b, WellFormed.insertWff m a b hw ⟩ @[inline] def erase (m : HashMap α β) (a : α) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) := match m with | ⟨ m, _ ⟩ => m.findEntry? a @[inline] def find? (m : HashMap α β) (a : α) : Option β := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" @[inline] def getOp (self : HashMap α β) (idx : α) : Option β := self.find? idx @[inline] def contains (m : HashMap α β) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMap α β) : m PUnit := match h with | ⟨ h, _ ⟩ => h.forM f @[inline] def size (m : HashMap α β) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashMap α β) : Bool := m.size = 0 @[inline] def empty : HashMap α β := mkHashMap def toList (m : HashMap α β) : List (α × β) := m.fold (init := []) fun r k v => (k, v)::r def toArray (m : HashMap α β) : Array (α × β) := m.fold (init := #[]) fun r k v => r.push (k, v) def numBuckets (m : HashMap α β) : Nat := m.val.buckets.val.size end HashMap end Std
024dd33a8e476b9776af6d781e5c01bc947c3359
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/inner_product_space/calculus.lean
31ddee695201e8148a49c287e853f9fc9aa5bf0a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
15,632
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.inner_product_space.pi_L2 import analysis.special_functions.sqrt /-! # Calculus in inner product spaces In this file we prove that the inner product and square of the norm in an inner space are infinitely `ℝ`-smooth. In order to state these results, we need a `normed_space ℝ E` instance. Though we can deduce this structure from `inner_product_space 𝕜 E`, this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]`. We also prove that functions to a `euclidean_space` are (higher) differentiable if and only if their components are. This follows from the corresponding fact for finite product of normed spaces, and from the equivalence of norms in finite dimensions. ## TODO The last part of the file should be generalized to `pi_Lp`. -/ noncomputable theory open is_R_or_C real filter open_locale big_operators classical topology section deriv_inner variables {𝕜 E F : Type*} [is_R_or_C 𝕜] variables [normed_add_comm_group E] [inner_product_space 𝕜 E] variables [normed_add_comm_group F] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y variables (𝕜) [normed_space ℝ E] /-- Derivative of the inner product. -/ def fderiv_inner_clm (p : E × E) : E × E →L[ℝ] 𝕜 := is_bounded_bilinear_map_inner.deriv p @[simp] lemma fderiv_inner_clm_apply (p x : E × E) : fderiv_inner_clm 𝕜 p x = ⟪p.1, x.2⟫ + ⟪x.1, p.2⟫ := rfl lemma cont_diff_inner {n} : cont_diff ℝ n (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.cont_diff lemma cont_diff_at_inner {p : E × E} {n} : cont_diff_at ℝ n (λ p : E × E, ⟪p.1, p.2⟫) p := cont_diff_inner.cont_diff_at lemma differentiable_inner : differentiable ℝ (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.differentiable_at variables {G : Type*} [normed_add_comm_group G] [normed_space ℝ G] {f g : G → E} {f' g' : G →L[ℝ] E} {s : set G} {x : G} {n : ℕ∞} include 𝕜 lemma cont_diff_within_at.inner (hf : cont_diff_within_at ℝ n f s x) (hg : cont_diff_within_at ℝ n g s x) : cont_diff_within_at ℝ n (λ x, ⟪f x, g x⟫) s x := cont_diff_at_inner.comp_cont_diff_within_at x (hf.prod hg) lemma cont_diff_at.inner (hf : cont_diff_at ℝ n f x) (hg : cont_diff_at ℝ n g x) : cont_diff_at ℝ n (λ x, ⟪f x, g x⟫) x := hf.inner 𝕜 hg lemma cont_diff_on.inner (hf : cont_diff_on ℝ n f s) (hg : cont_diff_on ℝ n g s) : cont_diff_on ℝ n (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner 𝕜 (hg x hx) lemma cont_diff.inner (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g) : cont_diff ℝ n (λ x, ⟪f x, g x⟫) := cont_diff_inner.comp (hf.prod hg) lemma has_fderiv_within_at.inner (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm 𝕜 (f x, g x)).comp $ f'.prod g') s x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp_has_fderiv_within_at x (hf.prod hg) lemma has_strict_fderiv_at.inner (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm 𝕜 (f x, g x)).comp $ f'.prod g') x := (is_bounded_bilinear_map_inner.has_strict_fderiv_at (f x, g x)).comp x (hf.prod hg) lemma has_fderiv_at.inner (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm 𝕜 (f x, g x)).comp $ f'.prod g') x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp x (hf.prod hg) lemma has_deriv_within_at.inner {f g : ℝ → E} {f' g' : E} {s : set ℝ} {x : ℝ} (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) s x := by simpa using (hf.has_fderiv_within_at.inner 𝕜 hg.has_fderiv_within_at).has_deriv_within_at lemma has_deriv_at.inner {f g : ℝ → E} {f' g' : E} {x : ℝ} : has_deriv_at f f' x → has_deriv_at g g' x → has_deriv_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) x := by simpa only [← has_deriv_within_at_univ] using has_deriv_within_at.inner 𝕜 lemma differentiable_within_at.inner (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) : differentiable_within_at ℝ (λ x, ⟪f x, g x⟫) s x := ((differentiable_inner _).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg).has_fderiv_within_at).differentiable_within_at lemma differentiable_at.inner (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : differentiable_at ℝ (λ x, ⟪f x, g x⟫) x := (differentiable_inner _).comp x (hf.prod hg) lemma differentiable_on.inner (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) : differentiable_on ℝ (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner 𝕜 (hg x hx) lemma differentiable.inner (hf : differentiable ℝ f) (hg : differentiable ℝ g) : differentiable ℝ (λ x, ⟪f x, g x⟫) := λ x, (hf x).inner 𝕜 (hg x) lemma fderiv_inner_apply (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (y : G) : fderiv ℝ (λ t, ⟪f t, g t⟫) x y = ⟪f x, fderiv ℝ g x y⟫ + ⟪fderiv ℝ f x y, g x⟫ := by { rw [(hf.has_fderiv_at.inner 𝕜 hg.has_fderiv_at).fderiv], refl } lemma deriv_inner_apply {f g : ℝ → E} {x : ℝ} (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : deriv (λ t, ⟪f t, g t⟫) x = ⟪f x, deriv g x⟫ + ⟪deriv f x, g x⟫ := (hf.has_deriv_at.inner 𝕜 hg.has_deriv_at).deriv lemma cont_diff_norm_sq : cont_diff ℝ n (λ x : E, ‖x‖ ^ 2) := begin simp only [sq, ← @inner_self_eq_norm_mul_norm 𝕜], exact (re_clm : 𝕜 →L[ℝ] ℝ).cont_diff.comp (cont_diff_id.inner 𝕜 cont_diff_id) end lemma cont_diff.norm_sq (hf : cont_diff ℝ n f) : cont_diff ℝ n (λ x, ‖f x‖ ^ 2) := (cont_diff_norm_sq 𝕜).comp hf lemma cont_diff_within_at.norm_sq (hf : cont_diff_within_at ℝ n f s x) : cont_diff_within_at ℝ n (λ y, ‖f y‖ ^ 2) s x := (cont_diff_norm_sq 𝕜).cont_diff_at.comp_cont_diff_within_at x hf lemma cont_diff_at.norm_sq (hf : cont_diff_at ℝ n f x) : cont_diff_at ℝ n (λ y, ‖f y‖ ^ 2) x := hf.norm_sq 𝕜 lemma cont_diff_at_norm {x : E} (hx : x ≠ 0) : cont_diff_at ℝ n norm x := have ‖id x‖ ^ 2 ≠ 0, from pow_ne_zero _ (norm_pos_iff.2 hx).ne', by simpa only [id, sqrt_sq, norm_nonneg] using (cont_diff_at_id.norm_sq 𝕜).sqrt this lemma cont_diff_at.norm (hf : cont_diff_at ℝ n f x) (h0 : f x ≠ 0) : cont_diff_at ℝ n (λ y, ‖f y‖) x := (cont_diff_at_norm 𝕜 h0).comp x hf lemma cont_diff_at.dist (hf : cont_diff_at ℝ n f x) (hg : cont_diff_at ℝ n g x) (hne : f x ≠ g x) : cont_diff_at ℝ n (λ y, dist (f y) (g y)) x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm 𝕜 (sub_ne_zero.2 hne) } lemma cont_diff_within_at.norm (hf : cont_diff_within_at ℝ n f s x) (h0 : f x ≠ 0) : cont_diff_within_at ℝ n (λ y, ‖f y‖) s x := (cont_diff_at_norm 𝕜 h0).comp_cont_diff_within_at x hf lemma cont_diff_within_at.dist (hf : cont_diff_within_at ℝ n f s x) (hg : cont_diff_within_at ℝ n g s x) (hne : f x ≠ g x) : cont_diff_within_at ℝ n (λ y, dist (f y) (g y)) s x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm 𝕜 (sub_ne_zero.2 hne) } lemma cont_diff_on.norm_sq (hf : cont_diff_on ℝ n f s) : cont_diff_on ℝ n (λ y, ‖f y‖ ^ 2) s := (λ x hx, (hf x hx).norm_sq 𝕜) lemma cont_diff_on.norm (hf : cont_diff_on ℝ n f s) (h0 : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ y, ‖f y‖) s := λ x hx, (hf x hx).norm 𝕜 (h0 x hx) lemma cont_diff_on.dist (hf : cont_diff_on ℝ n f s) (hg : cont_diff_on ℝ n g s) (hne : ∀ x ∈ s, f x ≠ g x) : cont_diff_on ℝ n (λ y, dist (f y) (g y)) s := λ x hx, (hf x hx).dist 𝕜 (hg x hx) (hne x hx) lemma cont_diff.norm (hf : cont_diff ℝ n f) (h0 : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ y, ‖f y‖) := cont_diff_iff_cont_diff_at.2 $ λ x, hf.cont_diff_at.norm 𝕜 (h0 x) lemma cont_diff.dist (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g) (hne : ∀ x, f x ≠ g x) : cont_diff ℝ n (λ y, dist (f y) (g y)) := cont_diff_iff_cont_diff_at.2 $ λ x, hf.cont_diff_at.dist 𝕜 hg.cont_diff_at (hne x) omit 𝕜 lemma has_strict_fderiv_at_norm_sq (x : F) : has_strict_fderiv_at (λ x, ‖x‖ ^ 2) (bit0 (innerSL ℝ x)) x := begin simp only [sq, ← @inner_self_eq_norm_mul_norm ℝ], convert (has_strict_fderiv_at_id x).inner ℝ (has_strict_fderiv_at_id x), ext y, simp [bit0, real_inner_comm], end include 𝕜 lemma differentiable_at.norm_sq (hf : differentiable_at ℝ f x) : differentiable_at ℝ (λ y, ‖f y‖ ^ 2) x := ((cont_diff_at_id.norm_sq 𝕜).differentiable_at le_rfl).comp x hf lemma differentiable_at.norm (hf : differentiable_at ℝ f x) (h0 : f x ≠ 0) : differentiable_at ℝ (λ y, ‖f y‖) x := ((cont_diff_at_norm 𝕜 h0).differentiable_at le_rfl).comp x hf lemma differentiable_at.dist (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (hne : f x ≠ g x) : differentiable_at ℝ (λ y, dist (f y) (g y)) x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm 𝕜 (sub_ne_zero.2 hne) } lemma differentiable.norm_sq (hf : differentiable ℝ f) : differentiable ℝ (λ y, ‖f y‖ ^ 2) := λ x, (hf x).norm_sq 𝕜 lemma differentiable.norm (hf : differentiable ℝ f) (h0 : ∀ x, f x ≠ 0) : differentiable ℝ (λ y, ‖f y‖) := λ x, (hf x).norm 𝕜 (h0 x) lemma differentiable.dist (hf : differentiable ℝ f) (hg : differentiable ℝ g) (hne : ∀ x, f x ≠ g x) : differentiable ℝ (λ y, dist (f y) (g y)) := λ x, (hf x).dist 𝕜 (hg x) (hne x) lemma differentiable_within_at.norm_sq (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ y, ‖f y‖ ^ 2) s x := ((cont_diff_at_id.norm_sq 𝕜).differentiable_at le_rfl).comp_differentiable_within_at x hf lemma differentiable_within_at.norm (hf : differentiable_within_at ℝ f s x) (h0 : f x ≠ 0) : differentiable_within_at ℝ (λ y, ‖f y‖) s x := ((cont_diff_at_id.norm 𝕜 h0).differentiable_at le_rfl).comp_differentiable_within_at x hf lemma differentiable_within_at.dist (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) (hne : f x ≠ g x) : differentiable_within_at ℝ (λ y, dist (f y) (g y)) s x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm 𝕜 (sub_ne_zero.2 hne) } lemma differentiable_on.norm_sq (hf : differentiable_on ℝ f s) : differentiable_on ℝ (λ y, ‖f y‖ ^ 2) s := λ x hx, (hf x hx).norm_sq 𝕜 lemma differentiable_on.norm (hf : differentiable_on ℝ f s) (h0 : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ y, ‖f y‖) s := λ x hx, (hf x hx).norm 𝕜 (h0 x hx) lemma differentiable_on.dist (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) (hne : ∀ x ∈ s, f x ≠ g x) : differentiable_on ℝ (λ y, dist (f y) (g y)) s := λ x hx, (hf x hx).dist 𝕜 (hg x hx) (hne x hx) end deriv_inner section pi_like open continuous_linear_map variables {𝕜 ι H : Type*} [is_R_or_C 𝕜] [normed_add_comm_group H] [normed_space 𝕜 H] [fintype ι] {f : H → euclidean_space 𝕜 ι} {f' : H →L[𝕜] euclidean_space 𝕜 ι} {t : set H} {y : H} lemma differentiable_within_at_euclidean : differentiable_within_at 𝕜 f t y ↔ ∀ i, differentiable_within_at 𝕜 (λ x, f x i) t y := begin rw [← (euclidean_space.equiv ι 𝕜).comp_differentiable_within_at_iff, differentiable_within_at_pi], refl end lemma differentiable_at_euclidean : differentiable_at 𝕜 f y ↔ ∀ i, differentiable_at 𝕜 (λ x, f x i) y := begin rw [← (euclidean_space.equiv ι 𝕜).comp_differentiable_at_iff, differentiable_at_pi], refl end lemma differentiable_on_euclidean : differentiable_on 𝕜 f t ↔ ∀ i, differentiable_on 𝕜 (λ x, f x i) t := begin rw [← (euclidean_space.equiv ι 𝕜).comp_differentiable_on_iff, differentiable_on_pi], refl end lemma differentiable_euclidean : differentiable 𝕜 f ↔ ∀ i, differentiable 𝕜 (λ x, f x i) := begin rw [← (euclidean_space.equiv ι 𝕜).comp_differentiable_iff, differentiable_pi], refl end lemma has_strict_fderiv_at_euclidean : has_strict_fderiv_at f f' y ↔ ∀ i, has_strict_fderiv_at (λ x, f x i) (euclidean_space.proj i ∘L f') y := begin rw [← (euclidean_space.equiv ι 𝕜).comp_has_strict_fderiv_at_iff, has_strict_fderiv_at_pi'], refl end lemma has_fderiv_within_at_euclidean : has_fderiv_within_at f f' t y ↔ ∀ i, has_fderiv_within_at (λ x, f x i) (euclidean_space.proj i ∘L f') t y := begin rw [← (euclidean_space.equiv ι 𝕜).comp_has_fderiv_within_at_iff, has_fderiv_within_at_pi'], refl end lemma cont_diff_within_at_euclidean {n : ℕ∞} : cont_diff_within_at 𝕜 n f t y ↔ ∀ i, cont_diff_within_at 𝕜 n (λ x, f x i) t y := begin rw [← (euclidean_space.equiv ι 𝕜).comp_cont_diff_within_at_iff, cont_diff_within_at_pi], refl end lemma cont_diff_at_euclidean {n : ℕ∞} : cont_diff_at 𝕜 n f y ↔ ∀ i, cont_diff_at 𝕜 n (λ x, f x i) y := begin rw [← (euclidean_space.equiv ι 𝕜).comp_cont_diff_at_iff, cont_diff_at_pi], refl end lemma cont_diff_on_euclidean {n : ℕ∞} : cont_diff_on 𝕜 n f t ↔ ∀ i, cont_diff_on 𝕜 n (λ x, f x i) t := begin rw [← (euclidean_space.equiv ι 𝕜).comp_cont_diff_on_iff, cont_diff_on_pi], refl end lemma cont_diff_euclidean {n : ℕ∞} : cont_diff 𝕜 n f ↔ ∀ i, cont_diff 𝕜 n (λ x, f x i) := begin rw [← (euclidean_space.equiv ι 𝕜).comp_cont_diff_iff, cont_diff_pi], refl end end pi_like section diffeomorph_unit_ball open metric (hiding mem_nhds_iff) variables {n : ℕ∞} {E : Type*} [normed_add_comm_group E] [inner_product_space ℝ E] lemma cont_diff_homeomorph_unit_ball : cont_diff ℝ n $ λ (x : E), (homeomorph_unit_ball x : E) := begin suffices : cont_diff ℝ n (λ x, (1 + ‖x‖^2).sqrt⁻¹), { exact this.smul cont_diff_id, }, have h : ∀ (x : E), 0 < 1 + ‖x‖ ^ 2 := λ x, by positivity, refine cont_diff.inv _ (λ x, real.sqrt_ne_zero'.mpr (h x)), exact (cont_diff_const.add $ cont_diff_norm_sq ℝ).sqrt (λ x, (h x).ne.symm), end lemma cont_diff_on_homeomorph_unit_ball_symm {f : E → E} (h : ∀ y (hy : y ∈ ball (0 : E) 1), f y = homeomorph_unit_ball.symm ⟨y, hy⟩) : cont_diff_on ℝ n f $ ball 0 1 := begin intros y hy, apply cont_diff_at.cont_diff_within_at, have hf : f =ᶠ[𝓝 y] λ y, (1 - ‖(y : E)‖^2).sqrt⁻¹ • (y : E), { rw eventually_eq_iff_exists_mem, refine ⟨ball (0 : E) 1, mem_nhds_iff.mpr ⟨ball (0 : E) 1, set.subset.refl _, is_open_ball, hy⟩, λ z hz, _⟩, rw h z hz, refl, }, refine cont_diff_at.congr_of_eventually_eq _ hf, suffices : cont_diff_at ℝ n (λy, (1 - ‖(y : E)‖^2).sqrt⁻¹) y, { exact this.smul cont_diff_at_id }, have h : 0 < 1 - ‖(y : E)‖^2, by rwa [mem_ball_zero_iff, ← _root_.abs_one, ← abs_norm, ← sq_lt_sq, one_pow, ← sub_pos] at hy, refine cont_diff_at.inv _ (real.sqrt_ne_zero'.mpr h), refine cont_diff_at.comp _ (cont_diff_at_sqrt h.ne.symm) _, exact cont_diff_at_const.sub (cont_diff_norm_sq ℝ).cont_diff_at, end end diffeomorph_unit_ball
bbeddd3006d8f3d4f2d4c61421e524dc53a413cb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/filtered_auto.lean
91d8ca5f7a2003a4fedaf1f933b42cc7245e2898
[]
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
9,373
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.fin_category import Mathlib.category_theory.limits.cones import Mathlib.category_theory.adjunction.basic import Mathlib.order.bounded_lattice import Mathlib.PostPort universes v u l v₁ u₁ namespace Mathlib /-! # Filtered categories A category is filtered if every finite diagram admits a cocone. We give a simple characterisation of this condition as 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. Filtered colimits are often better behaved than arbitrary colimits. See `category_theory/limits/types` for some details. Filtered categories are nice because colimits indexed by filtered categories tend to be easier to describe than general colimits (and often often preserved by functors). In this file we show that any functor from a finite category to a filtered category admits a cocone: * `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)` More generally, for any finite collection of objects and morphisms between them in a filtered category (even if not closed under composition) there exists some object `Z` receiving maps from all of them, so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute. This formulation is often more useful in practice. We give two variants, `sup_exists'`, which takes a single finset of objects, and a finset of morphisms (bundled with their sources and targets), and `sup_exists`, which takes a finset of objects, and an indexed family (indexed by source and target) of finsets of morphisms. ## Future work * Finite limits commute with filtered colimits * Forgetful functors for algebraic categories typically preserve filtered colimits. -/ namespace category_theory /-- A category `is_filtered_or_empty` if 1. for every pair of objects there exists another object "to the right", and 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal. -/ class is_filtered_or_empty (C : Type u) [category C] where cocone_objs : ∀ (X Y : C), ∃ (Z : C), ∃ (f : X ⟶ Z), ∃ (g : Y ⟶ Z), True cocone_maps : ∀ {X Y : C} (f g : X ⟶ Y), ∃ (Z : C), ∃ (h : Y ⟶ Z), f ≫ h = g ≫ h /-- A category `is_filtered` if 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. See https://stacks.math.columbia.edu/tag/002V. (They also define a diagram being filtered.) -/ class is_filtered (C : Type u) [category C] extends is_filtered_or_empty C where nonempty : Nonempty C protected instance is_filtered_or_empty_of_semilattice_sup (α : Type u) [semilattice_sup α] : is_filtered_or_empty α := is_filtered_or_empty.mk (fun (X Y : α) => Exists.intro (X ⊔ Y) (Exists.intro (hom_of_le le_sup_left) (Exists.intro (hom_of_le le_sup_right) trivial))) fun (X Y : α) (f g : X ⟶ Y) => Exists.intro Y (Exists.intro 𝟙 (ulift.ext (f ≫ 𝟙) (g ≫ 𝟙) (plift.ext (ulift.down (f ≫ 𝟙)) (ulift.down (g ≫ 𝟙))))) protected instance is_filtered_of_semilattice_sup_top (α : Type u) [semilattice_sup_top α] : is_filtered α := is_filtered.mk namespace is_filtered /-- `max j j'` is an arbitrary choice of object to the right of both `j` and `j'`, whose existence is ensured by `is_filtered`. -/ def max {C : Type u} [category C] [is_filtered C] (j : C) (j' : C) : C := Exists.some sorry /-- `left_to_max j j'` is an arbitrarily choice of morphism from `j` to `max j j'`, whose existence is ensured by `is_filtered`. -/ def left_to_max {C : Type u} [category C] [is_filtered C] (j : C) (j' : C) : j ⟶ max j j' := Exists.some sorry /-- `right_to_max j j'` is an arbitrarily choice of morphism from `j'` to `max j j'`, whose existence is ensured by `is_filtered`. -/ def right_to_max {C : Type u} [category C] [is_filtered C] (j : C) (j' : C) : j' ⟶ max j j' := Exists.some sorry /-- `coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ def coeq {C : Type u} [category C] [is_filtered C] {j : C} {j' : C} (f : j ⟶ j') (f' : j ⟶ j') : C := Exists.some sorry /-- `coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ def coeq_hom {C : Type u} [category C] [is_filtered C] {j : C} {j' : C} (f : j ⟶ j') (f' : j ⟶ j') : j' ⟶ coeq f f' := Exists.some sorry /-- `coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that `f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. -/ @[simp] theorem coeq_condition_assoc {C : Type u} [category C] [is_filtered C] {j : C} {j' : C} (f : j ⟶ j') (f' : j ⟶ j') {X' : C} : ∀ (f'_1 : coeq f f' ⟶ X'), f ≫ coeq_hom f f' ≫ f'_1 = f' ≫ coeq_hom f f' ≫ f'_1 := sorry /-- Any finite collection of objects in a filtered category has an object "to the right". -/ theorem sup_objs_exists {C : Type u} [category C] [is_filtered C] (O : finset C) : ∃ (S : C), ∀ {X : C}, X ∈ O → Nonempty (X ⟶ S) := sorry /-- Given any `finset` of objects `{X, ...}` and indexed collection of `finset`s of morphisms `{f, ...}` in `C`, there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`, such that the triangles commute: `f ≫ T X = T Y`, for `f : X ⟶ Y` in the `finset`. -/ theorem sup_exists {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) : ∃ (S : C), ∃ (T : {X : C} → X ∈ O → (X ⟶ S)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}, psigma.mk X (psigma.mk Y (psigma.mk mX (psigma.mk mY f))) ∈ H → f ≫ T mY = T mX := sorry /-- An arbitrary choice of object "to the right" of a finite collection of objects `O` and morphisms `H`, making all the triangles commute. -/ def sup {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) : C := Exists.some (sup_exists O H) /-- The morphisms to `sup O H`. -/ def to_sup {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) {X : C} (m : X ∈ O) : X ⟶ sup O H := Exists.some sorry X m /-- The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute. -/ theorem to_sup_commutes {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) {X : C} {Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y} (mf : psigma.mk X (psigma.mk Y (psigma.mk mX (psigma.mk mY f))) ∈ H) : f ≫ to_sup O H mY = to_sup O H mX := Exists.some_spec (Exists.some_spec (sup_exists O H)) X Y mX mY f mf /-- If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`, there exists a cocone over `F`. -/ theorem cocone_nonempty {C : Type u} [category C] [is_filtered C] {J : Type v} [small_category J] [fin_category J] (F : J ⥤ C) : Nonempty (limits.cocone F) := sorry /-- An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`. -/ def cocone {C : Type u} [category C] [is_filtered C] {J : Type v} [small_category J] [fin_category J] (F : J ⥤ C) : limits.cocone F := nonempty.some (cocone_nonempty F) /-- If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered. -/ theorem of_right_adjoint {C : Type u} [category C] [is_filtered C] {D : Type u₁} [category D] {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D := mk /-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/ theorem of_is_right_adjoint {C : Type u} [category C] [is_filtered C] {D : Type u₁} [category D] (R : C ⥤ D) [is_right_adjoint R] : is_filtered D := of_right_adjoint (adjunction.of_right_adjoint R) /-- Being filtered is preserved by equivalence of categories. -/ theorem of_equivalence {C : Type u} [category C] [is_filtered C] {D : Type u₁} [category D] (h : C ≌ D) : is_filtered D := of_right_adjoint (equivalence.to_adjunction (equivalence.symm h)) end Mathlib
ec4e45d265ff91add726cea03c01e9c548229c26
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/simple.lean
544a488f7055517fb0ac342b4e5a8fb0033896f1
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
8,679
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import category_theory.limits.shapes.zero_morphisms import category_theory.limits.shapes.kernels import category_theory.abelian.basic import category_theory.subobject.lattice import order.atoms /-! # Simple objects We define simple objects in any category with zero morphisms. A simple object is an object `Y` such that any monomorphism `f : X ⟶ Y` is either an isomorphism or zero (but not both). This is formalized as a `Prop` valued typeclass `simple X`. In some contexts, especially representation theory, simple objects are called "irreducibles". If a morphism `f` out of a simple object is nonzero and has a kernel, then that kernel is zero. (We state this as `kernel.ι f = 0`, but should add `kernel f ≅ 0`.) When the category is abelian, being simple is the same as being cosimple (although we do not state a separate typeclass for this). As a consequence, any nonzero epimorphism out of a simple object is an isomorphism, and any nonzero morphism into a simple object has trivial cokernel. We show that any simple object is indecomposable. -/ noncomputable theory open category_theory.limits namespace category_theory universes v u variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms C] /-- An object is simple if monomorphisms into it are (exclusively) either isomorphisms or zero. -/ class simple (X : C) : Prop := (mono_is_iso_iff_nonzero : ∀ {Y : C} (f : Y ⟶ X) [mono f], is_iso f ↔ (f ≠ 0)) /-- A nonzero monomorphism to a simple object is an isomorphism. -/ lemma is_iso_of_mono_of_nonzero {X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : f ≠ 0) : is_iso f := (simple.mono_is_iso_iff_nonzero f).mpr w lemma simple.of_iso {X Y : C} [simple Y] (i : X ≅ Y) : simple X := { mono_is_iso_iff_nonzero := λ Z f m, begin resetI, haveI : mono (f ≫ i.hom) := mono_comp _ _, split, { introsI h w, haveI j : is_iso (f ≫ i.hom), apply_instance, rw simple.mono_is_iso_iff_nonzero at j, unfreezingI { subst w, }, simpa using j, }, { intro h, haveI j : is_iso (f ≫ i.hom), { apply is_iso_of_mono_of_nonzero, intro w, apply h, simpa using (cancel_mono i.inv).2 w, }, rw [←category.comp_id f, ←i.hom_inv_id, ←category.assoc], apply_instance, }, end } lemma kernel_zero_of_nonzero_from_simple {X Y : C} [simple X] {f : X ⟶ Y} [has_kernel f] (w : f ≠ 0) : kernel.ι f = 0 := begin classical, by_contra, haveI := is_iso_of_mono_of_nonzero h, exact w (eq_zero_of_epi_kernel f), end /-- A nonzero morphism `f` to a simple object is an epimorphism (assuming `f` has an image, and `C` has equalizers). -/ -- See also `mono_of_nonzero_from_simple`, which requires `preadditive C`. lemma epi_of_nonzero_to_simple [has_equalizers C] {X Y : C} [simple Y] {f : X ⟶ Y} [has_image f] (w : f ≠ 0) : epi f := begin rw ←image.fac f, haveI : is_iso (image.ι f) := is_iso_of_mono_of_nonzero (λ h, w (eq_zero_of_image_eq_zero h)), apply epi_comp, end lemma mono_to_simple_zero_of_not_iso {X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : is_iso f → false) : f = 0 := begin classical, by_contra, exact w (is_iso_of_mono_of_nonzero h) end lemma id_nonzero (X : C) [simple.{v} X] : 𝟙 X ≠ 0 := (simple.mono_is_iso_iff_nonzero (𝟙 X)).mp (by apply_instance) instance (X : C) [simple.{v} X] : nontrivial (End X) := nontrivial_of_ne 1 0 (id_nonzero X) section lemma simple.not_is_zero (X : C) [simple X] : ¬ is_zero X := by simpa [limits.is_zero.iff_id_eq_zero] using id_nonzero X variable [has_zero_object C] open_locale zero_object variables (C) /-- We don't want the definition of 'simple' to include the zero object, so we check that here. -/ lemma zero_not_simple [simple (0 : C)] : false := (simple.mono_is_iso_iff_nonzero (0 : (0 : C) ⟶ (0 : C))).mp ⟨⟨0, by tidy⟩⟩ rfl end end -- We next make the dual arguments, but for this we must be in an abelian category. section abelian variables [abelian C] /-- In an abelian category, an object satisfying the dual of the definition of a simple object is simple. -/ lemma simple_of_cosimple (X : C) (h : ∀ {Z : C} (f : X ⟶ Z) [epi f], is_iso f ↔ (f ≠ 0)) : simple X := ⟨λ Y f I, begin classical, fsplit, { introsI, have hx := cokernel.π_of_epi f, by_contra, substI h, exact (h _).mp (cokernel.π_of_zero _ _) hx }, { intro hf, suffices : epi f, { exactI is_iso_of_mono_of_epi _ }, apply preadditive.epi_of_cokernel_zero, by_contra h', exact cokernel_not_iso_of_nonzero hf ((h _).mpr h') } end⟩ /-- A nonzero epimorphism from a simple object is an isomorphism. -/ lemma is_iso_of_epi_of_nonzero {X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : f ≠ 0) : is_iso f := begin -- `f ≠ 0` means that `kernel.ι f` is not an iso, and hence zero, and hence `f` is a mono. haveI : mono f := preadditive.mono_of_kernel_zero (mono_to_simple_zero_of_not_iso (kernel_not_iso_of_nonzero w)), exact is_iso_of_mono_of_epi f, end lemma cokernel_zero_of_nonzero_to_simple {X Y : C} [simple Y] {f : X ⟶ Y} (w : f ≠ 0) : cokernel.π f = 0 := begin classical, by_contradiction h, haveI := is_iso_of_epi_of_nonzero h, exact w (eq_zero_of_mono_cokernel f), end lemma epi_from_simple_zero_of_not_iso {X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : is_iso f → false) : f = 0 := begin classical, by_contra, exact w (is_iso_of_epi_of_nonzero h), end end abelian section indecomposable variables [preadditive C] [has_binary_biproducts C] -- There are another three potential variations of this lemma, -- but as any one suffices to prove `indecomposable_of_simple` we will not give them all. lemma biprod.is_iso_inl_iff_is_zero (X Y : C) : is_iso (biprod.inl : X ⟶ X ⊞ Y) ↔ is_zero Y := begin rw [biprod.is_iso_inl_iff_id_eq_fst_comp_inl, ←biprod.total, add_right_eq_self], split, { intro h, replace h := h =≫ biprod.snd, simpa [←is_zero.iff_split_epi_eq_zero (biprod.snd : X ⊞ Y ⟶ Y)] using h, }, { intro h, rw is_zero.iff_split_epi_eq_zero (biprod.snd : X ⊞ Y ⟶ Y) at h, rw [h, zero_comp], }, end /-- Any simple object in a preadditive category is indecomposable. -/ lemma indecomposable_of_simple (X : C) [simple X] : indecomposable X := ⟨simple.not_is_zero X, λ Y Z i, begin refine or_iff_not_imp_left.mpr (λ h, _), rw is_zero.iff_split_mono_eq_zero (biprod.inl : Y ⟶ Y ⊞ Z) at h, change biprod.inl ≠ 0 at h, rw ←(simple.mono_is_iso_iff_nonzero biprod.inl) at h, { rwa biprod.is_iso_inl_iff_is_zero at h, }, { exact simple.of_iso i.symm, }, { apply_instance, }, end⟩ end indecomposable section subobject variables [has_zero_morphisms C] [has_zero_object C] open_locale zero_object open subobject instance {X : C} [simple X] : nontrivial (subobject X) := nontrivial_of_not_is_zero (simple.not_is_zero X) instance {X : C} [simple X] : is_simple_order (subobject X) := { eq_bot_or_eq_top := begin rintro ⟨⟨⟨(Y : C), ⟨⟨⟩⟩, (f : Y ⟶ X)⟩, (m : mono f)⟩⟩, resetI, change mk f = ⊥ ∨ mk f = ⊤, by_cases h : f = 0, { exact or.inl (mk_eq_bot_iff_zero.mpr h), }, { refine or.inr ((is_iso_iff_mk_eq_top _).mp ((simple.mono_is_iso_iff_nonzero f).mpr h)), } end, } /-- If `X` has subobject lattice `{⊥, ⊤}`, then `X` is simple. -/ lemma simple_of_is_simple_order_subobject (X : C) [is_simple_order (subobject X)] : simple X := begin split, introsI, split, { introI i, rw subobject.is_iso_iff_mk_eq_top at i, intro w, rw ←subobject.mk_eq_bot_iff_zero at w, exact is_simple_order.bot_ne_top (w.symm.trans i), }, { intro i, rcases is_simple_order.eq_bot_or_eq_top (subobject.mk f) with h|h, { rw subobject.mk_eq_bot_iff_zero at h, exact false.elim (i h), }, { exact (subobject.is_iso_iff_mk_eq_top _).mpr h, }, } end /-- `X` is simple iff it has subobject lattice `{⊥, ⊤}`. -/ lemma simple_iff_subobject_is_simple_order (X : C) : simple X ↔ is_simple_order (subobject X) := ⟨by { introI h, apply_instance, }, by { introI h, exact simple_of_is_simple_order_subobject X, }⟩ /-- A subobject is simple iff it is an atom in the subobject lattice. -/ lemma subobject_simple_iff_is_atom {X : C} (Y : subobject X) : simple (Y : C) ↔ is_atom Y := (simple_iff_subobject_is_simple_order _).trans ((order_iso.is_simple_order_iff (subobject_order_iso Y)).trans set.is_simple_order_Iic_iff_is_atom) end subobject end category_theory
88218b655bd27453087612c5658a2804478f9782
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/ns.lean
a1448a39879a35396439982cb093774d996add5c
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
266
lean
constant nat : Type.{1} constant f : nat → nat namespace foo constant int : Type.{1} constant f : int → int constant a : nat constant i : int check _root_.f a check f i end foo open foo constants a : nat constants i : int check f a check f i
ad4abc7bf3d4f9c956b5f0cf5ad8b5ec98d575f8
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Init/Data/List/Basic.lean
aef2e871e1548e17c868713cdec14f61073198fa
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
29,072
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.SimpLemmas import Init.Data.Nat.Basic set_option linter.missingDocs true -- keep it documented open Decidable List universe u v w variable {α : Type u} {β : Type v} {γ : Type w} namespace List instance : GetElem (List α) Nat α fun as i => i < as.length where getElem as i h := as.get ⟨i, h⟩ @[simp] theorem cons_getElem_zero (a : α) (as : List α) (h : 0 < (a :: as).length) : getElem (a :: as) 0 h = a := by rfl @[simp] theorem cons_getElem_succ (a : α) (as : List α) (i : Nat) (h : i + 1 < (a :: as).length) : getElem (a :: as) (i+1) h = getElem as i (Nat.lt_of_succ_lt_succ h) := by rfl theorem length_add_eq_lengthTRAux (as : List α) (n : Nat) : as.length + n = as.lengthTRAux n := by induction as generalizing n with | nil => simp [length, lengthTRAux] | cons a as ih => simp [length, lengthTRAux, ← ih, Nat.succ_add] rfl @[csimp] theorem length_eq_lengthTR : @List.length = @List.lengthTR := by apply funext; intro α; apply funext; intro as simp [lengthTR, ← length_add_eq_lengthTRAux] @[simp] theorem length_nil : length ([] : List α) = 0 := rfl /-- Auxiliary for `List.reverse`. `List.reverseAux l r = l.reverse ++ r`, but it is defined directly. -/ def reverseAux : List α → List α → List α | [], r => r | a::l, r => reverseAux l (a::r) /-- `O(|as|)`. Reverse of a list: * `[1, 2, 3, 4].reverse = [4, 3, 2, 1]` Note that because of the "functional but in place" optimization implemented by Lean's compiler, this function works without any allocations provided that the input list is unshared: it simply walks the linked list and reverses all the node pointers. -/ def reverse (as : List α) : List α := reverseAux as [] theorem reverseAux_reverseAux_nil (as bs : List α) : reverseAux (reverseAux as bs) [] = reverseAux bs as := by induction as generalizing bs with | nil => rfl | cons a as ih => simp [reverseAux, ih] theorem reverseAux_reverseAux (as bs cs : List α) : reverseAux (reverseAux as bs) cs = reverseAux bs (reverseAux (reverseAux as []) cs) := by induction as generalizing bs cs with | nil => rfl | cons a as ih => simp [reverseAux, ih (a::bs), ih [a]] @[simp] theorem reverse_reverse (as : List α) : as.reverse.reverse = as := by simp [reverse]; rw [reverseAux_reverseAux_nil]; rfl /-- `O(|xs|)`: append two lists. `[1, 2, 3] ++ [4, 5] = [1, 2, 3, 4, 5]`. It takes time proportional to the first list. -/ protected def append : (xs ys : List α) → List α | [], bs => bs | a::as, bs => a :: List.append as bs /-- Tail-recursive version of `List.append`. -/ def appendTR (as bs : List α) : List α := reverseAux as.reverse bs @[csimp] theorem append_eq_appendTR : @List.append = @appendTR := by apply funext; intro α; apply funext; intro as; apply funext; intro bs simp [appendTR, reverse] induction as with | nil => rfl | cons a as ih => simp [reverseAux, List.append, ih, reverseAux_reverseAux] instance : Append (List α) := ⟨List.append⟩ @[simp] theorem nil_append (as : List α) : [] ++ as = as := rfl @[simp] theorem append_nil (as : List α) : as ++ [] = as := by induction as with | nil => rfl | cons a as ih => simp_all [HAppend.hAppend, Append.append, List.append] @[simp] theorem cons_append (a : α) (as bs : List α) : (a::as) ++ bs = a::(as ++ bs) := rfl @[simp] theorem List.append_eq (as bs : List α) : List.append as bs = as ++ bs := rfl theorem append_assoc (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by induction as with | nil => rfl | cons a as ih => simp [ih] theorem append_cons (as : List α) (b : α) (bs : List α) : as ++ b :: bs = as ++ [b] ++ bs := by induction as with | nil => simp | cons a as ih => simp [ih] instance : EmptyCollection (List α) := ⟨List.nil⟩ /-- `O(|l|)`. `erase l a` removes the first occurrence of `a` from `l`. * `erase [1, 5, 3, 2, 5] 5 = [1, 3, 2, 5]` * `erase [1, 5, 3, 2, 5] 6 = [1, 5, 3, 2, 5]` -/ protected def erase {α} [BEq α] : List α → α → List α | [], _ => [] | a::as, b => match a == b with | true => as | false => a :: List.erase as b /-- `O(i)`. `eraseIdx l i` removes the `i`'th element of the list `l`. * `erase [a, b, c, d, e] 0 = [b, c, d, e]` * `erase [a, b, c, d, e] 1 = [a, c, d, e]` * `erase [a, b, c, d, e] 5 = [a, b, c, d, e]` -/ def eraseIdx : List α → Nat → List α | [], _ => [] | _::as, 0 => as | a::as, n+1 => a :: eraseIdx as n /-- `O(1)`. `isEmpty l` is true if the list is empty. * `isEmpty [] = true` * `isEmpty [a] = false` * `isEmpty [a, b] = false` -/ def isEmpty : List α → Bool | [] => true | _ :: _ => false /-- `O(|l|)`. `map f l` applies `f` to each element of the list. * `map f [a, b, c] = [f a, f b, f c]` -/ @[specialize] def map (f : α → β) : List α → List β | [] => [] | a::as => f a :: map f as /-- Tail-recursive version of `List.map`. -/ @[inline] def mapTR (f : α → β) (as : List α) : List β := loop as [] where @[specialize] loop : List α → List β → List β | [], bs => bs.reverse | a::as, bs => loop as (f a :: bs) theorem reverseAux_eq_append (as bs : List α) : reverseAux as bs = reverseAux as [] ++ bs := by induction as generalizing bs with | nil => simp [reverseAux] | cons a as ih => simp [reverseAux] rw [ih (a :: bs), ih [a], append_assoc] rfl @[simp] theorem reverse_nil : reverse ([] : List α) = [] := rfl @[simp] theorem reverse_cons (a : α) (as : List α) : reverse (a :: as) = reverse as ++ [a] := by simp [reverse, reverseAux] rw [← reverseAux_eq_append] @[simp] theorem reverse_append (as bs : List α) : (as ++ bs).reverse = bs.reverse ++ as.reverse := by induction as generalizing bs with | nil => simp | cons a as ih => simp [ih]; rw [append_assoc] theorem mapTR_loop_eq (f : α → β) (as : List α) (bs : List β) : mapTR.loop f as bs = bs.reverse ++ map f as := by induction as generalizing bs with | nil => simp [mapTR.loop, map] | cons a as ih => simp [mapTR.loop, map] rw [ih (f a :: bs), reverse_cons, append_assoc] rfl @[csimp] theorem map_eq_mapTR : @map = @mapTR := funext fun α => funext fun β => funext fun f => funext fun as => by simp [mapTR, mapTR_loop_eq] /-- `O(|join L|)`. `join L` concatenates all the lists in `L` into one list. * `join [[a], [], [b, c], [d, e, f]] = [a, b, c, d, e, f]` -/ def join : List (List α) → List α | [] => [] | a :: as => a ++ join as /-- `O(|l|)`. `filterMap f l` takes a function `f : α → Option β` and applies it to each element of `l`; the resulting non-`none` values are collected to form the output list. ``` filterMap (fun x => if x > 2 then some (2 * x) else none) [1, 2, 5, 2, 7, 7] = [10, 14, 14] ``` -/ @[specialize] def filterMap (f : α → Option β) : List α → List β | [] => [] | a::as => match f a with | none => filterMap f as | some b => b :: filterMap f as /-- `O(|l|)`. `filter f l` returns the list of elements in `l` for which `f` returns true. ``` filter (· > 2) [1, 2, 5, 2, 7, 7] = [5, 7, 7] ``` -/ def filter (p : α → Bool) : List α → List α | [] => [] | a::as => match p a with | true => a :: filter p as | false => filter p as /-- Tail-recursive version of `List.filter`. -/ @[inline] def filterTR (p : α → Bool) (as : List α) : List α := loop as [] where @[specialize] loop : List α → List α → List α | [], rs => rs.reverse | a::as, rs => match p a with | true => loop as (a::rs) | false => loop as rs theorem filterTR_loop_eq (p : α → Bool) (as bs : List α) : filterTR.loop p as bs = bs.reverse ++ filter p as := by induction as generalizing bs with | nil => simp [filterTR.loop, filter] | cons a as ih => simp [filterTR.loop, filter] split next => rw [ih, reverse_cons, append_assoc]; simp next => rw [ih] @[csimp] theorem filter_eq_filterTR : @filter = @filterTR := by apply funext; intro α; apply funext; intro p; apply funext; intro as simp [filterTR, filterTR_loop_eq] /-- `O(|l|)`. `partition p l` calls `p` on each element of `l`, partitioning the list into two lists `(l_true, l_false)` where `l_true` has the elements where `p` was true and `l_false` has the elements where `p` is false. `partition p l = (filter p l, filter (not ∘ p) l)`, but it is slightly more efficient since it only has to do one pass over the list. ``` partition (· > 2) [1, 2, 5, 2, 7, 7] = ([5, 7, 7], [1, 2, 2]) ``` -/ @[inline] def partition (p : α → Bool) (as : List α) : List α × List α := loop as ([], []) where @[specialize] loop : List α → List α × List α → List α × List α | [], (bs, cs) => (bs.reverse, cs.reverse) | a::as, (bs, cs) => match p a with | true => loop as (a::bs, cs) | false => loop as (bs, a::cs) /-- `O(|l|)`. `dropWhile p l` removes elements from the list until it finds the first element for which `p` returns false; this element and everything after it is returned. ``` dropWhile (· < 4) [1, 3, 2, 4, 2, 7, 4] = [4, 2, 7, 4] ``` -/ def dropWhile (p : α → Bool) : List α → List α | [] => [] | a::l => match p a with | true => dropWhile p l | false => a::l /-- `O(|l|)`. `find? p l` returns the first element for which `p` returns true, or `none` if no such element is found. * `find? (· < 5) [7, 6, 5, 8, 1, 2, 6] = some 1` * `find? (· < 1) [7, 6, 5, 8, 1, 2, 6] = none` -/ def find? (p : α → Bool) : List α → Option α | [] => none | a::as => match p a with | true => some a | false => find? p as /-- `O(|l|)`. `findSome? f l` applies `f` to each element of `l`, and returns the first non-`none` result. * `findSome? (fun x => if x < 5 then some (10 * x) else none) [7, 6, 5, 8, 1, 2, 6] = some 10` -/ def findSome? (f : α → Option β) : List α → Option β | [] => none | a::as => match f a with | some b => some b | none => findSome? f as /-- `O(|l|)`. `replace l a b` replaces the first element in the list equal to `a` with `b`. * `replace [1, 4, 2, 3, 3, 7] 3 6 = [1, 4, 2, 6, 3, 7]` * `replace [1, 4, 2, 3, 3, 7] 5 6 = [1, 4, 2, 3, 3, 7]` -/ def replace [BEq α] : List α → α → α → List α | [], _, _ => [] | a::as, b, c => match a == b with | true => c::as | false => a :: replace as b c /-- `O(|l|)`. `elem a l` or `l.contains a` is true if there is an element in `l` equal to `a`. * `elem 3 [1, 4, 2, 3, 3, 7] = true` * `elem 5 [1, 4, 2, 3, 3, 7] = false` -/ def elem [BEq α] (a : α) : List α → Bool | [] => false | b::bs => match a == b with | true => true | false => elem a bs /-- `notElem a l` is `!(elem a l)`. -/ def notElem [BEq α] (a : α) (as : List α) : Bool := !(as.elem a) @[inherit_doc elem] abbrev contains [BEq α] (as : List α) (a : α) : Bool := elem a as /-- `a ∈ l` is a predicate which asserts that `a` is in the list `l`. Unlike `elem`, this uses `=` instead of `==` and is suited for mathematical reasoning. * `a ∈ [x, y, z] ↔ a = x ∨ a = y ∨ a = z` -/ inductive Mem (a : α) : List α → Prop /-- The head of a list is a member: `a ∈ a :: as`. -/ | head (as : List α) : Mem a (a::as) /-- A member of the tail of a list is a member of the list: `a ∈ l → a ∈ b :: l`. -/ | tail (b : α) {as : List α} : Mem a as → Mem a (b::as) instance : Membership α (List α) where mem := Mem theorem mem_of_elem_eq_true [DecidableEq α] {a : α} {as : List α} : elem a as = true → a ∈ as := by match as with | [] => simp [elem] | a'::as => simp [elem] split next h => intros; simp [BEq.beq] at h; subst h; apply Mem.head next _ => intro h; exact Mem.tail _ (mem_of_elem_eq_true h) theorem elem_eq_true_of_mem [DecidableEq α] {a : α} {as : List α} (h : a ∈ as) : elem a as = true := by induction h with | head _ => simp [elem] | tail _ _ ih => simp [elem]; split; rfl; assumption instance [DecidableEq α] (a : α) (as : List α) : Decidable (a ∈ as) := decidable_of_decidable_of_iff (Iff.intro mem_of_elem_eq_true elem_eq_true_of_mem) theorem mem_append_of_mem_left {a : α} {as : List α} (bs : List α) : a ∈ as → a ∈ as ++ bs := by intro h induction h with | head => apply Mem.head | tail => apply Mem.tail; assumption theorem mem_append_of_mem_right {b : α} {bs : List α} (as : List α) : b ∈ bs → b ∈ as ++ bs := by intro h induction as with | nil => simp [h] | cons => apply Mem.tail; assumption /-- `O(|l|^2)`. Erase duplicated elements in the list. Keeps the first occurrence of duplicated elements. * `eraseDups [1, 3, 2, 2, 3, 5] = [1, 3, 2, 5]` -/ def eraseDups {α} [BEq α] (as : List α) : List α := loop as [] where loop : List α → List α → List α | [], bs => bs.reverse | a::as, bs => match bs.elem a with | true => loop as bs | false => loop as (a::bs) /-- `O(|l|)`. Erase repeated adjacent elements. Keeps the first occurrence of each run. * `eraseReps [1, 3, 2, 2, 2, 3, 5] = [1, 3, 2, 3, 5]` -/ def eraseReps {α} [BEq α] : List α → List α | [] => [] | a::as => loop a as [] where loop {α} [BEq α] : α → List α → List α → List α | a, [], rs => (a::rs).reverse | a, a'::as, rs => match a == a' with | true => loop a as rs | false => loop a' as (a::rs) /-- `O(|l|)`. `span p l` splits the list `l` into two parts, where the first part contains the longest initial segment for which `p` returns true and the second part is everything else. * `span (· > 5) [6, 8, 9, 5, 2, 9] = ([6, 8, 9], [5, 2, 9])` * `span (· > 10) [6, 8, 9, 5, 2, 9] = ([6, 8, 9, 5, 2, 9], [])` -/ @[inline] def span (p : α → Bool) (as : List α) : List α × List α := loop as [] where @[specialize] loop : List α → List α → List α × List α | [], rs => (rs.reverse, []) | a::as, rs => match p a with | true => loop as (a::rs) | false => (rs.reverse, a::as) /-- `O(|l|)`. `groupBy R l` splits `l` into chains of elements such that adjacent elements are related by `R`. * `groupBy (·==·) [1, 1, 2, 2, 2, 3, 2] = [[1, 1], [2, 2, 2], [3], [2]]` * `groupBy (·<·) [1, 2, 5, 4, 5, 4, 1] = [[1, 2, 5], [4, 5], [4], [1]]` -/ @[specialize] def groupBy (R : α → α → Bool) : List α → List (List α) | [] => [] | a::as => loop as [[a]] where @[specialize] loop : List α → List (List α) → List (List α) | a::as, (ag::g)::gs => match R ag a with | true => loop as ((a::ag::g)::gs) | false => loop as ([a]::(ag::g).reverse::gs) | _, gs => gs.reverse /-- `O(|l|)`. `lookup a l` treats `l : List (α × β)` like an association list, and returns the first `β` value corresponding to an `α` value in the list equal to `a`. * `lookup 3 [(1, 2), (3, 4), (3, 5)] = some 4` * `lookup 2 [(1, 2), (3, 4), (3, 5)] = none` -/ def lookup [BEq α] : α → List (α × β) → Option β | _, [] => none | a, (k,b)::es => match a == k with | true => some b | false => lookup a es /-- `O(|xs|)`. Computes the "set difference" of lists, by filtering out all elements of `xs` which are also in `ys`. * `removeAll [1, 1, 5, 1, 2, 4, 5] [1, 2, 2] = [5, 4, 5]` -/ def removeAll [BEq α] (xs ys : List α) : List α := xs.filter (fun x => ys.notElem x) /-- `O(min n |xs|)`. Removes the first `n` elements of `xs`. * `drop 0 [a, b, c, d, e] = [a, b, c, d, e]` * `drop 3 [a, b, c, d, e] = [d, e]` * `drop 6 [a, b, c, d, e] = []` -/ def drop : Nat → List α → List α | 0, a => a | _+1, [] => [] | n+1, _::as => drop n as @[simp] theorem drop_nil : ([] : List α).drop i = [] := by cases i <;> rfl theorem get_drop_eq_drop (as : List α) (i : Nat) (h : i < as.length) : as[i] :: as.drop (i+1) = as.drop i := match as, i with | _::_, 0 => rfl | _::_, i+1 => get_drop_eq_drop _ i _ /-- `O(min n |xs|)`. Returns the first `n` elements of `xs`, or the whole list if `n` is too large. * `take 0 [a, b, c, d, e] = []` * `take 3 [a, b, c, d, e] = [a, b, c]` * `take 6 [a, b, c, d, e] = [a, b, c, d, e]` -/ def take : Nat → List α → List α | 0, _ => [] | _+1, [] => [] | n+1, a::as => a :: take n as /-- `O(|xs|)`. Returns the longest initial segment of `xs` for which `p` returns true. * `takeWhile (· > 5) [7, 6, 4, 8] = [7, 6]` * `takeWhile (· > 5) [7, 6, 6, 8] = [7, 6, 6, 8]` -/ def takeWhile (p : α → Bool) : (xs : List α) → List α | [] => [] | hd :: tl => match p hd with | true => hd :: takeWhile p tl | false => [] /-- `O(|l|)`. Applies function `f` to all of the elements of the list, from right to left. * `foldr f init [a, b, c] = f a <| f b <| f c <| init` -/ @[specialize] def foldr (f : α → β → β) (init : β) : List α → β | [] => init | a :: l => f a (foldr f init l) /-- `O(|l|)`. Returns true if `p` is true for any element of `l`. * `any p [a, b, c] = p a || p b || p c` -/ @[inline] def any (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a || r) false l /-- `O(|l|)`. Returns true if `p` is true for every element of `l`. * `any p [a, b, c] = p a && p b && p c` -/ @[inline] def all (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a && r) true l /-- `O(|l|)`. Returns true if `true` is an element of the list of booleans `l`. * `or [a, b, c] = a || b || c` -/ def or (bs : List Bool) : Bool := bs.any id /-- `O(|l|)`. Returns true if every element of `l` is the value `true`. * `and [a, b, c] = a && b && c` -/ def and (bs : List Bool) : Bool := bs.all id /-- `O(min |xs| |ys|)`. Applies `f` to the two lists in parallel, stopping at the shorter list. * `zipWith f [x₁, x₂, x₃] [y₁, y₂, y₃, y₄] = [f x₁ y₁, f x₂ y₂, f x₃ y₃]` -/ @[specialize] def zipWith (f : α → β → γ) : (xs : List α) → (ys : List β) → List γ | x::xs, y::ys => f x y :: zipWith f xs ys | _, _ => [] /-- `O(min |xs| |ys|)`. Combines the two lists into a list of pairs, with one element from each list. The longer list is truncated to match the shorter list. * `zip [x₁, x₂, x₃] [y₁, y₂, y₃, y₄] = [(x₁, y₁), (x₂, y₂), (x₃, y₃)]` -/ def zip : List α → List β → List (Prod α β) := zipWith Prod.mk /-- `O(|l|)`. Separates a list of pairs into two lists containing the first components and second components. * `unzip [(x₁, y₁), (x₂, y₂), (x₃, y₃)] = ([x₁, x₂, x₃], [y₁, y₂, y₃])` -/ def unzip : List (α × β) → List α × List β | [] => ([], []) | (a, b) :: t => match unzip t with | (al, bl) => (a::al, b::bl) /-- `O(n)`. `range n` is the numbers from `0` to `n` exclusive, in increasing order. * `range 5 = [0, 1, 2, 3, 4]` -/ def range (n : Nat) : List Nat := loop n [] where loop : Nat → List Nat → List Nat | 0, ns => ns | n+1, ns => loop n (n::ns) /-- `O(n)`. `iota n` is the numbers from `1` to `n` inclusive, in decreasing order. * `iota 5 = [5, 4, 3, 2, 1]` -/ def iota : Nat → List Nat | 0 => [] | m@(n+1) => m :: iota n /-- Tail-recursive version of `iota`. -/ def iotaTR (n : Nat) : List Nat := let rec go : Nat → List Nat → List Nat | 0, r => r.reverse | m@(n+1), r => go n (m::r) go n [] @[csimp] theorem iota_eq_iotaTR : @iota = @iotaTR := have aux (n : Nat) (r : List Nat) : iotaTR.go n r = r.reverse ++ iota n := by induction n generalizing r with | zero => simp [iota, iotaTR.go] | succ n ih => simp [iota, iotaTR.go, ih, append_assoc] funext fun n => by simp [iotaTR, aux] /-- `O(|l|)`. `enumFrom n l` is like `enum` but it allows you to specify the initial index. * `enumFrom 5 [a, b, c] = [(5, a), (6, b), (7, c)]` -/ def enumFrom : Nat → List α → List (Nat × α) | _, [] => nil | n, x :: xs => (n, x) :: enumFrom (n + 1) xs /-- `O(|l|)`. `enum l` pairs up each element with its index in the list. * `enum [a, b, c] = [(0, a), (1, b), (2, c)]` -/ def enum : List α → List (Nat × α) := enumFrom 0 /-- `O(|l|)`. `intersperse sep l` alternates `sep` and the elements of `l`: * `intersperse sep [] = []` * `intersperse sep [a] = [a]` * `intersperse sep [a, b] = [a, sep, b]` * `intersperse sep [a, b, c] = [a, sep, b, sep, c]` -/ def intersperse (sep : α) : List α → List α | [] => [] | [x] => [x] | x::xs => x :: sep :: intersperse sep xs /-- `O(|xs|)`. `intercalate sep xs` alternates `sep` and the elements of `xs`: * `intercalate sep [] = []` * `intercalate sep [a] = a` * `intercalate sep [a, b] = a ++ sep ++ b` * `intercalate sep [a, b, c] = a ++ sep ++ b ++ sep ++ c` -/ def intercalate (sep : List α) (xs : List (List α)) : List α := join (intersperse sep xs) /-- `bind xs f` is the bind operation of the list monad. It applies `f` to each element of `xs` to get a list of lists, and then concatenates them all together. * `[2, 3, 2].bind range = [0, 1, 0, 1, 2, 0, 1]` -/ @[inline] protected def bind {α : Type u} {β : Type v} (a : List α) (b : α → List β) : List β := join (map b a) /-- `pure x = [x]` is the `pure` operation of the list monad. -/ @[inline] protected def pure {α : Type u} (a : α) : List α := [a] /-- The lexicographic order on lists. `[] < a::as`, and `a::as < b::bs` if `a < b` or if `a` and `b` are equivalent and `as < bs`. -/ inductive lt [LT α] : List α → List α → Prop where /-- `[]` is the smallest element in the order. -/ | nil (b : α) (bs : List α) : lt [] (b::bs) /-- If `a < b` then `a::as < b::bs`. -/ | head {a : α} (as : List α) {b : α} (bs : List α) : a < b → lt (a::as) (b::bs) /-- If `a` and `b` are equivalent and `as < bs`, then `a::as < b::bs`. -/ | tail {a : α} {as : List α} {b : α} {bs : List α} : ¬ a < b → ¬ b < a → lt as bs → lt (a::as) (b::bs) instance [LT α] : LT (List α) := ⟨List.lt⟩ instance hasDecidableLt [LT α] [h : DecidableRel (α:=α) (·<·)] : (l₁ l₂ : List α) → Decidable (l₁ < l₂) | [], [] => isFalse (fun h => nomatch h) | [], _::_ => isTrue (List.lt.nil _ _) | _::_, [] => isFalse (fun h => nomatch h) | a::as, b::bs => match h a b with | isTrue h₁ => isTrue (List.lt.head _ _ h₁) | isFalse h₁ => match h b a with | isTrue h₂ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ h₂' _ => absurd h₂ h₂') | isFalse h₂ => match hasDecidableLt as bs with | isTrue h₃ => isTrue (List.lt.tail h₁ h₂ h₃) | isFalse h₃ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ _ h₃' => absurd h₃' h₃) /-- The lexicographic order on lists. -/ @[reducible] protected def le [LT α] (a b : List α) : Prop := ¬ b < a instance [LT α] : LE (List α) := ⟨List.le⟩ instance [LT α] [DecidableRel ((· < ·) : α → α → Prop)] : (l₁ l₂ : List α) → Decidable (l₁ ≤ l₂) := fun _ _ => inferInstanceAs (Decidable (Not _)) /-- `isPrefixOf l₁ l₂` returns `true` Iff `l₁` is a prefix of `l₂`. That is, there exists a `t` such that `l₂ == l₁ ++ t`. -/ def isPrefixOf [BEq α] : List α → List α → Bool | [], _ => true | _, [] => false | a::as, b::bs => a == b && isPrefixOf as bs /-- `isPrefixOf? l₁ l₂` returns `some t` when `l₂ == l₁ ++ t`. -/ def isPrefixOf? [BEq α] : List α → List α → Option (List α) | [], l₂ => some l₂ | _, [] => none | (x₁ :: l₁), (x₂ :: l₂) => if x₁ == x₂ then isPrefixOf? l₁ l₂ else none /-- `isSuffixOf l₁ l₂` returns `true` Iff `l₁` is a suffix of `l₂`. That is, there exists a `t` such that `l₂ == t ++ l₁`. -/ def isSuffixOf [BEq α] (l₁ l₂ : List α) : Bool := isPrefixOf l₁.reverse l₂.reverse /-- `isSuffixOf? l₁ l₂` returns `some t` when `l₂ == t ++ l₁`.-/ def isSuffixOf? [BEq α] (l₁ l₂ : List α) : Option (List α) := Option.map List.reverse <| isPrefixOf? l₁.reverse l₂.reverse /-- `O(min |as| |bs|)`. Returns true if `as` and `bs` have the same length, and they are pairwise related by `eqv`. -/ @[specialize] def isEqv : (as bs : List α) → (eqv : α → α → Bool) → Bool | [], [], _ => true | a::as, b::bs, eqv => eqv a b && isEqv as bs eqv | _, _, _ => false /-- The equality relation on lists asserts that they have the same length and they are pairwise `BEq`. -/ protected def beq [BEq α] : List α → List α → Bool | [], [] => true | a::as, b::bs => a == b && List.beq as bs | _, _ => false instance [BEq α] : BEq (List α) := ⟨List.beq⟩ /-- `replicate n a` is `n` copies of `a`: * `replicate 5 a = [a, a, a, a, a]` -/ @[simp] def replicate : (n : Nat) → (a : α) → List α | 0, _ => [] | n+1, a => a :: replicate n a /-- Tail-recursive version of `List.replicate`. -/ def replicateTR {α : Type u} (n : Nat) (a : α) : List α := let rec loop : Nat → List α → List α | 0, as => as | n+1, as => loop n (a::as) loop n [] theorem replicateTR_loop_replicate_eq (a : α) (m n : Nat) : replicateTR.loop a n (replicate m a) = replicate (n + m) a := by induction n generalizing m with simp [replicateTR.loop] | succ n ih => simp [Nat.succ_add]; exact ih (m+1) @[csimp] theorem replicate_eq_replicateTR : @List.replicate = @List.replicateTR := by apply funext; intro α; apply funext; intro n; apply funext; intro a exact (replicateTR_loop_replicate_eq _ 0 n).symm /-- Removes the last element of the list. * `dropLast [] = []` * `dropLast [a] = []` * `dropLast [a, b, c] = [a, b]` -/ def dropLast {α} : List α → List α | [] => [] | [_] => [] | a::as => a :: dropLast as @[simp] theorem length_replicate (n : Nat) (a : α) : (replicate n a).length = n := by induction n <;> simp_all @[simp] theorem length_concat (as : List α) (a : α) : (concat as a).length = as.length + 1 := by induction as with | nil => rfl | cons _ xs ih => simp [concat, ih] @[simp] theorem length_set (as : List α) (i : Nat) (a : α) : (as.set i a).length = as.length := by induction as generalizing i with | nil => rfl | cons x xs ih => cases i with | zero => rfl | succ i => simp [set, ih] @[simp] theorem length_dropLast_cons (a : α) (as : List α) : (a :: as).dropLast.length = as.length := by match as with | [] => rfl | b::bs => have ih := length_dropLast_cons b bs simp[dropLast, ih] @[simp] theorem length_append (as bs : List α) : (as ++ bs).length = as.length + bs.length := by induction as with | nil => simp | cons _ as ih => simp [ih, Nat.succ_add] @[simp] theorem length_map (as : List α) (f : α → β) : (as.map f).length = as.length := by induction as with | nil => simp [List.map] | cons _ as ih => simp [List.map, ih] @[simp] theorem length_reverse (as : List α) : (as.reverse).length = as.length := by induction as with | nil => rfl | cons a as ih => simp [ih] /-- Returns the largest element of the list, if it is not empty. * `[].maximum? = none` * `[4].maximum? = some 4` * `[1, 4, 2, 10, 6].maximum? = some 10` -/ def maximum? [Max α] : List α → Option α | [] => none | a::as => some <| as.foldl max a /-- Returns the smallest element of the list, if it is not empty. * `[].maximum? = none` * `[4].maximum? = some 4` * `[1, 4, 2, 10, 6].maximum? = some 1` -/ def minimum? [Min α] : List α → Option α | [] => none | a::as => some <| as.foldl min a instance [BEq α] [LawfulBEq α] : LawfulBEq (List α) where eq_of_beq {as bs} := by induction as generalizing bs with | nil => intro h; cases bs <;> first | rfl | contradiction | cons a as ih => cases bs with | nil => intro h; contradiction | cons b bs => simp [show (a::as == b::bs) = (a == b && as == bs) from rfl] intro ⟨h₁, h₂⟩ exact ⟨h₁, ih h₂⟩ rfl {as} := by induction as with | nil => rfl | cons a as ih => simp [BEq.beq, List.beq, LawfulBEq.rfl]; exact ih theorem of_concat_eq_concat {as bs : List α} {a b : α} (h : as.concat a = bs.concat b) : as = bs ∧ a = b := by match as, bs with | [], [] => simp [concat] at h; simp [h] | [_], [] => simp [concat] at h | _::_::_, [] => simp [concat] at h | [], [_] => simp [concat] at h | [], _::_::_ => simp [concat] at h | _::_, _::_ => simp [concat] at h; simp [h]; apply of_concat_eq_concat h.2 theorem concat_eq_append (as : List α) (a : α) : as.concat a = as ++ [a] := by induction as <;> simp [concat, *] theorem drop_eq_nil_of_le {as : List α} {i : Nat} (h : as.length ≤ i) : as.drop i = [] := by match as, i with | [], i => simp | _::_, 0 => simp at h | _::as, i+1 => simp at h; exact @drop_eq_nil_of_le as i (Nat.le_of_succ_le_succ h) end List
e81c35e86038134505ee43135594461e2ef2dcb2
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/normed/group/basic.lean
3915dc614e70365596e5d1e398f2e06f4af9e566
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,159
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 -/ import order.liminf_limsup import topology.algebra.uniform_group import topology.metric_space.algebra import topology.metric_space.isometry import topology.sequences /-! # Normed (semi)groups In this file we define four classes: * `has_norm`, `has_nnnorm`: auxiliary classes endowing a type `α` with a function `norm : α → ℝ` (notation: `∥x∥`) and `nnnorm : α → ℝ≥0` (notation: `∥x∥₊`), respectively; * `semi_normed_group`: a seminormed group is an additive group with a norm and a pseudo metric space structures that agree with each other: `∀ x y, dist x y = ∥x - y∥`; * `normed_group`: a normed group is an additive group with a norm and a metric space structures that agree with each other: `∀ x y, dist x y = ∥x - y∥`. We also prove basic properties of (semi)normed groups and provide some instances. ## Tags normed group -/ variables {α ι E F : Type*} noncomputable theory open filter metric open_locale topological_space big_operators nnreal ennreal uniformity pointwise /-- Auxiliary class, endowing a type `E` with a function `norm : E → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (E : Type*) := (norm : E → ℝ) export has_norm (norm) notation `∥` e `∥` := norm e /-- A seminormed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a pseudometric space structure. -/ class semi_normed_group (E : Type*) extends has_norm E, add_comm_group E, pseudo_metric_space E := (dist_eq : ∀ x y : E, dist x y = norm (x - y)) /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (E : Type*) extends has_norm E, add_comm_group E, metric_space E := (dist_eq : ∀ x y : E, dist x y = norm (x - y)) /-- A normed group is a seminormed group. -/ @[priority 100] -- see Note [lower instance priority] instance normed_group.to_semi_normed_group [h : normed_group E] : semi_normed_group E := { .. h } /-- Construct a seminormed group from a translation invariant pseudodistance. -/ def semi_normed_group.of_add_dist [has_norm E] [add_comm_group E] [pseudo_metric_space E] (H1 : ∀ x : E, ∥x∥ = dist x 0) (H2 : ∀ x y z : E, dist x y ≤ dist (x + z) (y + z)) : semi_normed_group E := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x - y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def semi_normed_group.of_add_dist' [has_norm E] [add_comm_group E] [pseudo_metric_space E] (H1 : ∀ x : E, ∥x∥ = dist x 0) (H2 : ∀ x y z : E, dist (x + z) (y + z) ≤ dist x y) : semi_normed_group E := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x - y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A seminormed group can be built from a seminorm that satisfies algebraic properties. This is formalised in this structure. -/ structure semi_normed_group.core (E : Type*) [add_comm_group E] [has_norm E] : Prop := (norm_zero : ∥(0 : E)∥ = 0) (triangle : ∀ x y : E, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : E, ∥-x∥ = ∥x∥) /-- Constructing a seminormed group from core properties of a seminorm, i.e., registering the pseudodistance and the pseudometric space structure from the seminorm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`). -/ noncomputable def semi_normed_group.of_core (E : Type*) [add_comm_group E] [has_norm E] (C : semi_normed_group.core E) : semi_normed_group E := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, by simp [C.norm_zero], dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } instance : normed_group punit := { norm := function.const _ 0, dist_eq := λ _ _, rfl, } @[simp] lemma punit.norm_eq_zero (r : punit) : ∥r∥ = 0 := rfl instance : normed_group ℝ := { norm := λ x, |x|, dist_eq := assume x y, rfl } lemma real.norm_eq_abs (r : ℝ) : ∥r∥ = |r| := rfl section semi_normed_group variables [semi_normed_group E] [semi_normed_group F] lemma dist_eq_norm (g h : E) : dist g h = ∥g - h∥ := semi_normed_group.dist_eq _ _ lemma dist_eq_norm' (g h : E) : dist g h = ∥h - g∥ := by rw [dist_comm, dist_eq_norm] @[simp] lemma dist_zero_right (g : E) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] @[simp] lemma dist_zero_left : dist (0 : E) = norm := funext $ λ g, by rw [dist_comm, dist_zero_right] lemma tendsto_norm_cocompact_at_top [proper_space E] : tendsto norm (cocompact E) at_top := by simpa only [dist_zero_right] using tendsto_dist_right_cocompact_at_top (0 : E) lemma norm_sub_rev (g h : E) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : E) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : E) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : E) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : E) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : E) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : E) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := by simpa only [sub_eq_add_neg] using dist_add_right _ _ _ /-- **Triangle inequality** for the norm. -/ lemma norm_add_le (g h : E) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : E} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : E) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : E} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : E) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [sub_eq_add_neg, dist_neg_neg] using dist_add_add_le g₁ (-g₂) h₁ (-h₂) lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : E} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : E) : |dist g₁ h₁ - dist g₂ h₂| ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : E) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_zero : ∥(0 : E)∥ = 0 := by rw [← dist_zero_right, dist_self] @[nontriviality] lemma norm_of_subsingleton [subsingleton E] (x : E) : ∥x∥ = 0 := by rw [subsingleton.elim x 0, norm_zero] lemma norm_sum_le (s : finset ι) (f : ι → E) : ∥∑ i in s, f i∥ ≤ ∑ i in s, ∥f i∥ := s.le_sum_of_subadditive norm norm_zero norm_add_le f lemma norm_sum_le_of_le (s : finset ι) {f : ι → E} {n : ι → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥∑ b in s, f b∥ ≤ ∑ b in s, n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) lemma dist_sum_sum_le_of_le (s : finset ι) {f g : ι → E} {d : ι → ℝ} (h : ∀ b ∈ s, dist (f b) (g b) ≤ d b) : dist (∑ b in s, f b) (∑ b in s, g b) ≤ ∑ b in s, d b := begin simp only [dist_eq_norm, ← finset.sum_sub_distrib] at *, exact norm_sum_le_of_le s h end lemma dist_sum_sum_le (s : finset ι) (f g : ι → E) : dist (∑ b in s, f b) (∑ b in s, g b) ≤ ∑ b in s, dist (f b) (g b) := dist_sum_sum_le_of_le s (λ _ _, le_rfl) lemma norm_sub_le (g h : E) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : E} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : E) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : E) : |∥g∥ - ∥h∥| ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : E) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : E) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_le_insert (u v : E) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ := calc ∥v∥ = ∥u - (u - v)∥ : by abel ... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _ lemma norm_le_insert' (u v : E) : ∥u∥ ≤ ∥v∥ + ∥u - v∥ := by { rw norm_sub_rev, exact norm_le_insert v u } lemma norm_le_add_norm_add (u v : E) : ∥u∥ ≤ ∥u + v∥ + ∥v∥ := calc ∥u∥ = ∥u + v - v∥ : by rw add_sub_cancel ... ≤ ∥u + v∥ + ∥v∥ : norm_sub_le _ _ lemma ball_zero_eq (ε : ℝ) : ball (0 : E) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma mem_ball_iff_norm {g h : E} {r : ℝ} : h ∈ ball g r ↔ ∥h - g∥ < r := by rw [mem_ball, dist_eq_norm] lemma add_mem_ball_iff_norm {g h : E} {r : ℝ} : g + h ∈ ball g r ↔ ∥h∥ < r := by rw [mem_ball_iff_norm, add_sub_cancel'] lemma mem_ball_iff_norm' {g h : E} {r : ℝ} : h ∈ ball g r ↔ ∥g - h∥ < r := by rw [mem_ball', dist_eq_norm] @[simp] lemma mem_ball_zero_iff {ε : ℝ} {x : E} : x ∈ ball (0 : E) ε ↔ ∥x∥ < ε := by rw [mem_ball, dist_zero_right] lemma mem_closed_ball_iff_norm {g h : E} {r : ℝ} : h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r := by rw [mem_closed_ball, dist_eq_norm] lemma add_mem_closed_ball_iff_norm {g h : E} {r : ℝ} : g + h ∈ closed_ball g r ↔ ∥h∥ ≤ r := by rw [mem_closed_ball_iff_norm, add_sub_cancel'] lemma mem_closed_ball_iff_norm' {g h : E} {r : ℝ} : h ∈ closed_ball g r ↔ ∥g - h∥ ≤ r := by rw [mem_closed_ball', dist_eq_norm] lemma norm_le_of_mem_closed_ball {g h : E} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_le_norm_add_const_of_dist_le {a b : E} {c : ℝ} (h : dist a b ≤ c) : ∥a∥ ≤ ∥b∥ + c := norm_le_of_mem_closed_ball h lemma norm_lt_of_mem_ball {g h : E} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_norm_add_const_of_dist_lt {a b : E} {c : ℝ} (h : dist a b < c) : ∥a∥ < ∥b∥ + c := norm_lt_of_mem_ball h lemma bounded_iff_forall_norm_le {s : set E} : bounded s ↔ ∃ C, ∀ x ∈ s, ∥x∥ ≤ C := by simpa only [set.subset_def, mem_closed_ball_iff_norm, sub_zero] using bounded_iff_subset_ball (0 : E) lemma preimage_add_ball (x y : E) (r : ℝ) : ((+) y) ⁻¹' (ball x r) = ball (x - y) r := begin ext z, simp only [dist_eq_norm, set.mem_preimage, mem_ball], abel end lemma preimage_add_closed_ball (x y : E) (r : ℝ) : ((+) y) ⁻¹' (closed_ball x r) = closed_ball (x - y) r := begin ext z, simp only [dist_eq_norm, set.mem_preimage, mem_closed_ball], abel end @[simp] lemma mem_sphere_iff_norm (v w : E) (r : ℝ) : w ∈ sphere v r ↔ ∥w - v∥ = r := by simp [dist_eq_norm] @[simp] lemma mem_sphere_zero_iff_norm {w : E} {r : ℝ} : w ∈ sphere (0:E) r ↔ ∥w∥ = r := by simp [dist_eq_norm] @[simp] lemma norm_eq_of_mem_sphere {r : ℝ} (x : sphere (0:E) r) : ∥(x:E)∥ = r := mem_sphere_zero_iff_norm.mp x.2 lemma preimage_add_sphere (x y : E) (r : ℝ) : ((+) y) ⁻¹' (sphere x r) = sphere (x - y) r := begin ext z, simp only [set.mem_preimage, mem_sphere_iff_norm], abel end lemma ne_zero_of_norm_pos {g : E} : 0 < ∥ g ∥ → g ≠ 0 := begin intros hpos hzero, rw [hzero, norm_zero] at hpos, exact lt_irrefl 0 hpos, end lemma nonzero_of_mem_sphere {r : ℝ} (hr : 0 < r) (x : sphere (0:E) r) : (x:E) ≠ 0 := begin refine ne_zero_of_norm_pos _, rwa norm_eq_of_mem_sphere x, end lemma nonzero_of_mem_unit_sphere (x : sphere (0:E) 1) : (x:E) ≠ 0 := by { apply nonzero_of_mem_sphere, norm_num } /-- We equip the sphere, in a seminormed group, with a formal operation of negation, namely the antipodal map. -/ instance {r : ℝ} : has_neg (sphere (0:E) r) := { neg := λ w, ⟨-↑w, by simp⟩ } @[simp] lemma coe_neg_sphere {r : ℝ} (v : sphere (0:E) r) : (((-v) : sphere _ _) : E) = - (v:E) := rfl namespace isometric -- TODO This material is superseded by similar constructions such as -- `affine_isometry_equiv.const_vadd`; deduplicate /-- Addition `y ↦ y + x` as an `isometry`. -/ protected def add_right (x : E) : E ≃ᵢ E := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_right _ _ _, .. equiv.add_right x } @[simp] lemma add_right_to_equiv (x : E) : (isometric.add_right x).to_equiv = equiv.add_right x := rfl @[simp] lemma coe_add_right (x : E) : (isometric.add_right x : E → E) = λ y, y + x := rfl lemma add_right_apply (x y : E) : (isometric.add_right x : E → E) y = y + x := rfl @[simp] lemma add_right_symm (x : E) : (isometric.add_right x).symm = isometric.add_right (-x) := ext $ λ y, rfl /-- Addition `y ↦ x + y` as an `isometry`. -/ protected def add_left (x : E) : E ≃ᵢ E := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_left _ _ _, to_equiv := equiv.add_left x } @[simp] lemma add_left_to_equiv (x : E) : (isometric.add_left x).to_equiv = equiv.add_left x := rfl @[simp] lemma coe_add_left (x : E) : ⇑(isometric.add_left x) = (+) x := rfl @[simp] lemma add_left_symm (x : E) : (isometric.add_left x).symm = isometric.add_left (-x) := ext $ λ y, rfl variable (E) /-- Negation `x ↦ -x` as an `isometry`. -/ protected def neg : E ≃ᵢ E := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ x y, dist_neg_neg _ _, to_equiv := equiv.neg E } variable {E} @[simp] lemma neg_symm : (isometric.neg E).symm = isometric.neg E := rfl @[simp] lemma neg_to_equiv : (isometric.neg E).to_equiv = equiv.neg E := rfl @[simp] lemma coe_neg : ⇑(isometric.neg E) = has_neg.neg := rfl end isometric theorem normed_group.tendsto_nhds_zero {f : α → E} {l : filter α} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] lemma normed_group.tendsto_nhds_nhds {f : E → F} {x : E} {y : F} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm] lemma normed_group.cauchy_seq_iff [nonempty α] [semilattice_sup α] {u : α → E} : cauchy_seq u ↔ ∀ ε > 0, ∃ N, ∀ m n, N ≤ m → N ≤ n → ∥u m - u n∥ < ε := by simp [metric.cauchy_seq_iff, dist_eq_norm] lemma cauchy_seq.add {u v : ℕ → E} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (u + v) := begin rw normed_group.cauchy_seq_iff at *, intros ε ε_pos, rcases hu (ε/2) (half_pos ε_pos) with ⟨Nu, hNu⟩, rcases hv (ε/2) (half_pos ε_pos) with ⟨Nv, hNv⟩, use max Nu Nv, intros m n hm hn, replace hm := max_le_iff.mp hm, replace hn := max_le_iff.mp hn, calc ∥(u + v) m - (u + v) n∥ = ∥u m + v m - (u n + v n)∥ : rfl ... = ∥(u m - u n) + (v m - v n)∥ : by abel ... ≤ ∥u m - u n∥ + ∥v m - v n∥ : norm_add_le _ _ ... < ε : by linarith only [hNu m n hm.1 hn.1, hNv m n hm.2 hn.2] end open finset lemma cauchy_seq_sum_of_eventually_eq {u v : ℕ → E} {N : ℕ} (huv : ∀ n ≥ N, u n = v n) (hv : cauchy_seq (λ n, ∑ k in range (n+1), v k)) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin let d : ℕ → E := λ n, ∑ k in range (n + 1), (u k - v k), rw show (λ n, ∑ k in range (n + 1), u k) = d + (λ n, ∑ k in range (n + 1), v k), by { ext n, simp [d] }, have : ∀ n ≥ N, d n = d N, { intros n hn, dsimp [d], rw eventually_constant_sum _ hn, intros m hm, simp [huv m hm] }, exact (tendsto_at_top_of_eventually_const this).cauchy_seq.add hv end /-- A homomorphism `f` of seminormed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of (semi)normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.lipschitz_of_bound (f : E →+ F) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (real.to_nnreal C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma lipschitz_on_with_iff_norm_sub_le {f : E → F} {C : ℝ≥0} {s : set E} : lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm] lemma lipschitz_on_with.norm_sub_le {f : E → F} {C : ℝ≥0} {s : set E} (h : lipschitz_on_with C f s) {x y : E} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ := lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in lemma lipschitz_on_with.norm_sub_le_of_le {f : E → F} {C : ℝ≥0} {s : set E} (h : lipschitz_on_with C f s){x y : E} (x_in : x ∈ s) (y_in : y ∈ s) {d : ℝ} (hd : ∥x - y∥ ≤ d) : ∥f x - f y∥ ≤ C * d := (h.norm_sub_le x_in y_in).trans $ mul_le_mul_of_nonneg_left hd C.2 lemma lipschitz_with_iff_norm_sub_le {f : E → F} {C : ℝ≥0} : lipschitz_with C f ↔ ∀ x y, ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_with_iff_dist_le_mul, dist_eq_norm] alias lipschitz_with_iff_norm_sub_le ↔ lipschitz_with.norm_sub_le _ lemma lipschitz_with.norm_sub_le_of_le {f : E → F} {C : ℝ≥0} (h : lipschitz_with C f) {x y : E} {d : ℝ} (hd : ∥x - y∥ ≤ d) : ∥f x - f y∥ ≤ C * d := (h.norm_sub_le x y).trans $ mul_le_mul_of_nonneg_left hd C.2 /-- A homomorphism `f` of seminormed groups is continuous, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.continuous_of_bound (f : E →+ F) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous lemma is_compact.exists_bound_of_continuous_on [topological_space α] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : ∃ C, ∀ x ∈ s, ∥f x∥ ≤ C := begin have : bounded (f '' s) := (hs.image_of_continuous_on hf).bounded, rcases bounded_iff_forall_norm_le.1 this with ⟨C, hC⟩, exact ⟨C, λ x hx, hC _ (set.mem_image_of_mem _ hx)⟩, end lemma add_monoid_hom.isometry_iff_norm (f : E →+ F) : isometry f ↔ ∀ x, ∥f x∥ = ∥x∥ := begin simp only [isometry_emetric_iff_metric, dist_eq_norm, ← f.map_sub], refine ⟨λ h x, _, λ h x y, h _⟩, simpa using h x 0 end lemma add_monoid_hom.isometry_of_norm (f : E →+ F) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f := f.isometry_iff_norm.2 hf lemma controlled_sum_of_mem_closure {s : add_subgroup E} {g : E} (hg : g ∈ closure (s : set E)) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ v : ℕ → E, tendsto (λ n, ∑ i in range (n+1), v i) at_top (𝓝 g) ∧ (∀ n, v n ∈ s) ∧ ∥v 0 - g∥ < b 0 ∧ ∀ n > 0, ∥v n∥ < b n := begin obtain ⟨u : ℕ → E, u_in : ∀ n, u n ∈ s, lim_u : tendsto u at_top (𝓝 g)⟩ := mem_closure_iff_seq_limit.mp hg, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ∀ n ≥ n₀, ∥u n - g∥ < b 0, { have : {x | ∥x - g∥ < b 0} ∈ 𝓝 g, { simp_rw ← dist_eq_norm, exact metric.ball_mem_nhds _ (b_pos _) }, exact filter.tendsto_at_top'.mp lim_u _ this }, set z : ℕ → E := λ n, u (n + n₀), have lim_z : tendsto z at_top (𝓝 g) := lim_u.comp (tendsto_add_at_top_nat n₀), have mem_𝓤 : ∀ n, {p : E × E | ∥p.1 - p.2∥ < b (n + 1)} ∈ 𝓤 E := λ n, by simpa [← dist_eq_norm] using metric.dist_mem_uniformity (b_pos $ n+1), obtain ⟨φ : ℕ → ℕ, φ_extr : strict_mono φ, hφ : ∀ n, ∥z (φ $ n + 1) - z (φ n)∥ < b (n + 1)⟩ := lim_z.cauchy_seq.subseq_mem mem_𝓤, set w : ℕ → E := z ∘ φ, have hw : tendsto w at_top (𝓝 g), from lim_z.comp φ_extr.tendsto_at_top, set v : ℕ → E := λ i, if i = 0 then w 0 else w i - w (i - 1), refine ⟨v, tendsto.congr (finset.eq_sum_range_sub' w) hw , _, hn₀ _ (n₀.le_add_left _), _⟩, { rintro ⟨⟩, { change w 0 ∈ s, apply u_in }, { apply s.sub_mem ; apply u_in }, }, { intros l hl, obtain ⟨k, rfl⟩ : ∃ k, l = k+1, exact nat.exists_eq_succ_of_ne_zero (ne_of_gt hl), apply hφ }, end lemma controlled_sum_of_mem_closure_range {j : E →+ F} {h : F} (Hh : h ∈ (closure $ (j.range : set F))) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ g : ℕ → E, tendsto (λ n, ∑ i in range (n+1), j (g i)) at_top (𝓝 h) ∧ ∥j (g 0) - h∥ < b 0 ∧ ∀ n > 0, ∥j (g n)∥ < b n := begin rcases controlled_sum_of_mem_closure Hh b_pos with ⟨v, sum_v, v_in, hv₀, hv_pos⟩, choose g hg using v_in, change ∀ (n : ℕ), j (g n) = v n at hg, refine ⟨g, by simpa [← hg] using sum_v, by simpa [hg 0] using hv₀, λ n hn, by simpa [hg] using hv_pos n hn⟩ end section nnnorm /-- Auxiliary class, endowing a type `α` with a function `nnnorm : α → ℝ≥0`. -/ class has_nnnorm (E : Type*) := (nnnorm : E → ℝ≥0) export has_nnnorm (nnnorm) notation `∥`e`∥₊` := nnnorm e @[priority 100] -- see Note [lower instance priority] instance semi_normed_group.to_has_nnnorm : has_nnnorm E := ⟨λ a, ⟨norm a, norm_nonneg a⟩⟩ @[simp, norm_cast] lemma coe_nnnorm (a : E) : (∥a∥₊ : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : E) : nndist a b = ∥a - b∥₊ := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_zero : ∥(0 : E)∥₊ = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : E) : ∥g + h∥₊ ≤ ∥g∥₊ + ∥h∥₊ := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : E) : ∥-g∥₊ = ∥g∥₊ := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : E) : nndist ∥g∥₊ ∥h∥₊ ≤ ∥g - h∥₊ := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : E) : ennreal.of_real ∥x∥ = (∥x∥₊ : ℝ≥0∞) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : E) : edist x y = (∥x - y∥₊ : ℝ≥0∞) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : E) : edist x 0 = (∥x∥₊ : ℝ≥0∞) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma mem_emetric_ball_zero_iff {x : E} {r : ℝ≥0∞} : x ∈ emetric.ball (0 : E) r ↔ ↑∥x∥₊ < r := by rw [emetric.mem_ball, edist_eq_coe_nnnorm] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : E) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : E) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le (s : finset ι) (f : ι → E) : ∥∑ a in s, f a∥₊ ≤ ∑ a in s, ∥f a∥₊ := s.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le f lemma add_monoid_hom.lipschitz_of_bound_nnnorm (f : E →+ F) (C : ℝ≥0) (h : ∀ x, ∥f x∥₊ ≤ C * ∥x∥₊) : lipschitz_with C f := @real.to_nnreal_coe C ▸ f.lipschitz_of_bound C h end nnnorm namespace lipschitz_with variables [pseudo_emetric_space α] {K Kf Kg : ℝ≥0} {f g : α → E} lemma neg (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma add (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma sub (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg end lipschitz_with namespace antilipschitz_with variables [pseudo_emetric_space α] {K Kf Kg : ℝ≥0} {f g : α → E} lemma add_lipschitz_with (hf : antilipschitz_with Kf f) (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin letI : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space hf.edist_ne_top, refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], rw le_div_iff (nnreal.coe_pos.2 $ sub_pos_iff_lt.2 hK), rw [mul_comm, nnreal.coe_sub hK.le, sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end lemma add_sub_lipschitz_with (hf : antilipschitz_with Kf f) (hg : lipschitz_with Kg (g - f)) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ g := by simpa only [pi.sub_apply, add_sub_cancel'_right] using hf.add_lipschitz_with hg hK end antilipschitz_with /-- A group homomorphism from an `add_comm_group` to a `semi_normed_group` induces a `semi_normed_group` structure on the domain. See note [reducible non-instances] -/ @[reducible] def semi_normed_group.induced {E} [add_comm_group E] (f : E →+ F) : semi_normed_group E := { norm := λ x, ∥f x∥, dist_eq := λ x y, by simpa only [add_monoid_hom.map_sub, ← dist_eq_norm], .. pseudo_metric_space.induced f semi_normed_group.to_pseudo_metric_space, } /-- A subgroup of a seminormed group is also a seminormed group, with the restriction of the norm. -/ instance add_subgroup.semi_normed_group (s : add_subgroup E) : semi_normed_group s := semi_normed_group.induced s.subtype /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. -/ @[simp] lemma coe_norm_subgroup {E : Type*} [semi_normed_group E] {s : add_subgroup E} (x : s) : ∥x∥ = ∥(x:E)∥ := rfl /-- A submodule of a seminormed group is also a seminormed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.semi_normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : semi_normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `E` is equal to its norm in `s`. See note [implicit instance arguments]. -/ @[simp, norm_cast] lemma submodule.norm_coe {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ∥(x : E)∥ = ∥x∥ := rfl @[simp] lemma submodule.norm_mk {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : E) (hx : x ∈ s) : ∥(⟨x, hx⟩ : s)∥ = ∥x∥ := rfl /-- seminormed group instance on the product of two seminormed groups, using the sup norm. -/ instance prod.semi_normed_group : semi_normed_group (E × F) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : E × F), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.semi_norm_def (x : E × F) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnsemi_norm_def (x : E × F) : ∥x∥₊ = max (∥x.1∥₊) (∥x.2∥₊) := by { have := x.semi_norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma semi_norm_fst_le (x : E × F) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma semi_norm_snd_le (x : E × F) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma semi_norm_prod_le_iff {x : E × F} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- seminormed group instance on the product of finitely many seminormed groups, using the sup norm. -/ instance pi.semi_normed_group {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] : semi_normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, ∥f b∥₊) : ℝ≥0) : ℝ), dist_eq := assume x y, congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = ∥x a - y a∥₊, from nndist_eq_nnnorm _ _ } /-- The seminorm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_semi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The seminorm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_semi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma semi_norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_semi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_semi_norm_const [nonempty ι] [fintype ι] (a : E) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnsemi_norm_const [nonempty ι] [fintype ι] (a : E) : ∥(λ i : ι, a)∥₊ = ∥a∥₊ := nnreal.eq $ pi_semi_norm_const a lemma tendsto_iff_norm_tendsto_zero {f : α → E} {a : filter α} {b : E} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥f e - b∥) a (𝓝 0) := by { convert tendsto_iff_dist_tendsto_zero, simp [dist_eq_norm] } lemma is_bounded_under_of_tendsto {l : filter α} {f : α → E} {c : E} (h : filter.tendsto f l (𝓝 c)) : is_bounded_under (≤) l (λ x, ∥f x∥) := ⟨∥c∥ + 1, @tendsto.eventually α E f _ _ (λ k, ∥k∥ ≤ ∥c∥ + 1) h (filter.eventually_iff_exists_mem.mpr ⟨metric.closed_ball c 1, metric.closed_ball_mem_nhds c zero_lt_one, λ y hy, norm_le_norm_add_const_of_dist_le hy⟩)⟩ lemma tendsto_zero_iff_norm_tendsto_zero {f : α → E} {a : filter α} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥f e∥) a (𝓝 0) := by { rw [tendsto_iff_norm_tendsto_zero], simp only [sub_zero] } /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `g` which tends to `0`, then `f` tends to `0`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ lemma squeeze_zero_norm' {f : α → E} {g : α → ℝ} {t₀ : filter α} (h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := tendsto_zero_iff_norm_tendsto_zero.mpr (squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h') /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which tends to `0`, then `f` tends to `0`. -/ lemma squeeze_zero_norm {f : α → E} {g : α → ℝ} {t₀ : filter α} (h : ∀ n, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero_norm' (eventually_of_forall h) h' lemma tendsto_norm_sub_self (x : E) : tendsto (λ g : E, ∥g - x∥) (𝓝 x) (𝓝 0) := by simpa [dist_eq_norm] using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (x:E)) (𝓝 x) _) lemma tendsto_norm {x : E} : tendsto (λg : E, ∥g∥) (𝓝 x) (𝓝 ∥x∥) := by simpa using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (0:E)) _ _) lemma tendsto_norm_zero : tendsto (λg : E, ∥g∥) (𝓝 0) (𝓝 0) := by simpa using tendsto_norm_sub_self (0:E) @[continuity] lemma continuous_norm : continuous (λg:E, ∥g∥) := by simpa using continuous_id.dist (continuous_const : continuous (λ g, (0:E))) @[continuity] lemma continuous_nnnorm : continuous (λ (a : E), ∥a∥₊) := continuous_subtype_mk _ continuous_norm lemma lipschitz_with_one_norm : lipschitz_with 1 (norm : E → ℝ) := by simpa only [dist_zero_left] using lipschitz_with.dist_right (0 : E) lemma uniform_continuous_norm : uniform_continuous (norm : E → ℝ) := lipschitz_with_one_norm.uniform_continuous lemma uniform_continuous_nnnorm : uniform_continuous (λ (a : E), ∥a∥₊) := uniform_continuous_subtype_mk uniform_continuous_norm _ section variables {l : filter α} {f : α → E} {a : E} lemma filter.tendsto.norm (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto_norm.comp h lemma filter.tendsto.nnnorm (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥₊) l (𝓝 (∥a∥₊)) := tendsto.comp continuous_nnnorm.continuous_at h end section variables [topological_space α] {f : α → E} {s : set α} {a : α} {b : E} lemma continuous.norm (h : continuous f) : continuous (λ x, ∥f x∥) := continuous_norm.comp h lemma continuous.nnnorm (h : continuous f) : continuous (λ x, ∥f x∥₊) := continuous_nnnorm.comp h lemma continuous_at.norm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥) a := h.norm lemma continuous_at.nnnorm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥₊) a := h.nnnorm lemma continuous_within_at.norm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥) s a := h.norm lemma continuous_within_at.nnnorm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥₊) s a := h.nnnorm lemma continuous_on.norm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥) s := λ x hx, (h x hx).norm lemma continuous_on.nnnorm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥₊) s := λ x hx, (h x hx).nnnorm end /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter α} {f : α → E} (h : tendsto (λ y, ∥f y∥) l at_top) (x : E) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end @[priority 100] -- see Note [lower instance priority] instance semi_normed_group.has_lipschitz_add : has_lipschitz_add E := { lipschitz_add := ⟨2, lipschitz_with.prod_fst.add lipschitz_with.prod_snd⟩ } /-- A seminormed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group E := ⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩ @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group E := by apply_instance -- short-circuit type class inference lemma nat.norm_cast_le [has_one E] : ∀ n : ℕ, ∥(n : E)∥ ≤ n * ∥(1 : E)∥ | 0 := by simp | (n + 1) := by { rw [n.cast_succ, n.cast_succ, add_mul, one_mul], exact norm_add_le_of_le (nat.norm_cast_le n) le_rfl } lemma semi_normed_group.mem_closure_iff {s : set E} {x : E} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, ∥x - y∥ < ε := by simp [metric.mem_closure_iff, dist_eq_norm] lemma norm_le_zero_iff' [separated_space E] {g : E} : ∥g∥ ≤ 0 ↔ g = 0 := begin have : g = 0 ↔ g ∈ closure ({0} : set E), by simpa only [separated_space.out, mem_id_rel, sub_zero] using group_separation_rel g (0 : E), rw [this, semi_normed_group.mem_closure_iff], simp [forall_lt_iff_le'] end lemma norm_eq_zero_iff' [separated_space E] {g : E} : ∥g∥ = 0 ↔ g = 0 := begin conv_rhs { rw ← norm_le_zero_iff' }, split ; intro h, { rw h }, { exact le_antisymm h (norm_nonneg g) } end lemma norm_pos_iff' [separated_space E] {g : E} : 0 < ∥g∥ ↔ g ≠ 0 := by rw [← not_le, norm_le_zero_iff'] end semi_normed_group section normed_group /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm E] [add_comm_group E] [metric_space E] (H1 : ∀ x : E, ∥x∥ = dist x 0) (H2 : ∀ x y z : E, dist x y ≤ dist (x + z) (y + z)) : normed_group E := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (E : Type*) [add_comm_group E] [has_norm E] : Prop := (norm_eq_zero_iff : ∀ x : E, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : E, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : E, ∥-x∥ = ∥x∥) /-- The `semi_normed_group.core` induced by a `normed_group.core`. -/ lemma normed_group.core.to_semi_normed_group.core {E : Type*} [add_comm_group E] [has_norm E] (C : normed_group.core E) : semi_normed_group.core E := { norm_zero := (C.norm_eq_zero_iff 0).2 rfl, triangle := C.triangle, norm_neg := C.norm_neg } /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (E : Type*) [add_comm_group E] [has_norm E] (C : normed_group.core E) : normed_group E := { eq_of_dist_eq_zero := λ x y h, begin rw [dist_eq_norm] at h, exact sub_eq_zero.mp ((C.norm_eq_zero_iff _).1 h) end ..semi_normed_group.of_core E (normed_group.core.to_semi_normed_group.core C) } variables [normed_group E] [normed_group F] @[simp] lemma norm_eq_zero {g : E} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_pos_iff {g : E} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos @[simp] lemma norm_le_zero_iff {g : E} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw [← dist_zero_right], exact dist_le_zero } lemma eq_of_norm_sub_le_zero {g h : E} (a : ∥g - h∥ ≤ 0) : g = h := by rwa [← sub_eq_zero, ← norm_le_zero_iff] lemma eq_of_norm_sub_eq_zero {u v : E} (h : ∥u - v∥ = 0) : u = v := begin apply eq_of_dist_eq_zero, rwa dist_eq_norm end lemma norm_sub_eq_zero_iff {u v : E} : ∥u - v∥ = 0 ↔ u = v := begin convert dist_eq_zero, rwa dist_eq_norm end @[simp] lemma nnnorm_eq_zero {a : E} : ∥a∥₊ = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] /-- An injective group homomorphism from an `add_comm_group` to a `normed_group` induces a `normed_group` structure on the domain. See note [reducible non-instances]. -/ @[reducible] def normed_group.induced {E} [add_comm_group E] (f : E →+ F) (h : function.injective f) : normed_group E := { .. semi_normed_group.induced f, .. metric_space.induced f h normed_group.to_metric_space, } /-- A subgroup of a normed group is also a normed group, with the restriction of the norm. -/ instance add_subgroup.normed_group (s : add_subgroup E) : normed_group s := normed_group.induced s.subtype subtype.coe_injective /-- A submodule of a normed group is also a normed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { ..submodule.semi_normed_group s } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (E × F) := { ..prod.semi_normed_group } lemma prod.norm_def (x : E × F) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnnorm_def (x : E × F) : ∥x∥₊ = max (∥x.1∥₊) (∥x.2∥₊) := by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma norm_fst_le (x : E × F) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : E × F) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : E × F} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { ..pi.semi_normed_group } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The norm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_norm_const [nonempty ι] [fintype ι] (a : E) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnnorm_const [nonempty ι] [fintype ι] (a : E) : ∥(λ i : ι, a)∥₊ = ∥a∥₊ := nnreal.eq $ pi_norm_const a lemma tendsto_norm_nhds_within_zero : tendsto (norm : E → ℝ) (𝓝[{0}ᶜ] 0) (𝓝[set.Ioi 0] 0) := (continuous_norm.tendsto' (0 : E) 0 norm_zero).inf $ tendsto_principal_principal.2 $ λ x, norm_pos_iff.2 end normed_group
2b6afeb9d9dced073fea33740ad869a3cbbff02c
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/monoid_object.lean
4c751d0ca2ebdc62e49c6423b872acdaa038721b
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
8,064
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import .braided_monoidal_category open tactic.rewrite_search.metric open tactic.rewrite_search.strategy open tactic.rewrite_search.tracer universes v u namespace category_theory open monoidal_category class monoid_object {C : Sort u} (M : C) [monoidal_category.{v} C] := (unit : tensor_unit C ⟶ M) (product : M ⊗ M ⟶ M) (pentagon' : (associator M M M).hom ≫ ((𝟙 M) ⊗ product) ≫ product = (product ⊗ (𝟙 M)) ≫ product . obviously) (left_unit' : (left_unitor M).hom = (unit ⊗ (𝟙 M)) ≫ product . obviously) (right_unit' : (right_unitor M).hom = ((𝟙 M) ⊗ unit) ≫ product . obviously) restate_axiom monoid_object.pentagon' attribute [simp,search] monoid_object.pentagon restate_axiom monoid_object.left_unit' attribute [simp,search] monoid_object.left_unit restate_axiom monoid_object.right_unit' attribute [search] monoid_object.right_unit section open braided_monoidal_category open monoid_object @[reducible] def reassociate_and_braid_product {C : Sort u} (X Y : C) [braided_monoidal_category.{v} C] := (associator X Y (X ⊗ Y)).hom ≫ ((𝟙 X) ⊗ (associator Y X Y).inv) ≫ ((𝟙 X) ⊗ (braiding Y X).hom ⊗ (𝟙 Y)) ≫ ((𝟙 X) ⊗ (associator X Y Y).hom) ≫ (associator X X (Y ⊗ Y)).inv -- TODO: prove that the tensor product of two monoid objects is -- again a monoid object in a symmetric monoidal category. -- This is trivial on paper via string diagrams. -- Would it be possible to write a string diagram tactic? instance product_monoid_object_of_monoid_object {C : Sort u} (M N : C) [braided_monoidal_category.{v} C] [ℳ : monoid_object.{v} M] [𝒩 : monoid_object.{v} N] : monoid_object (M ⊗ N) := { unit := (left_unitor (tensor_unit C)).inv ≫ (ℳ.unit ⊗ 𝒩.unit), product := reassociate_and_braid_product M N ≫ (ℳ.product ⊗ 𝒩.product), pentagon' := sorry, left_unit' := sorry, right_unit' := sorry } end class monoid_morphism {C : Sort u} [monoidal_category.{v} C] {M M' : C} [monoid_object.{v} M] [monoid_object.{v} M'] (f : M ⟶ M') := (square' : (f ⊗ f) ≫ monoid_object.product M' = monoid_object.product M ≫ f . obviously) (triangle' : monoid_object.unit M ≫ f = monoid_object.unit M' . obviously) restate_axiom monoid_morphism.square' attribute [search] monoid_morphism.square restate_axiom monoid_morphism.triangle' attribute [search] monoid_morphism.triangle class is_commutative {C : Sort u} (M : C) [symmetric_monoidal_category.{v} C] [monoid_object M] := (symmetry' : (braided_monoidal_category.braiding M M).hom ≫ monoid_object.product M = monoid_object.product M) restate_axiom is_commutative.symmetry' attribute [search] is_commutative.symmetry' -- TODO: rephrase this section as a monoid object in the category C^{op}. section class comonoid_object {C : Sort u} (M : C) [monoidal_category.{v} C] := (counit : M ⟶ tensor_unit C) (coproduct : M ⟶ M ⊗ M) (copentagon' : coproduct ≫ ((𝟙 M) ⊗ coproduct) ≫ (associator M M M).inv = coproduct ≫ (coproduct ⊗ (𝟙 M)) . obviously) (left_counit' : (left_unitor M).inv = coproduct ≫ (counit ⊗ (𝟙 M)) . obviously) (right_counit' : (right_unitor M).inv = coproduct ≫ ((𝟙 M) ⊗ counit) . obviously) restate_axiom comonoid_object.copentagon' attribute [search] comonoid_object.copentagon restate_axiom comonoid_object.left_counit' attribute [search] comonoid_object.left_counit restate_axiom comonoid_object.right_counit' attribute [search] comonoid_object.right_counit class comonoid_morphism {C : Sort u} [monoidal_category.{v} C] {M M' : C} [comonoid_object.{v} M] [comonoid_object.{v} M'] (f : M ⟶ M') := (square' : comonoid_object.coproduct M ≫ (f ⊗ f) = f ≫ comonoid_object.coproduct M' . obviously) (triangle' : f ≫ comonoid_object.counit M' = comonoid_object.counit M . obviously) restate_axiom comonoid_morphism.square' attribute [search] comonoid_morphism.square restate_axiom comonoid_morphism.triangle' attribute [search] comonoid_morphism.triangle class is_cocommutative {C : Sort u} (M : C) [symmetric_monoidal_category.{v} C] [comonoid_object M] := (symmetry' : comonoid_object.coproduct M ≫ (braided_monoidal_category.braiding M M).hom = comonoid_object.coproduct M) restate_axiom is_cocommutative.symmetry' attribute [search] is_cocommutative.symmetry' end section open braided_monoidal_category class bimonoid_object {C : Sort u} (M : C) [braided_monoidal_category.{v} C] extends monoid_object.{v} M, comonoid_object.{v} M := (product_coproduct' : product ≫ coproduct = (coproduct ⊗ coproduct) ≫ (associator M M (M ⊗ M)).hom ≫ ((𝟙 M) ⊗ (associator M M M).inv) ≫ ((𝟙 M) ⊗ (braiding M M).hom ⊗ (𝟙 M)) ≫ ((𝟙 M) ⊗ (associator M M M).hom) ≫ (associator M M (M ⊗ M)).inv ≫ (product ⊗ product)) (product_counit' : product ≫ counit = (counit ⊗ counit) ≫ (left_unitor (tensor_unit C)).hom) (unit_coproduct' : unit ≫ coproduct = (left_unitor (tensor_unit C)).inv ≫ (unit ⊗ unit)) (unit_counit' : unit ≫ counit = 𝟙 (tensor_unit C)) restate_axiom bimonoid_object.product_coproduct' attribute [search] bimonoid_object.product_coproduct' restate_axiom bimonoid_object.product_counit' attribute [search] bimonoid_object.product_counit' restate_axiom bimonoid_object.unit_coproduct' attribute [search] bimonoid_object.unit_coproduct restate_axiom bimonoid_object.unit_counit' attribute [search] bimonoid_object.unit_counit class hopf_monoid_object {C : Sort u} (M : C) [braided_monoidal_category.{v} C] extends bimonoid_object.{v} M := (antipode : M ⟶ M) (antipode_property' : counit ≫ unit = coproduct ≫ ((𝟙 M) ⊗ antipode) ≫ product) restate_axiom hopf_monoid_object.antipode_property' attribute [search] hopf_monoid_object.antipode_property end class frobenius_object {C : Sort u} (M : C) [monoidal_category.{v} C] extends monoid_object.{v} M, comonoid_object.{v} M := (left_frobenius' : (coproduct ⊗ (𝟙 M)) ≫ (associator M M M).hom ≫ ((𝟙 M) ⊗ product) = (product ≫ coproduct) . obviously) (right_frobenius' : ((𝟙 M) ⊗ coproduct) ≫ (associator M M M).inv ≫ (product ⊗ (𝟙 M)) = (product ≫ coproduct) . obviously) restate_axiom frobenius_object.left_frobenius' attribute [search] frobenius_object.left_frobenius restate_axiom frobenius_object.right_frobenius' attribute [search] frobenius_object.right_frobenius class is_commutative_frobenius {C : Sort u} (M : C) [symmetric_monoidal_category.{v} C] [frobenius_object.{v} M] := (commutative : is_commutative M) (cocommutative : is_cocommutative M) class is_symmetric_frobenius {C : Sort u} (M : C) [symmetric_monoidal_category.{v} C] [frobenius_object.{v} M] := (symmetry' : (braided_monoidal_category.braiding M M).hom ≫ monoid_object.product M ≫ comonoid_object.counit M = monoid_object.product M ≫ comonoid_object.counit M . obviously) restate_axiom is_symmetric_frobenius.symmetry' attribute [search] is_symmetric_frobenius.symmetry class is_special {C : Sort u} (M : C) [monoidal_category.{v} C] [frobenius_object.{v} M] := (special' : comonoid_object.coproduct M ≫ monoid_object.product M = (𝟙 M)) restate_axiom is_special.special' attribute [search] is_special.special class is_extra {C : Sort u} (M : C) [monoidal_category.{v} C] [frobenius_object.{v} M] := (extra' : monoid_object.unit M ≫ comonoid_object.counit M = 𝟙 (tensor_unit C)) restate_axiom is_extra.extra' attribute [search] is_extra.extra structure special_commutative_frobenius_object {C : Sort u} (M : C) [symmetric_monoidal_category.{v} C] extends frobenius_object.{v} M := (special : is_special M) (commutative : is_commutative_frobenius M) end category_theory
2161c1b630ada137c77755de506ffcb3978ee070
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/coelambda.lean
d809d8f87c99c0ec7da942ab953c93466b682a62
[ "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
220
lean
new_frontend #eval #[2, 3, 1, 0].qsort fun a b => a < b #eval #[2, 3, 1, 0].qsort fun a b => let x := a; x < b #eval #[2, 3, 1, 0].qsort (· < ·) #eval #[2, 3, 1, 0].filter (· > 1) #eval #[2, 3, 1, 0].filter (2 > ·)
a87634b0075286adbfa54e45104672102f993c5a
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/Elab/Match.lean
4b0600b32e4428273185bd3ddfdf992ea6ab6eb6
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,355
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.Arg import Lean.Parser.Term import Lean.Elab.PatternVar namespace Lean.Elab.Term open Meta open Lean.Parser.Term 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 | _ => #[] builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind 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 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 isMatchValue e 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 _ => do if (← isProof e) then /- We mark nested proofs as inaccessible. This is fine due to proof irrelevance. We need this feature to be able to elaborate definitions such as: ``` def f : Fin 2 → Nat | 0 => 5 | 1 => 45 ``` -/ return Pattern.inaccessible e else 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
4d6eefc31b311a7c160571a7519c944debaf2540
d0664585e88edfefe384f2b01de54487029040bb
/solutions/entourages_from_pseudometric.lean
35a1463632af8a1ebfc456555dbfd55c873e4780
[]
no_license
ImperialCollegeLondon/uniform-structures
acf0a092d764925564595c59e7347e066d2a78ab
a41a170ef125b36bdac1e2201f54affa958d0349
refs/heads/master
1,668,088,958,039
1,592,495,127,000
1,592,495,127,000
269,964,470
2
0
null
null
null
null
UTF-8
Lean
false
false
3,757
lean
-- import the definitions of uniform space via entourages import uniform_structure.entourages -- import the definition of pseudometric space import pseudometric_space -- In this exercise we will show that a pseudometric on a set X -- gives rise to a collection of entourages for X -- This is a question about pseudometrics so let's put it -- in the pseudometric namespace open_locale classical namespace pseudometric -- Let X be a set (or a type), and let d be a pseudometric on X variables {X : Type} (d : X → X → ℝ) [is_pseudometric d] -- Define U ⊆ X × X to be an entourage if there exists ε > 0 such -- that d(x,y)≤ε → (x,y) ∈ U def entourages := {U : set (X × X) | ∃ ε > 0, ∀ x y : X, d x y ≤ ε → (x,y) ∈ U} -- this lemma is true by definition lemma mem_entourages (U : set (X × X)) : U ∈ entourages d ↔ ∃ ε > 0, ∀ x y : X, d x y ≤ ε → (x,y) ∈ U := iff.rfl -- The exerise is to show that the 5 axioms of a uniform space are -- satisfied. -- Hint: You can `rw mem_entourages` to change from `U ∈ entourages d` to the -- explicit epsilon definition. -- Hint: if `hU : U ∈ entourages d` then `obtain ⟨ε, hε, hεU⟩ := hU` will -- get you the ε which is a witness to U being an entourage for d. -- Axiom 1: the diagonal is in U lemma refl (U : set (X × X)) (hU : U ∈ entourages d) : ∀ (x : X), (x, x) ∈ U := begin intro x, have hx : d x x = 0, exact d_self d x, obtain ⟨ε, hε, hεU⟩ := hU, apply hεU, rw hx, linarith, end -- Axiom 2: anything bigger than an entourage is an entourage lemma bigger (U V : set (X × X)) (hU : U ∈ entourages d) (hUV : U ⊆ V) : V ∈ entourages d := begin rw mem_entourages, obtain ⟨ε, hε, hεU⟩ := hU, use ε, split, apply hε, tauto, end -- Axiom 3: Intersection of two entourages is an entourage lemma inter (U V : set (X × X)) (hU : U ∈ entourages d) (hV : V ∈ entourages d) : U ∩ V ∈ entourages d := begin rw mem_entourages, obtain ⟨ε1, hε1, hε1U⟩ := hU, obtain ⟨ε2, hε2, hε2V⟩ := hV, set e := min ε1 ε2 with he, use e, split, have h: e>0, simp, split, apply hε1, apply hε2, simp, split, apply hε1, apply hε2, simp, tauto, end /- -/ -- Axiom 4: the "square root" axiom. -- You'll need `mem_comp_ent` here (defined in the entourages file) lemma comp (U : set (X × X)) (hU : U ∈ entourages d) : ∃ (V : set (X × X)) (H : V ∈ entourages d), V ∘ V ⊆ U := begin obtain ⟨ε, hε, hεU⟩ := hU, use {z : X × X | d z.1 z.2 ≤ ε/2}, split, rw mem_entourages, use ε/2, split, linarith, tauto, intro x, intro h, have q: d x.1 x.2 ≤ ε, have s: ∃ z, (x.1, z) ∈ {z : X × X | d z.1 z.2 ≤ ε/2} ∧ (z, x.2) ∈ {z : X × X | d z.1 z.2 ≤ ε/2}, rw ← mem_comp_ent, apply h, obtain ⟨z, hz1, hz2⟩ := s, have p1: d x.1 z ≤ ε/2, apply hz1, have p2: d z x.2 ≤ ε/2, apply hz2, have p3 : d x.1 x.2 ≤ d x.1 z + d z x.2, apply d_triangle d, linarith, have p4: (x.1, x.2) ∈ U, apply hεU, apply q, cases x, apply p4, end -- Axiom 5: the "transpose" axiom. lemma symm (U : set (X × X)) (hU : U ∈ entourages d) : {z : X × X | (z.snd, z.fst) ∈ U} ∈ entourages d := begin rw mem_entourages, obtain ⟨ε, hε, hεU⟩ := hU, use ε, split, apply hε, intros x y, have hx : d x y = d y x, exact d_comm d x y, intro h, apply hεU, have q: d x y = d (x, y).snd (x, y).fst, apply hx, linarith, end definition to_entourages : uniform_space_entourage X := { entourages := entourages d, refl := refl d, bigger := bigger d, inter := inter d, comp := comp d, symm := symm d } end pseudometric
9c0db405e7130fa20bec59f8e5c3352822d801f5
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/matrix/block.lean
95b44c4b4d91e4afa8ae478411e57f82a7ed87b8
[ "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
15,835
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import data.matrix.basic /-! # Block Matrices ## Main definitions * `matrix.from_blocks`: build a block matrix out of 4 blocks * `matrix.to_blocks₁₁`, `matrix.to_blocks₁₂`, `matrix.to_blocks₂₁`, `matrix.to_blocks₂₂`: extract each of the four blocks from `matrix.from_blocks`. * `matrix.block_diagonal`: block diagonal of equally sized blocks * `matrix.block_diagonal'`: block diagonal of unequally sized blocks -/ variables {l m n o : Type*} [fintype l] [fintype m] [fintype n] [fintype o] variables {m' : o → Type*} [∀ i, fintype (m' i)] variables {n' : o → Type*} [∀ i, fintype (n' i)] variables {R : Type*} {S : Type*} {α : Type*} {β : Type*} open_locale matrix namespace matrix section block_matrices /-- We can form a single large matrix by flattening smaller 'block' matrices of compatible dimensions. -/ def from_blocks (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : matrix (n ⊕ o) (l ⊕ m) α := sum.elim (λ i, sum.elim (A i) (B i)) (λ i, sum.elim (C i) (D i)) @[simp] lemma from_blocks_apply₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : l) : from_blocks A B C D (sum.inl i) (sum.inl j) = A i j := rfl @[simp] lemma from_blocks_apply₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : m) : from_blocks A B C D (sum.inl i) (sum.inr j) = B i j := rfl @[simp] lemma from_blocks_apply₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : l) : from_blocks A B C D (sum.inr i) (sum.inl j) = C i j := rfl @[simp] lemma from_blocks_apply₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : m) : from_blocks A B C D (sum.inr i) (sum.inr j) = D i j := rfl /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "top left" submatrix. -/ def to_blocks₁₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n l α := λ i j, M (sum.inl i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "top right" submatrix. -/ def to_blocks₁₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n m α := λ i j, M (sum.inl i) (sum.inr j) /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "bottom left" submatrix. -/ def to_blocks₂₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o l α := λ i j, M (sum.inr i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "bottom right" submatrix. -/ def to_blocks₂₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o m α := λ i j, M (sum.inr i) (sum.inr j) lemma from_blocks_to_blocks (M : matrix (n ⊕ o) (l ⊕ m) α) : from_blocks M.to_blocks₁₁ M.to_blocks₁₂ M.to_blocks₂₁ M.to_blocks₂₂ = M := begin ext i j, rcases i; rcases j; refl, end @[simp] lemma to_blocks_from_blocks₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₁ = A := rfl @[simp] lemma to_blocks_from_blocks₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₂ = B := rfl @[simp] lemma to_blocks_from_blocks₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₁ = C := rfl @[simp] lemma to_blocks_from_blocks₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₂ = D := rfl lemma from_blocks_map (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (f : α → β) : (from_blocks A B C D).map f = from_blocks (A.map f) (B.map f) (C.map f) (D.map f) := begin ext i j, rcases i; rcases j; simp [from_blocks], end lemma from_blocks_transpose (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D)ᵀ = from_blocks Aᵀ Cᵀ Bᵀ Dᵀ := begin ext i j, rcases i; rcases j; simp [from_blocks], end lemma from_blocks_conj_transpose [has_star α] (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D)ᴴ = from_blocks Aᴴ Cᴴ Bᴴ Dᴴ := begin simp only [conj_transpose, from_blocks_transpose, from_blocks_map] end /-- Let `p` pick out certain rows and `q` pick out certain columns of a matrix `M`. Then `to_block M p q` is the corresponding block matrix. -/ def to_block (M : matrix m n α) (p : m → Prop) [decidable_pred p] (q : n → Prop) [decidable_pred q] : matrix {a // p a} {a // q a} α := M.minor coe coe @[simp] lemma to_block_apply (M : matrix m n α) (p : m → Prop) [decidable_pred p] (q : n → Prop) [decidable_pred q] (i : {a // p a}) (j : {a // q a}) : to_block M p q i j = M ↑i ↑j := rfl /-- Let `b` map rows and columns of a square matrix `M` to blocks. Then `to_square_block M b k` is the block `k` matrix. -/ def to_square_block (M : matrix m m α) {n : nat} (b : m → fin n) (k : fin n) : matrix {a // b a = k} {a // b a = k} α := M.minor coe coe @[simp] lemma to_square_block_def (M : matrix m m α) {n : nat} (b : m → fin n) (k : fin n) : to_square_block M b k = λ i j, M ↑i ↑j := rfl /-- Alternate version with `b : m → nat`. Let `b` map rows and columns of a square matrix `M` to blocks. Then `to_square_block' M b k` is the block `k` matrix. -/ def to_square_block' (M : matrix m m α) (b : m → nat) (k : nat) : matrix {a // b a = k} {a // b a = k} α := M.minor coe coe @[simp] lemma to_square_block_def' (M : matrix m m α) (b : m → nat) (k : nat) : to_square_block' M b k = λ i j, M ↑i ↑j := rfl /-- Let `p` pick out certain rows and columns of a square matrix `M`. Then `to_square_block_prop M p` is the corresponding block matrix. -/ def to_square_block_prop (M : matrix m m α) (p : m → Prop) [decidable_pred p] : matrix {a // p a} {a // p a} α := M.minor coe coe @[simp] lemma to_square_block_prop_def (M : matrix m m α) (p : m → Prop) [decidable_pred p] : to_square_block_prop M p = λ i j, M ↑i ↑j := rfl variables [semiring α] lemma from_blocks_smul (x : α) (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : x • (from_blocks A B C D) = from_blocks (x • A) (x • B) (x • C) (x • D) := begin ext i j, rcases i; rcases j; simp [from_blocks], end lemma from_blocks_add (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix n l α) (B' : matrix n m α) (C' : matrix o l α) (D' : matrix o m α) : (from_blocks A B C D) + (from_blocks A' B' C' D') = from_blocks (A + A') (B + B') (C + C') (D + D') := begin ext i j, rcases i; rcases j; refl, end lemma from_blocks_multiply {p q : Type*} [fintype p] [fintype q] (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix l p α) (B' : matrix l q α) (C' : matrix m p α) (D' : matrix m q α) : (from_blocks A B C D) ⬝ (from_blocks A' B' C' D') = from_blocks (A ⬝ A' + B ⬝ C') (A ⬝ B' + B ⬝ D') (C ⬝ A' + D ⬝ C') (C ⬝ B' + D ⬝ D') := begin ext i j, rcases i; rcases j; simp only [from_blocks, mul_apply, fintype.sum_sum_type, sum.elim_inl, sum.elim_inr, pi.add_apply], end variables [decidable_eq l] [decidable_eq m] @[simp] lemma from_blocks_diagonal (d₁ : l → α) (d₂ : m → α) : from_blocks (diagonal d₁) 0 0 (diagonal d₂) = diagonal (sum.elim d₁ d₂) := begin ext i j, rcases i; rcases j; simp [diagonal], end @[simp] lemma from_blocks_one : from_blocks (1 : matrix l l α) 0 0 (1 : matrix m m α) = 1 := by { ext i j, rcases i; rcases j; simp [one_apply] } end block_matrices section block_diagonal variables (M N : o → matrix m n α) [decidable_eq o] section has_zero variables [has_zero α] [has_zero β] /-- `matrix.block_diagonal M` turns a homogenously-indexed collection of matrices `M : o → matrix m n α'` into a `m × o`-by-`n × o` block matrix which has the entries of `M` along the diagonal and zero elsewhere. See also `matrix.block_diagonal'` if the matrices may not have the same size everywhere. -/ def block_diagonal : matrix (m × o) (n × o) α | ⟨i, k⟩ ⟨j, k'⟩ := if k = k' then M k i j else 0 lemma block_diagonal_apply (ik jk) : block_diagonal M ik jk = if ik.2 = jk.2 then M ik.2 ik.1 jk.1 else 0 := by { cases ik, cases jk, refl } @[simp] lemma block_diagonal_apply_eq (i j k) : block_diagonal M (i, k) (j, k) = M k i j := if_pos rfl lemma block_diagonal_apply_ne (i j) {k k'} (h : k ≠ k') : block_diagonal M (i, k) (j, k') = 0 := if_neg h lemma block_diagonal_map (f : α → β) (hf : f 0 = 0) : (block_diagonal M).map f = block_diagonal (λ k, (M k).map f) := begin ext, simp only [map_apply, block_diagonal_apply, eq_comm], rw [apply_ite f, hf], end @[simp] lemma block_diagonal_transpose : (block_diagonal M)ᵀ = block_diagonal (λ k, (M k)ᵀ) := begin ext, simp only [transpose_apply, block_diagonal_apply, eq_comm], split_ifs with h, { rw h }, { refl } end @[simp] lemma block_diagonal_conj_transpose {α : Type*} [semiring α] [star_ring α] (M : o → matrix m n α) : (block_diagonal M)ᴴ = block_diagonal (λ k, (M k)ᴴ) := begin simp only [conj_transpose, block_diagonal_transpose], rw block_diagonal_map _ star (star_zero α), end @[simp] lemma block_diagonal_zero : block_diagonal (0 : o → matrix m n α) = 0 := by { ext, simp [block_diagonal_apply] } @[simp] lemma block_diagonal_diagonal [decidable_eq m] (d : o → m → α) : block_diagonal (λ k, diagonal (d k)) = diagonal (λ ik, d ik.2 ik.1) := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, diagonal], split_ifs; finish end @[simp] lemma block_diagonal_one [decidable_eq m] [has_one α] : block_diagonal (1 : o → matrix m m α) = 1 := show block_diagonal (λ (_ : o), diagonal (λ (_ : m), (1 : α))) = diagonal (λ _, 1), by rw [block_diagonal_diagonal] end has_zero @[simp] lemma block_diagonal_add [add_monoid α] : block_diagonal (M + N) = block_diagonal M + block_diagonal N := begin ext, simp only [block_diagonal_apply, pi.add_apply], split_ifs; simp end @[simp] lemma block_diagonal_neg [add_group α] : block_diagonal (-M) = - block_diagonal M := begin ext, simp only [block_diagonal_apply, pi.neg_apply], split_ifs; simp end @[simp] lemma block_diagonal_sub [add_group α] : block_diagonal (M - N) = block_diagonal M - block_diagonal N := by simp [sub_eq_add_neg] @[simp] lemma block_diagonal_mul {p : Type*} [fintype p] [semiring α] (N : o → matrix n p α) : block_diagonal (λ k, M k ⬝ N k) = block_diagonal M ⬝ block_diagonal N := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product], split_ifs with h; simp [h] end @[simp] lemma block_diagonal_smul {R : Type*} [semiring R] [add_comm_monoid α] [module R α] (x : R) : block_diagonal (x • M) = x • block_diagonal M := by { ext, simp only [block_diagonal_apply, pi.smul_apply], split_ifs; simp } end block_diagonal section block_diagonal' variables (M N : Π i, matrix (m' i) (n' i) α) [decidable_eq o] section has_zero variables [has_zero α] [has_zero β] /-- `matrix.block_diagonal' M` turns `M : Π i, matrix (m i) (n i) α` into a `Σ i, m i`-by-`Σ i, n i` block matrix which has the entries of `M` along the diagonal and zero elsewhere. This is the dependently-typed version of `matrix.block_diagonal`. -/ def block_diagonal' : matrix (Σ i, m' i) (Σ i, n' i) α | ⟨k, i⟩ ⟨k', j⟩ := if h : k = k' then M k i (cast (congr_arg n' h.symm) j) else 0 lemma block_diagonal'_eq_block_diagonal (M : o → matrix m n α) {k k'} (i j) : block_diagonal M (i, k) (j, k') = block_diagonal' M ⟨k, i⟩ ⟨k', j⟩ := rfl lemma block_diagonal'_minor_eq_block_diagonal (M : o → matrix m n α) : (block_diagonal' M).minor (prod.to_sigma ∘ prod.swap) (prod.to_sigma ∘ prod.swap) = block_diagonal M := matrix.ext $ λ ⟨k, i⟩ ⟨k', j⟩, rfl lemma block_diagonal'_apply (ik jk) : block_diagonal' M ik jk = if h : ik.1 = jk.1 then M ik.1 ik.2 (cast (congr_arg n' h.symm) jk.2) else 0 := by { cases ik, cases jk, refl } @[simp] lemma block_diagonal'_apply_eq (k i j) : block_diagonal' M ⟨k, i⟩ ⟨k, j⟩ = M k i j := dif_pos rfl lemma block_diagonal'_apply_ne {k k'} (i j) (h : k ≠ k') : block_diagonal' M ⟨k, i⟩ ⟨k', j⟩ = 0 := dif_neg h lemma block_diagonal'_map (f : α → β) (hf : f 0 = 0) : (block_diagonal' M).map f = block_diagonal' (λ k, (M k).map f) := begin ext, simp only [map_apply, block_diagonal'_apply, eq_comm], rw [apply_dite f, hf], end @[simp] lemma block_diagonal'_transpose : (block_diagonal' M)ᵀ = block_diagonal' (λ k, (M k)ᵀ) := begin ext ⟨ii, ix⟩ ⟨ji, jx⟩, simp only [transpose_apply, block_diagonal'_apply, eq_comm], dsimp only, split_ifs with h₁ h₂ h₂, { subst h₁, refl, }, { exact (h₂ h₁.symm).elim }, { exact (h₁ h₂.symm).elim }, { refl } end @[simp] lemma block_diagonal'_conj_transpose {α} [semiring α] [star_ring α] (M : Π i, matrix (m' i) (n' i) α) : (block_diagonal' M)ᴴ = block_diagonal' (λ k, (M k)ᴴ) := begin simp only [conj_transpose, block_diagonal'_transpose], exact block_diagonal'_map _ star (star_zero α), end @[simp] lemma block_diagonal'_zero : block_diagonal' (0 : Π i, matrix (m' i) (n' i) α) = 0 := by { ext, simp [block_diagonal'_apply] } @[simp] lemma block_diagonal'_diagonal [∀ i, decidable_eq (m' i)] (d : Π i, m' i → α) : block_diagonal' (λ k, diagonal (d k)) = diagonal (λ ik, d ik.1 ik.2) := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal'_apply, diagonal], split_ifs; finish end @[simp] lemma block_diagonal'_one [∀ i, decidable_eq (m' i)] [has_one α] : block_diagonal' (1 : Π i, matrix (m' i) (m' i) α) = 1 := show block_diagonal' (λ (i : o), diagonal (λ (_ : m' i), (1 : α))) = diagonal (λ _, 1), by rw [block_diagonal'_diagonal] end has_zero @[simp] lemma block_diagonal'_add [add_monoid α] : block_diagonal' (M + N) = block_diagonal' M + block_diagonal' N := begin ext, simp only [block_diagonal'_apply, pi.add_apply], split_ifs; simp end @[simp] lemma block_diagonal'_neg [add_group α] : block_diagonal' (-M) = - block_diagonal' M := begin ext, simp only [block_diagonal'_apply, pi.neg_apply], split_ifs; simp end @[simp] lemma block_diagonal'_sub [add_group α] : block_diagonal' (M - N) = block_diagonal' M - block_diagonal' N := by simp [sub_eq_add_neg] @[simp] lemma block_diagonal'_mul {p : o → Type*} [Π i, fintype (p i)] [semiring α] (N : Π i, matrix (n' i) (p i) α) : block_diagonal' (λ k, M k ⬝ N k) = block_diagonal' M ⬝ block_diagonal' N := begin ext ⟨k, i⟩ ⟨k', j⟩, simp only [block_diagonal'_apply, mul_apply, ← finset.univ_sigma_univ, finset.sum_sigma], rw fintype.sum_eq_single k, { split_ifs; simp }, { intros j' hj', exact finset.sum_eq_zero (λ _ _, by rw [dif_neg hj'.symm, zero_mul]) }, end @[simp] lemma block_diagonal'_smul {R : Type*} [semiring R] [add_comm_monoid α] [module R α] (x : R) : block_diagonal' (x • M) = x • block_diagonal' M := by { ext, simp only [block_diagonal'_apply, pi.smul_apply], split_ifs; simp } end block_diagonal' end matrix
97ebbb76f3018b3afd9a7bd458a11e6dd3b60b2d
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/zmod/parity.lean
921dc07342dbf9a0d4b255c85152bfae73573679
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
804
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.nat.parity import data.zmod.basic /-! # Relating parity to natural numbers mod 2 This module provides lemmas relating `zmod 2` to `even` and `odd`. ## Tags parity, zmod, even, odd -/ namespace zmod lemma eq_zero_iff_even {n : ℕ} : (n : zmod 2) = 0 ↔ even n := (char_p.cast_eq_zero_iff (zmod 2) 2 n).trans even_iff_two_dvd.symm lemma eq_one_iff_odd {n : ℕ} : (n : zmod 2) = 1 ↔ odd n := begin change (n : zmod 2) = ((1 : ℕ) : zmod 2) ↔ _, rw [zmod.eq_iff_modeq_nat, nat.odd_iff], trivial, end lemma ne_zero_iff_odd {n : ℕ} : (n : zmod 2) ≠ 0 ↔ odd n := by split; { contrapose, simp [eq_zero_iff_even], } end zmod
68fa40e3c926d9b2de462273f5f314e40c64688e
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/Reformat/Input.lean
fed9c10875c05653312f44f55954174ccf41cab7
[ "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
9,645
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 -/ prelude universes u v w @[inline] def id {α : Sort u} (a : α) : α := a /- The kernel definitional equality test (t =?= s) has special support for idDelta applications. It implements the following rules 1) (idDelta t) =?= t 2) t =?= (idDelta t) 3) (idDelta t) =?= s IF (unfoldOf t) =?= s 4) t =?= idDelta s IF t =?= (unfoldOf s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use idDelta applications to address performance problems when Type checking theorems generated by the equation Compiler. -/ @[inline] def idDelta {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a @[reducible] def inferInstance {α : Type u} [i : α] : α := i @[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop | refl {} : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) := (fst : α) (snd : β) attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) := (fst : α) (snd : β) /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) := (fst : α) (snd : β) structure And (a b : Prop) : Prop := intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) := mk {} :: (default : α) constant arbitrary (α : Sort u) [s : Inhabited α] : α := @Inhabited.default α s instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) := { default := fun _ => arbitrary β } instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) := { default := fun a => arbitrary (β a) } /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u := up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType := (type : Type u) (val : type) instance : Inhabited PointedType.{u} := { default := { type := PUnit.{u+1}, val := ⟨⟩ } } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) := up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true | _, isTrue _, _ => rfl | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqTrue' : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false | _, isTrue h₁, h₂ => absurd h₁ h₂ | _, isFalse h, _ => rfl theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h => match s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h => match s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) := (beq : α → α → Bool) open BEq (beq) instance {α : Type u} [DecidableEq α] : BEq α := ⟨fun a b => decide (Eq a b)⟩ -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t
4190b43f75db3ec9e052d4a7cbf0f0e8e0ceba82
4727251e0cd73359b15b664c3170e5d754078599
/src/data/fp/basic.lean
4bbed9f2e17f8f0984e9bf64353ba102dac15876
[ "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
6,376
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.semiquot import data.rat.floor /-! # Implementation of floating-point numbers (experimental). -/ def int.shift2 (a b : ℕ) : ℤ → ℕ × ℕ | (int.of_nat e) := (a.shiftl e, b) | -[1+ e] := (a, b.shiftl e.succ) namespace fp @[derive inhabited] inductive rmode | NE -- round to nearest even class float_cfg := (prec emax : ℕ) (prec_pos : 0 < prec) (prec_max : prec ≤ emax) variable [C : float_cfg] include C def prec := C.prec def emax := C.emax def emin : ℤ := 1 - C.emax def valid_finite (e : ℤ) (m : ℕ) : Prop := emin ≤ e + prec - 1 ∧ e + prec - 1 ≤ emax ∧ e = max (e + m.size - prec) emin instance dec_valid_finite (e m) : decidable (valid_finite e m) := by unfold valid_finite; apply_instance inductive float | inf : bool → float | nan : float | finite : bool → Π e m, valid_finite e m → float def float.is_finite : float → bool | (float.finite s e m f) := tt | _ := ff def to_rat : Π (f : float), f.is_finite → ℚ | (float.finite s e m f) _ := let (n, d) := int.shift2 m 1 e, r := rat.mk_nat n d in if s then -r else r theorem float.zero.valid : valid_finite emin 0 := ⟨begin rw add_sub_assoc, apply le_add_of_nonneg_right, apply sub_nonneg_of_le, apply int.coe_nat_le_coe_nat_of_le, exact C.prec_pos end, suffices prec ≤ 2 * emax, begin rw ← int.coe_nat_le at this, rw ← sub_nonneg at *, simp only [emin, emax] at *, ring_nf, assumption end, le_trans C.prec_max (nat.le_mul_of_pos_left dec_trivial), by rw max_eq_right; simp [sub_eq_add_neg]⟩ def float.zero (s : bool) : float := float.finite s emin 0 float.zero.valid instance : inhabited float := ⟨float.zero tt⟩ protected def float.sign' : float → semiquot bool | (float.inf s) := pure s | float.nan := ⊤ | (float.finite s e m f) := pure s protected def float.sign : float → bool | (float.inf s) := s | float.nan := ff | (float.finite s e m f) := s protected def float.is_zero : float → bool | (float.finite s e 0 f) := tt | _ := ff protected def float.neg : float → float | (float.inf s) := float.inf (bnot s) | float.nan := float.nan | (float.finite s e m f) := float.finite (bnot s) e m f def div_nat_lt_two_pow (n d : ℕ) : ℤ → bool | (int.of_nat e) := n < d.shiftl e | -[1+ e] := n.shiftl e.succ < d -- TODO(Mario): Prove these and drop 'meta' meta def of_pos_rat_dn (n : ℕ+) (d : ℕ+) : float × bool := begin let e₁ : ℤ := n.1.size - d.1.size - prec, cases h₁ : int.shift2 d.1 n.1 (e₁ + prec) with d₁ n₁, let e₂ := if n₁ < d₁ then e₁ - 1 else e₁, let e₃ := max e₂ emin, cases h₂ : int.shift2 d.1 n.1 (e₃ + prec) with d₂ n₂, let r := rat.mk_nat n₂ d₂, let m := r.floor, refine (float.finite ff e₃ (int.to_nat m) _, r.denom = 1), { exact undefined } end meta def next_up_pos (e m) (v : valid_finite e m) : float := let m' := m.succ in if ss : m'.size = m.size then float.finite ff e m' (by unfold valid_finite at *; rw ss; exact v) else if h : e = emax then float.inf ff else float.finite ff e.succ (nat.div2 m') undefined meta def next_dn_pos (e m) (v : valid_finite e m) : float := match m with | 0 := next_up_pos _ _ float.zero.valid | nat.succ m' := if ss : m'.size = m.size then float.finite ff e m' (by unfold valid_finite at *; rw ss; exact v) else if h : e = emin then float.finite ff emin m' undefined else float.finite ff e.pred (bit1 m') undefined end meta def next_up : float → float | (float.finite ff e m f) := next_up_pos e m f | (float.finite tt e m f) := float.neg $ next_dn_pos e m f | f := f meta def next_dn : float → float | (float.finite ff e m f) := next_dn_pos e m f | (float.finite tt e m f) := float.neg $ next_up_pos e m f | f := f meta def of_rat_up : ℚ → float | ⟨0, _, _, _⟩ := float.zero ff | ⟨nat.succ n, d, h, _⟩ := let (f, exact) := of_pos_rat_dn n.succ_pnat ⟨d, h⟩ in if exact then f else next_up f | ⟨-[1+n], d, h, _⟩ := float.neg (of_pos_rat_dn n.succ_pnat ⟨d, h⟩).1 meta def of_rat_dn (r : ℚ) : float := float.neg $ of_rat_up (-r) meta def of_rat : rmode → ℚ → float | rmode.NE r := let low := of_rat_dn r, high := of_rat_up r in if hf : high.is_finite then if r = to_rat _ hf then high else if lf : low.is_finite then if r - to_rat _ lf > to_rat _ hf - r then high else if r - to_rat _ lf < to_rat _ hf - r then low else match low, lf with float.finite s e m f, _ := if 2 ∣ m then low else high end else float.inf tt else float.inf ff namespace float instance : has_neg float := ⟨float.neg⟩ meta def add (mode : rmode) : float → float → float | nan _ := nan | _ nan := nan | (inf tt) (inf ff) := nan | (inf ff) (inf tt) := nan | (inf s₁) _ := inf s₁ | _ (inf s₂) := inf s₂ | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in of_rat mode (to_rat f₁ rfl + to_rat f₂ rfl) meta instance : has_add float := ⟨float.add rmode.NE⟩ meta def sub (mode : rmode) (f1 f2 : float) : float := add mode f1 (-f2) meta instance : has_sub float := ⟨float.sub rmode.NE⟩ meta def mul (mode : rmode) : float → float → float | nan _ := nan | _ nan := nan | (inf s₁) f₂ := if f₂.is_zero then nan else inf (bxor s₁ f₂.sign) | f₁ (inf s₂) := if f₁.is_zero then nan else inf (bxor f₁.sign s₂) | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in of_rat mode (to_rat f₁ rfl * to_rat f₂ rfl) meta def div (mode : rmode) : float → float → float | nan _ := nan | _ nan := nan | (inf s₁) (inf s₂) := nan | (inf s₁) f₂ := inf (bxor s₁ f₂.sign) | f₁ (inf s₂) := zero (bxor f₁.sign s₂) | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in if f₂.is_zero then inf (bxor s₁ s₂) else of_rat mode (to_rat f₁ rfl / to_rat f₂ rfl) end float end fp
b49b36b1d81ccc71c3a8aa28950fb9ae27ed3f0e
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/system/random/basic.lean
561bbbee99bc6670d8f537350839f07bb56c72cf
[ "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
9,125
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import algebra.group_power import control.uliftable import control.monad.basic import data.bitvec.basic import data.list.basic import data.set.intervals.basic import data.stream.basic import data.fin import tactic.cache import tactic.interactive import tactic.norm_num import system.io import system.random /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ open list io applicative universes u v w /-- A monad to generate random objects using the generator type `g` -/ @[reducible] def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α /-- A monad to generate random objects using the generator type `std_gen` -/ @[reducible] def rand := rand_g std_gen instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) := @state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm) open ulift (hiding inhabited) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := ⟨ prod.map id up ∘ random_gen.next ∘ down ⟩ local infix ` .. `:41 := set.Icc open stream /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] := (random_r : Π g [random_gen g] (x y : α), (x ≤ y) → rand_g g (x .. y)) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) [preorder α] extends bounded_random α := (random [] : Π (g : Type) [random_gen g], rand_g g α) attribute [instance, priority 100] random.to_bounded_random /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := by apply_normed 2^31 namespace rand open stream variables (α : Type u) variables (g : Type) [random_gen g] /-- create a new random number generator distinct from the one stored in the state -/ def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩ variables {g} section random variables [preorder α] [random α] export random (random) /-- Generate a random value of type `α`. -/ def random : rand_g g α := random.random α g /-- generate an infinite series of random values of type `α` -/ def random_series : rand_g g (stream α) := do gen ← uliftable.up (split g), pure $ stream.corec_state (random.random α g) gen end random variables {α} /-- Generate a random value between `x` and `y` inclusive. -/ def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (stream (x .. y)) := do gen ← uliftable.up (split g), pure $ corec_state (bounded_random.random_r g x y h) gen end rand namespace io private def accum_char (w : ℕ) (c : char) : ℕ := c.to_nat + 256 * w /-- create and a seed a random number generator -/ def mk_generator : io std_gen := do seed ← io.rand 0 shift_31_left, return $ mk_std_gen seed variables {α : Type} /-- run `cmd` using a randomly seeded random number generator -/ def run_rand (cmd : _root_.rand α) : io α := do g ← io.mk_generator, return $ (cmd.run ⟨g⟩).1 section random variables [preorder α] [random α] /-- randomly generate a value of type α -/ def random : io α := io.run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series : io (stream α) := io.run_rand (rand.random_series α) end random section bounded_random variables [preorder α] [bounded_random α] /-- randomly generate a value of type α between `x` and `y` -/ def random_r (x y : α) (p : x ≤ y) : io (x .. y) := io.run_rand (bounded_random.random_r _ x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) := io.run_rand (rand.random_series_r x y h) end bounded_random end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ meta def mk_generator : tactic std_gen := do tactic.unsafe_run_io @io.mk_generator /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do ⟨g⟩ ← tactic.up mk_generator, return (cmd.run ⟨g⟩).1 variables {α : Type u} section bounded_random variables [preorder α] [bounded_random α] /-- Generate a random value between `x` and `y` inclusive. -/ meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) := run_rand (rand.random_r x y h) /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) := run_rand (rand.random_series_r x y h) end bounded_random section random variables [preorder α] [random α] /-- randomly generate a value of type α -/ meta def random : tactic α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ meta def random_series : tactic (stream α) := run_rand (rand.random_series α) end random end tactic open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ) variables {g : Type} [random_gen g] open nat namespace fin variables {n : ℕ} [fact (0 < n)] /-- generate a `fin` randomly -/ protected def random : rand_g g (fin n) := ⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩ end fin open nat instance nat_bounded_random : bounded_random ℕ := { random_r := λ g inst x y hxy, do z ← @fin.random g inst (succ $ y - x) _, pure ⟨z.val + x, nat.le_add_left _ _, by rw ← nat.le_sub_right_iff_add_le hxy; apply le_of_succ_le_succ z.is_lt⟩ } instance fin_random (n : ℕ) [fact (0 < n)] : random (fin n) := { random := λ g inst, @fin.random g inst _ _, random_r := λ g inst (x y : fin n) p, do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p, pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ } /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n) | (succ n) _ := fin_random _ | 0 h := false.elim (not_lt_zero _ h) lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) : n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) := begin simp only [and_imp, set.mem_Icc], intros h₀ h₁, split; [ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ]; rw bool.of_nat_to_nat at h₂; exact h₂, end instance : random bool := { random := λ g inst, (bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _), random_r := λ g _inst x y p, subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> @bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) } open_locale fin_fact /-- generate a random bit vector of length `n` -/ def bitvec.random (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin $ 2^n) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) := have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y), begin simp only [and_imp, set.mem_Icc], intros z h₀ h₁, replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀, replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁, rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption, end, subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h) open nat instance random_bitvec (n : ℕ) : random (bitvec n) := { random := λ _ inst, @bitvec.random _ inst n, random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
62f22785dcead85c71d489a600af85d9b18f33df
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/category_theory/is_connected.lean
1b62ee85f33ad572913e6b4a2c64ba77a06a7e03
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,956
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.list.chain import category_theory.punit /-! # Connected category Define a connected category as a _nonempty_ category for which every functor to a discrete category is isomorphic to the constant functor. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. We give some equivalent definitions: - A nonempty category for which every functor to a discrete category is constant on objects. See `any_functor_const_on_obj` and `connected.of_any_functor_const_on_obj`. - A nonempty category for which every function `F` for which the presence of a morphism `f : j₁ ⟶ j₂` implies `F j₁ = F j₂` must be constant everywhere. See `constant_of_preserves_morphisms` and `connected.of_constant_of_preserves_morphisms`. - A nonempty category for which any subset of its elements containing the default and closed under morphisms is everything. See `induct_on_objects` and `connected.of_induct`. - A nonempty category for which every object is related under the reflexive transitive closure of the relation "there is a morphism in some direction from `j₁` to `j₂`". See `connected_zigzag` and `zigzag_connected`. - A nonempty category for which for any two objects there is a sequence of morphisms (some reversed) from one to the other. See `exists_zigzag'` and `connected_of_zigzag`. We also prove the result that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. This appears in `category_theory.limits.connected`. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory.category namespace category_theory /-- A possibly empty category for which every functor to a discrete category is constant. -/ class is_preconnected (J : Type u₁) [category.{v₁} J] : Prop := (iso_constant : Π {α : Type u₁} (F : J ⥤ discrete α) (j : J), nonempty (F ≅ (functor.const J).obj (F.obj j))) /-- We define a connected category as a _nonempty_ category for which every functor to a discrete category is constant. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. This allows us to show that the functor X ⨯ - preserves connected limits. See https://stacks.math.columbia.edu/tag/002S -/ class is_connected (J : Type u₁) [category.{v₁} J] extends is_preconnected J : Prop := [is_nonempty : nonempty J] attribute [instance, priority 100] is_connected.is_nonempty variables {J : Type u₁} [category.{v₁} J] variables {K : Type u₂} [category.{v₂} K] /-- If `J` is connected, any functor `F : J ⥤ discrete α` is isomorphic to the constant functor with value `F.obj j` (for any choice of `j`). -/ def iso_constant [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j : J) : F ≅ (functor.const J).obj (F.obj j) := (is_preconnected.iso_constant F j).some /-- If J is connected, any functor to a discrete category is constant on objects. The converse is given in `is_connected.of_any_functor_const_on_obj`. -/ lemma any_functor_const_on_obj [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j j' : J) : F.obj j = F.obj j' := ((iso_constant F j').hom.app j).down.1 /-- If any functor to a discrete category is constant on objects, J is connected. The converse of `any_functor_const_on_obj`. -/ lemma is_connected.of_any_functor_const_on_obj [nonempty J] (h : ∀ {α : Type u₁} (F : J ⥤ discrete α), ∀ (j j' : J), F.obj j = F.obj j') : is_connected J := { iso_constant := λ α F j', ⟨nat_iso.of_components (λ j, eq_to_iso (h F j j')) (λ _ _ _, subsingleton.elim _ _)⟩ } /-- If `J` is connected, then given any function `F` such that the presence of a morphism `j₁ ⟶ j₂` implies `F j₁ = F j₂`, we have that `F` is constant. This can be thought of as a local-to-global property. The converse is shown in `is_connected.of_constant_of_preserves_morphisms` -/ lemma constant_of_preserves_morphisms [is_preconnected J] {α : Type u₁} (F : J → α) (h : ∀ (j₁ j₂ : J) (f : j₁ ⟶ j₂), F j₁ = F j₂) (j j' : J) : F j = F j' := any_functor_const_on_obj { obj := F, map := λ _ _ f, eq_to_hom (h _ _ f) } j j' /-- `J` is connected if: given any function `F : J → α` which is constant for any `j₁, j₂` for which there is a morphism `j₁ ⟶ j₂`, then `F` is constant. This can be thought of as a local-to-global property. The converse of `constant_of_preserves_morphisms`. -/ lemma is_connected.of_constant_of_preserves_morphisms [nonempty J] (h : ∀ {α : Type u₁} (F : J → α), (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), F j₁ = F j₂) → (∀ j j' : J, F j = F j')) : is_connected J := is_connected.of_any_functor_const_on_obj (λ _ F, h F.obj (λ _ _ f, (F.map f).down.1)) /-- An inductive-like property for the objects of a connected category. If the set `p` is nonempty, and `p` is closed under morphisms of `J`, then `p` contains all of `J`. The converse is given in `is_connected.of_induct`. -/ lemma induct_on_objects [is_preconnected J] (p : set J) {j₀ : J} (h0 : j₀ ∈ p) (h1 : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) (j : J) : j ∈ p := begin injection (constant_of_preserves_morphisms (λ k, ulift.up (k ∈ p)) (λ j₁ j₂ f, _) j j₀) with i, rwa i, dsimp, exact congr_arg ulift.up (propext (h1 f)), end /-- If any maximal connected component containing some element j₀ of J is all of J, then J is connected. The converse of `induct_on_objects`. -/ lemma is_connected.of_induct [nonempty J] {j₀ : J} (h : ∀ (p : set J), j₀ ∈ p → (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) → ∀ (j : J), j ∈ p) : is_connected J := is_connected.of_constant_of_preserves_morphisms (λ α F a, begin have w := h {j | F j = F j₀} rfl (λ _ _ f, by simp [a f]), dsimp at w, intros j j', rw [w j, w j'], end) /-- Another induction principle for `is_preconnected J`: given a type family `Z : J → Sort*` and a rule for transporting in *both* directions along a morphism in `J`, we can transport an `x : Z j₀` to a point in `Z j` for any `j`. -/ lemma is_preconnected_induction [is_preconnected J] (Z : J → Sort*) (h₁ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₁ → Z j₂) (h₂ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₂ → Z j₁) {j₀ : J} (x : Z j₀) (j : J) : nonempty (Z j) := (induct_on_objects {j | nonempty (Z j)} ⟨x⟩ (λ j₁ j₂ f, ⟨by { rintro ⟨y⟩, exact ⟨h₁ f y⟩, }, by { rintro ⟨y⟩, exact ⟨h₂ f y⟩, }⟩) j : _) /-- If `J` and `K` are equivalent, then if `J` is preconnected then `K` is as well. -/ lemma is_preconnected_of_equivalent {K : Type u₁} [category.{v₂} K] [is_preconnected J] (e : J ≌ K) : is_preconnected K := { iso_constant := λ α F k, ⟨ calc F ≅ e.inverse ⋙ e.functor ⋙ F : (e.inv_fun_id_assoc F).symm ... ≅ e.inverse ⋙ (functor.const J).obj ((e.functor ⋙ F).obj (e.inverse.obj k)) : iso_whisker_left e.inverse (iso_constant (e.functor ⋙ F) (e.inverse.obj k)) ... ≅ e.inverse ⋙ (functor.const J).obj (F.obj k) : iso_whisker_left _ ((F ⋙ functor.const J).map_iso (e.counit_iso.app k)) ... ≅ (functor.const K).obj (F.obj k) : nat_iso.of_components (λ X, iso.refl _) (by simp), ⟩ } /-- If `J` and `K` are equivalent, then if `J` is connected then `K` is as well. -/ lemma is_connected_of_equivalent {K : Type u₁} [category.{v₂} K] (e : J ≌ K) [is_connected J] : is_connected K := { is_nonempty := nonempty.map e.functor.obj (by apply_instance), to_is_preconnected := is_preconnected_of_equivalent e } /-- j₁ and j₂ are related by `zag` if there is a morphism between them. -/ @[reducible] def zag (j₁ j₂ : J) : Prop := nonempty (j₁ ⟶ j₂) ∨ nonempty (j₂ ⟶ j₁) lemma zag_symmetric : symmetric (@zag J _) := λ j₂ j₁ h, h.swap /-- `j₁` and `j₂` are related by `zigzag` if there is a chain of morphisms from `j₁` to `j₂`, with backward morphisms allowed. -/ @[reducible] def zigzag : J → J → Prop := relation.refl_trans_gen zag lemma zigzag_symmetric : symmetric (@zigzag J _) := relation.refl_trans_gen.symmetric zag_symmetric lemma zigzag_equivalence : _root_.equivalence (@zigzag J _) := mk_equivalence _ relation.reflexive_refl_trans_gen zigzag_symmetric relation.transitive_refl_trans_gen /-- The setoid given by the equivalence relation `zigzag`. A quotient for this setoid is a connected component of the category. -/ def zigzag.setoid (J : Type u₂) [category.{v₁} J] : setoid J := { r := zigzag, iseqv := zigzag_equivalence } /-- If there is a zigzag from `j₁` to `j₂`, then there is a zigzag from `F j₁` to `F j₂` as long as `F` is a functor. -/ lemma zigzag_obj_of_zigzag (F : J ⥤ K) {j₁ j₂ : J} (h : zigzag j₁ j₂) : zigzag (F.obj j₁) (F.obj j₂) := begin refine relation.refl_trans_gen_lift _ _ h, intros j k, exact or.imp (nonempty.map (λ f, F.map f)) (nonempty.map (λ f, F.map f)) end -- TODO: figure out the right way to generalise this to `zigzag`. lemma zag_of_zag_obj (F : J ⥤ K) [full F] {j₁ j₂ : J} (h : zag (F.obj j₁) (F.obj j₂)) : zag j₁ j₂ := or.imp (nonempty.map F.preimage) (nonempty.map F.preimage) h /-- Any equivalence relation containing (⟶) holds for all pairs of a connected category. -/ lemma equiv_relation [is_connected J] (r : J → J → Prop) (hr : _root_.equivalence r) (h : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), r j₁ j₂) : ∀ (j₁ j₂ : J), r j₁ j₂ := begin have z : ∀ (j : J), r (classical.arbitrary J) j := induct_on_objects (λ k, r (classical.arbitrary J) k) (hr.1 (classical.arbitrary J)) (λ _ _ f, ⟨λ t, hr.2.2 t (h f), λ t, hr.2.2 t (hr.2.1 (h f))⟩), intros, apply hr.2.2 (hr.2.1 (z _)) (z _) end /-- In a connected category, any two objects are related by `zigzag`. -/ lemma is_connected_zigzag [is_connected J] (j₁ j₂ : J) : zigzag j₁ j₂ := equiv_relation _ zigzag_equivalence (λ _ _ f, relation.refl_trans_gen.single (or.inl (nonempty.intro f))) _ _ /-- If any two objects in an nonempty category are related by `zigzag`, the category is connected. -/ lemma zigzag_is_connected [nonempty J] (h : ∀ (j₁ j₂ : J), zigzag j₁ j₂) : is_connected J := begin apply is_connected.of_induct, intros p hp hjp j, have: ∀ (j₁ j₂ : J), zigzag j₁ j₂ → (j₁ ∈ p ↔ j₂ ∈ p), { introv k, induction k with _ _ rt_zag zag, { refl }, { rw k_ih, rcases zag with ⟨⟨_⟩⟩ | ⟨⟨_⟩⟩, apply hjp zag, apply (hjp zag).symm } }, rwa this j (classical.arbitrary J) (h _ _) end lemma exists_zigzag' [is_connected J] (j₁ j₂ : J) : ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂ := list.exists_chain_of_relation_refl_trans_gen (is_connected_zigzag _ _) /-- If any two objects in an nonempty category are linked by a sequence of (potentially reversed) morphisms, then J is connected. The converse of `exists_zigzag'`. -/ lemma is_connected_of_zigzag [nonempty J] (h : ∀ (j₁ j₂ : J), ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂) : is_connected J := begin apply is_connected.of_induct, intros p d k j, obtain ⟨l, zags, lst⟩ := h j (classical.arbitrary J), apply list.chain.induction_head p l zags lst _ d, rintros _ _ (⟨⟨xy⟩⟩ | ⟨⟨yx⟩⟩), { exact (k xy).2 }, { exact (k yx).1 } end /-- If `discrete α` is connected, then `α` is (type-)equivalent to `punit`. -/ def discrete_is_connected_equiv_punit {α : Type*} [is_connected (discrete α)] : α ≃ punit := discrete.equiv_of_equivalence { functor := functor.star α, inverse := discrete.functor (λ _, classical.arbitrary _), unit_iso := by { exact (iso_constant _ (classical.arbitrary _)), }, counit_iso := functor.punit_ext _ _ } variables {C : Type u₂} [category.{u₁} C] /-- For objects `X Y : C`, any natural transformation `α : const X ⟶ const Y` from a connected category must be constant. This is the key property of connected categories which we use to establish properties about limits. -/ lemma nat_trans_from_is_connected [is_preconnected J] {X Y : C} (α : (functor.const J).obj X ⟶ (functor.const J).obj Y) : ∀ (j j' : J), α.app j = (α.app j' : X ⟶ Y) := @constant_of_preserves_morphisms _ _ _ (X ⟶ Y) (λ j, α.app j) (λ _ _ f, (by { have := α.naturality f, erw [id_comp, comp_id] at this, exact this.symm })) end category_theory
e3a923f097cc8eb356bbfa253be0572c094406a1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/ringed_space.lean
919792ac6b32883d4e076e7a267ab3d572dcd423
[ "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,959
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer, Andrew Yang -/ import algebra.category.Ring.filtered_colimits import algebraic_geometry.sheafed_space import topology.sheaves.stalks import algebra.category.Ring.colimits import algebra.category.Ring.limits /-! # Ringed spaces We introduce the category of ringed spaces, as an alias for `SheafedSpace CommRing`. The facts collected in this file are typically stated for locally ringed spaces, but never actually make use of the locality of stalks. See for instance <https://stacks.math.columbia.edu/tag/01HZ>. -/ universe v open category_theory open topological_space open opposite open Top open Top.presheaf namespace algebraic_geometry /-- The type of Ringed spaces, as an abbreviation for `SheafedSpace CommRing`. -/ abbreviation RingedSpace : Type* := SheafedSpace CommRing namespace RingedSpace open SheafedSpace variables (X : RingedSpace.{v}) /-- If the germ of a section `f` is a unit in the stalk at `x`, then `f` must be a unit on some small neighborhood around `x`. -/ lemma is_unit_res_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (x : U) (h : is_unit (X.presheaf.germ x f)) : ∃ (V : opens X) (i : V ⟶ U) (hxV : x.1 ∈ V), is_unit (X.presheaf.map i.op f) := begin obtain ⟨g', heq⟩ := h.exists_right_inv, obtain ⟨V, hxV, g, rfl⟩ := X.presheaf.germ_exist x.1 g', let W := U ⊓ V, have hxW : x.1 ∈ W := ⟨x.2, hxV⟩, erw [← X.presheaf.germ_res_apply (opens.inf_le_left U V) ⟨x.1, hxW⟩ f, ← X.presheaf.germ_res_apply (opens.inf_le_right U V) ⟨x.1, hxW⟩ g, ← ring_hom.map_mul, ← ring_hom.map_one (X.presheaf.germ (⟨x.1, hxW⟩ : W))] at heq, obtain ⟨W', hxW', i₁, i₂, heq'⟩ := X.presheaf.germ_eq x.1 hxW hxW _ _ heq, use [W', i₁ ≫ opens.inf_le_left U V, hxW'], rw [ring_hom.map_one, ring_hom.map_mul, ← comp_apply, ← X.presheaf.map_comp, ← op_comp] at heq', exact is_unit_of_mul_eq_one _ _ heq', end /-- If a section `f` is a unit in each stalk, `f` must be a unit. -/ lemma is_unit_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (h : ∀ x : U, is_unit (X.presheaf.germ x f)) : is_unit f := begin -- We pick a cover of `U` by open sets `V x`, such that `f` is a unit on each `V x`. choose V iVU m h_unit using λ x : U, X.is_unit_res_of_is_unit_germ U f x (h x), have hcover : U ≤ supr V, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, -- Let `g x` denote the inverse of `f` in `U x`. choose g hg using λ x : U, is_unit.exists_right_inv (h_unit x), -- We claim that these local inverses glue together to a global inverse of `f`. obtain ⟨gl, gl_spec, -⟩ := X.sheaf.exists_unique_gluing' V U iVU hcover g _, swap, { intros x y, apply section_ext X.sheaf (V x ⊓ V y), rintro ⟨z, hzVx, hzVy⟩, rw [germ_res_apply, germ_res_apply], apply (is_unit.mul_right_inj (h ⟨z, (iVU x).le hzVx⟩)).mp, erw [← X.presheaf.germ_res_apply (iVU x) ⟨z, hzVx⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVx⟩ : V x)) (hg x), germ_res_apply, ← X.presheaf.germ_res_apply (iVU y) ⟨z, hzVy⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVy⟩ : V y)) (hg y), ring_hom.map_one, ring_hom.map_one] }, apply is_unit_of_mul_eq_one f gl, apply X.sheaf.eq_of_locally_eq' V U iVU hcover, intro i, rw [ring_hom.map_one, ring_hom.map_mul, gl_spec], exact hg i, end /-- The basic open of a section `f` is the set of all points `x`, such that the germ of `f` at `x` is a unit. -/ def basic_open {U : opens X} (f : X.presheaf.obj (op U)) : opens X := { val := coe '' { x : U | is_unit (X.presheaf.germ x f) }, property := begin rw is_open_iff_forall_mem_open, rintros _ ⟨x, hx, rfl⟩, obtain ⟨V, i, hxV, hf⟩ := X.is_unit_res_of_is_unit_germ U f x hx, use V.1, refine ⟨_, V.2, hxV⟩, intros y hy, use (⟨y, i.le hy⟩ : U), rw set.mem_set_of_eq, split, { convert ring_hom.is_unit_map (X.presheaf.germ ⟨y, hy⟩) hf, exact (X.presheaf.germ_res_apply i ⟨y, hy⟩ f).symm }, { refl } end } @[simp] lemma mem_basic_open {U : opens X} (f : X.presheaf.obj (op U)) (x : U) : ↑x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ x f) := begin split, { rintro ⟨x, hx, a⟩, cases subtype.eq a, exact hx }, { intro h, exact ⟨x, h, rfl⟩ }, end @[simp] lemma mem_top_basic_open (f : X.presheaf.obj (op ⊤)) (x : X) : x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ ⟨x, show x ∈ (⊤ : opens X), by trivial⟩ f) := mem_basic_open X f ⟨x, _⟩ lemma basic_open_le {U : opens X} (f : X.presheaf.obj (op U)) : X.basic_open f ≤ U := by { rintros _ ⟨x, hx, rfl⟩, exact x.2 } /-- The restriction of a section `f` to the basic open of `f` is a unit. -/ lemma is_unit_res_basic_open {U : opens X} (f : X.presheaf.obj (op U)) : is_unit (X.presheaf.map (@hom_of_le (opens X) _ _ _ (X.basic_open_le f)).op f) := begin apply is_unit_of_is_unit_germ, rintro ⟨_, ⟨x, hx, rfl⟩⟩, convert hx, rw germ_res_apply, refl, end @[simp] lemma basic_open_res {U V : (opens X)ᵒᵖ} (i : U ⟶ V) (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = (unop V) ⊓ @basic_open X (unop U) f := begin induction U using opposite.rec, induction V using opposite.rec, let g := i.unop, have : i = g.op := rfl, clear_value g, subst this, ext, split, { rintro ⟨x, (hx : is_unit _), rfl⟩, rw germ_res_apply at hx, exact ⟨x.2, g x, hx, rfl⟩ }, { rintros ⟨hxV, x, hx, rfl⟩, refine ⟨⟨x, hxV⟩, (_ : is_unit _), rfl⟩, rwa germ_res_apply } end -- This should fire before `basic_open_res`. @[simp, priority 1100] lemma basic_open_res_eq {U V : (opens X)ᵒᵖ} (i : U ⟶ V) [is_iso i] (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = @RingedSpace.basic_open X (unop U) f := begin apply le_antisymm, { rw X.basic_open_res i f, exact inf_le_right }, { have := X.basic_open_res (inv i) (X.presheaf.map i f), rw [← comp_apply, ← X.presheaf.map_comp, is_iso.hom_inv_id, X.presheaf.map_id] at this, erw this, exact inf_le_right } end @[simp] lemma basic_open_mul {U : opens X} (f g : X.presheaf.obj (op U)) : X.basic_open (f * g) = X.basic_open f ⊓ X.basic_open g := begin ext1, dsimp [RingedSpace.basic_open], rw set.image_inter subtype.coe_injective, congr, ext, simp_rw map_mul, exact is_unit.mul_iff, end lemma basic_open_of_is_unit {U : opens X} {f : X.presheaf.obj (op U)} (hf : is_unit f) : X.basic_open f = U := begin apply le_antisymm, { exact X.basic_open_le f }, intros x hx, erw X.mem_basic_open f (⟨x, hx⟩ : U), exact ring_hom.is_unit_map _ hf end end RingedSpace end algebraic_geometry
8cc36c02b19d1b1b2e719766a4f05836c4a229b8
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/uniform_space/basic.lean
e4790229b9e97541070d457daffb6edd3fe0253e
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
70,499
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 order.filter.lift import topology.separation /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ open set filter classical open_locale classical topological_space filter set_option eqn_compiler.zeta true universes u /-! ### Relations, seen as `set (α × α)` -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} localized "infix ` ○ `:55 := comp_rel" in uniformity @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ @[mono] lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k := λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ s ○ t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : (r ○ s) ○ t = r ○ (s ○ t) := by ext p; cases p; simp only [mem_comp_rel]; tauto lemma subset_comp_self {α : Type*} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s := λ ⟨x, y⟩ xy_in, ⟨x, h (by rw mem_id_rel), xy_in⟩ /-- The relation is invariant under swapping factors. -/ def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp] lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V := sep_subset _ _ @[mono] lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := inter_subset_inter h $ preimage_mono h lemma symmetric_rel_inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) := begin unfold symmetric_rel at *, rw [preimage_inter, hU, hV], end /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : 𝓟 id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, s ○ s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h } -- the topological structure is embedded in the uniform structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, t ○ t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α := begin apply (𝓤 α).inter_sets h, rw [← image_swap_eq_preimage_swap, uniformity_eq_symm], exact image_mem_map h, end theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (s ○ s)) = ((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, d ○ (d ○ d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), s ○ s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s := begin obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs, use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w], have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w, calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono ... ⊆ s : w_sub, end lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s := subset_comp_self (refl_le_uniformity h) lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s := begin rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩, rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩, use [t, t_in, t_symm], have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in, calc t ○ t ○ t ⊆ w ○ t : by mono ... ⊆ w ○ (t ○ t) : by mono ... ⊆ w ○ w : by mono ... ⊆ s : w_sub, end /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V open uniform_space (ball) lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) : x ∈ ball x V := refl_mem_uniformity hV /-- The triangle inequality for `uniform_space.ball` -/ lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W) := prod_mk_mem_comp_rel h h' lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) : ball x W ⊆ ball y V := λ z z_in, h' (mem_ball_comp h z_in) lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W := by tauto lemma ball_inter_left (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x V := ball_mono (inter_subset_left V W) x lemma ball_inter_right (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x W := ball_mono (inter_subset_right V W) x lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} : x ∈ ball y V ↔ y ∈ ball x V := show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV } lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} : ball x V = {y | (y, x) ∈ V} := by { ext y, rw mem_ball_symmetry hV, exact iff.rfl } lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V) (hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W := begin rw mem_ball_symmetry hV at hx, exact ⟨z, hx, hy⟩ end lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) : is_open (ball x V) := hV.preimage $ continuous_const.prod_mk continuous_id lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} : p ∈ V ○ M ○ W ↔ ((ball p.1 V).prod (ball p.2 W) ∩ M).nonempty := begin cases p with x y, split, { rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩, exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, }, { rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩, rwa mem_ball_symmetry hW' at z_in, use [z, w] ; tauto }, end /-! ### Neighborhoods in uniform spaces -/ lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} : {p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F := by rw mem_comap ; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, F.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux } /-- See also `is_open_iff_open_ball_subset`. -/ lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity], exact iff.rfl, end lemma nhds_basis_uniformity' {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, ball x (s i)) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin rw [nhds_eq_comap_uniformity, mem_comap], exact iff.rfl, end lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x := begin rw uniform_space.mem_nhds_iff, exact ⟨V, V_in, subset.refl _⟩ end lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s := begin rw uniform_space.mem_nhds_iff, split, { rintros ⟨V, V_in, V_sub⟩, use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V], exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub }, { rintros ⟨V, V_in, V_symm, V_sub⟩, exact ⟨V, V_in, V_sub⟩ } end lemma uniform_space.has_basis_nhds (x : α) : has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) := ⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩ open uniform_space lemma uniform_space.mem_closure_iff_symm_ball {s : set α} {x} : x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (s ∩ ball x V).nonempty := begin simp [mem_closure_iff_nhds_basis (has_basis_nhds x)], tauto, end lemma uniform_space.mem_closure_iff_ball {s : set α} {x} : x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → (ball x V ∩ s).nonempty := begin simp_rw [mem_closure_iff_nhds, uniform_space.mem_nhds_iff], split, { intros h V V_in, exact h (ball x V) ⟨V, V_in, subset.refl _⟩ }, { rintros h t ⟨V, V_in, Vt⟩, exact nonempty.mono (inter_subset_inter_left s Vt) (h V_in) }, end lemma uniform_space.has_basis_nhds_prod (x y : α) : has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, (ball x s).prod (ball y s) := begin rw nhds_prod_eq, apply (has_basis_nhds x).prod' (has_basis_nhds y), rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩, exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, symmetric_rel_inter U_symm V_symm⟩, ball_inter_left x U V, ball_inter_right y U V⟩, end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := ball_mem_nhds x h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : 𝓝 a ×ᶠ 𝓝 b = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, 𝓟 (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, _root_.mem_nhds_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end /-- Entourages are neighborhoods of the diagonal. -/ lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α := begin intros V V_in, rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩, have : (ball x w).prod (ball x w) ∈ 𝓝 (x, x), { rw nhds_prod_eq, exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) }, apply mem_of_superset this, rintros ⟨u, v⟩ ⟨u_in, v_in⟩, exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in) end /-- Entourages are neighborhoods of the diagonal. -/ lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α := supr_le nhds_le_uniformity /-! ### Closure and interior in uniform spaces -/ lemma closure_eq_uniformity (s : set $ α × α) : closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V := begin ext ⟨x, y⟩, simp_rw [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter, mem_set_of_eq], apply forall_congr, intro V, apply forall_congr, rintros ⟨V_in, V_symm⟩, simp_rw [mem_comp_comp V_symm, inter_comm, exists_prop], exact iff.rfl, end lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id := begin refine filter.has_basis_self.2 (λ t h, _), rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩, refine ⟨closure w, mem_of_superset w_in subset_closure, is_closed_closure, _⟩, refine subset.trans _ r, rw closure_eq_uniformity, apply Inter_subset_of_subset, apply Inter_subset, exact ⟨w_in, w_symm⟩ end /-- Closed entourages form a basis of the uniformity filter. -/ lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure := ⟨begin intro t, rw uniformity_has_basis_closed.mem_iff, split, { rintros ⟨r, ⟨r_in, r_closed⟩, r_sub⟩, use [r, r_in], convert r_sub, rw r_closed.closure_eq, refl }, { rintros ⟨r, r_in, r_sub⟩, exact ⟨closure r, ⟨mem_of_superset r_in subset_closure, is_closed_closure⟩, r_sub⟩ } end⟩ lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ 𝓟 t ≠ ⊥) : mem_closure_iff_nhds_ne_bot ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, ← ne_bot_iff, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in ⟨t, ht_mem, htc, hts⟩ lemma is_open_iff_open_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, is_open V ∧ ball x V ⊆ s := begin rw is_open_iff_ball_subset, split; intros h x hx, { obtain ⟨V, hV, hV'⟩ := h x hx, exact ⟨interior V, interior_mem_uniformity hV, is_open_interior, (ball_mono interior_subset x).trans hV'⟩, }, { obtain ⟨V, hV, -, hV'⟩ := h x hx, exact ⟨V, hV, hV'⟩, }, end /-- The uniform neighborhoods of all points of a dense set cover the whole space. -/ lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) : (⋃ x ∈ s, ball x U) = univ := begin refine bUnion_eq_univ_iff.2 (λ y, _), rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩, exact ⟨x, hxs, hxy⟩ end /-! ### Uniformity bases -/ /-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id := has_basis_self.2 $ λ s hs, ⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩ lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] /-- Symmetric entourages form a basis of `𝓤 α` -/ lemma uniform_space.has_basis_symmetric : (𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id := has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in, symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩ /-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open_symmetric : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id := begin simp only [← and_assoc], refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩), exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open.inter hs.2 (hs.2.preimage continuous_swap)⟩, symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩ end lemma uniform_space.has_seq_basis (h : is_countably_generated $ 𝓤 α) : ∃ V : ℕ → set (α × α), has_antimono_basis (𝓤 α) (λ _, true) V ∧ ∀ n, symmetric_rel (V n) := let ⟨U, hsym, hbasis⟩ := h.exists_antimono_subbasis uniform_space.has_basis_symmetric in ⟨U, hbasis, λ n, (hsym n).2⟩ /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) /-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `s`.-/ def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop := tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s.prod s)) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r := iff.rfl theorem uniform_continuous_on_univ [uniform_space β] {f : α → β} : uniform_continuous_on f univ ↔ uniform_continuous f := by rw [uniform_continuous_on, uniform_continuous, univ_prod_univ, principal_univ, inf_top_eq] lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} : uniform_continuous_on f S ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i := ((ha.inf_principal (S.prod S)).tendsto_iff hb).trans $ by finish [prod.forall] end uniform_space open_locale uniformity section constructions instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := 𝓟 id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓤 α = comap (prod.map f f) (𝓤 β) := by { rw h, refl } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) : @nhds _ (@uniform_space.to_topological_space _ u₁) a ≤ @nhds _ (@uniform_space.to_topological_space _ u₂) a := by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl) lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ to_nhds_mono h lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := begin casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, to_topological_space_top] }, { refine (eq_of_nhds_eq_nhds $ assume a, _), rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, rw [infi_uniformity, lift'_infi], { simp only [nhds_eq_uniformity], refl }, { exact assume a b, rfl } }, end lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi], simp only [← to_topological_space_infi], end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space punit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) := begin unfold uniform_continuous_on set.restrict uniform_continuous tendsto, rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl, uniformity_comap rfl, show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl], conv in (map _ (comap _ _)) { rw ← filter.map_map }, rw subtype_coe_map_comap_prod, refl, end lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_mem_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (h : uniform_continuous_on f s) : continuous_on f s := begin rw uniform_continuous_on_iff_restrict at h, rw continuous_on_iff_continuous_restrict, exact h.continuous end section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap] lemma mem_map_iff_exists_image' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_iff_exists_image lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_iff_exists_image'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_iff_exists_image.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_iff_exists_image.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_iff_exists_image.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_iff_exists_image.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.1 xs)) univ_mem) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_of_superset (union_mem_uniformity_sum univ_mem (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_iff_exists_image.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_iff_exists_image.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean /-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/ lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, (bInter_mem b_fin).2 bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end /-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/ lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-- A useful consequence of the Lebesgue number lemma: given any compact set `K` contained in an open set `U`, we can find an (open) entourage `V` such that the ball of size `V` about any point of `K` is contained in `U`. -/ lemma lebesgue_number_of_compact_open [uniform_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V ∈ 𝓤 α, is_open V ∧ ∀ x ∈ K, uniform_space.ball x V ⊆ U := begin let W : K → set (α × α) := λ k, classical.some $ is_open_iff_open_ball_subset.mp hU k.1 $ hKU k.2, have hW : ∀ k, W k ∈ 𝓤 α ∧ is_open (W k) ∧ uniform_space.ball k.1 (W k) ⊆ U, { intros k, obtain ⟨h₁, h₂, h₃⟩ := classical.some_spec (is_open_iff_open_ball_subset.mp hU k.1 (hKU k.2)), exact ⟨h₁, h₂, h₃⟩, }, let c : K → set α := λ k, uniform_space.ball k.1 (W k), have hc₁ : ∀ k, is_open (c k), { exact λ k, uniform_space.is_open_ball k.1 (hW k).2.1, }, have hc₂ : K ⊆ ⋃ i, c i, { intros k hk, simp only [mem_Union, set_coe.exists], exact ⟨k, hk, uniform_space.mem_ball_self k (hW ⟨k, hk⟩).1⟩, }, have hc₃ : ∀ k, c k ⊆ U, { exact λ k, (hW k).2.2, }, obtain ⟨V, hV, hV'⟩ := lebesgue_number_lemma hK hc₁ hc₂, refine ⟨interior V, interior_mem_uniformity hV, is_open_interior, _⟩, intros k hk, obtain ⟨k', hk'⟩ := hV' k hk, exact ((ball_mono interior_subset k).trans hk').trans (hc₃ k'), end /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) := ⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _), λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩ theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
7f331ebfdfec42c38ef7c1caeeca5ebbf6e005a3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/mv_polynomial/division.lean
5784eda1e59b6bc4f3b87f7d400ce6ea845bd367
[ "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
8,157
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.monoid_algebra.division import data.mv_polynomial.basic /-! # Division of `mv_polynomial` by monomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `mv_polynomial.div_monomial x s`: divides `x` by the monomial `mv_polynomial.monomial 1 s` * `mv_polynomial.mod_monomial x s`: the remainder upon dividing `x` by the monomial `mv_polynomial.monomial 1 s`. ## Main results * `mv_polynomial.div_monomial_add_mod_monomial`, `mv_polynomial.mod_monomial_add_div_monomial`: `div_monomial` and `mod_monomial` are well-behaved as quotient and remainder operators. ## Implementation notes Where possible, the results in this file should be first proved in the generality of `add_monoid_algebra`, and then the versions specialized to `mv_polynomial` proved in terms of these. -/ variables {σ R : Type*} [comm_semiring R] namespace mv_polynomial section copied_declarations /-! Please ensure the declarations in this section are direct translations of `add_monoid_algebra` results. -/ /-- Divide by `monomial 1 s`, discarding terms not divisible by this. -/ noncomputable def div_monomial (p : mv_polynomial σ R) (s : σ →₀ ℕ) : mv_polynomial σ R := add_monoid_algebra.div_of p s local infix ` /ᵐᵒⁿᵒᵐⁱᵃˡ `:70 := div_monomial @[simp] lemma coeff_div_monomial (s : σ →₀ ℕ) (x : mv_polynomial σ R) (s' : σ →₀ ℕ) : coeff s' (x /ᵐᵒⁿᵒᵐⁱᵃˡ s) = coeff (s + s') x := rfl @[simp] lemma support_div_monomial (s : σ →₀ ℕ) (x : mv_polynomial σ R) : (x /ᵐᵒⁿᵒᵐⁱᵃˡ s).support = x.support.preimage _ ((add_right_injective s).inj_on _) := rfl @[simp] lemma zero_div_monomial (s : σ →₀ ℕ) : (0 : mv_polynomial σ R) /ᵐᵒⁿᵒᵐⁱᵃˡ s = 0 := add_monoid_algebra.zero_div_of _ lemma div_monomial_zero (x : mv_polynomial σ R) : x /ᵐᵒⁿᵒᵐⁱᵃˡ 0 = x := x.div_of_zero lemma add_div_monomial (x y : mv_polynomial σ R) (s : σ →₀ ℕ) : (x + y) /ᵐᵒⁿᵒᵐⁱᵃˡ s = x /ᵐᵒⁿᵒᵐⁱᵃˡ s + y /ᵐᵒⁿᵒᵐⁱᵃˡ s := map_add _ _ _ lemma div_monomial_add (a b : σ →₀ ℕ) (x : mv_polynomial σ R) : x /ᵐᵒⁿᵒᵐⁱᵃˡ (a + b) = (x /ᵐᵒⁿᵒᵐⁱᵃˡ a) /ᵐᵒⁿᵒᵐⁱᵃˡ b := x.div_of_add _ _ @[simp] lemma div_monomial_monomial_mul (a : σ →₀ ℕ) (x : mv_polynomial σ R) : (monomial a 1 * x) /ᵐᵒⁿᵒᵐⁱᵃˡ a = x := x.of'_mul_div_of _ @[simp] lemma div_monomial_mul_monomial (a : σ →₀ ℕ) (x : mv_polynomial σ R) : (x * monomial a 1) /ᵐᵒⁿᵒᵐⁱᵃˡ a = x := x.mul_of'_div_of _ @[simp] lemma div_monomial_monomial (a : σ →₀ ℕ) : (monomial a 1) /ᵐᵒⁿᵒᵐⁱᵃˡ a = (1 : mv_polynomial σ R) := add_monoid_algebra.of'_div_of _ /-- The remainder upon division by `monomial 1 s`. -/ noncomputable def mod_monomial (x : mv_polynomial σ R) (s : σ →₀ ℕ) : mv_polynomial σ R := x.mod_of s local infix ` %ᵐᵒⁿᵒᵐⁱᵃˡ `:70 := mod_monomial @[simp] lemma coeff_mod_monomial_of_not_le {s' s : σ →₀ ℕ} (x : mv_polynomial σ R) (h : ¬s ≤ s') : coeff s' (x %ᵐᵒⁿᵒᵐⁱᵃˡ s) = coeff s' x := x.mod_of_apply_of_not_exists_add s s' begin rintro ⟨d, rfl⟩, exact h le_self_add, end @[simp] lemma coeff_mod_monomial_of_le {s' s : σ →₀ ℕ} (x : mv_polynomial σ R) (h : s ≤ s') : coeff s' (x %ᵐᵒⁿᵒᵐⁱᵃˡ s) = 0 := x.mod_of_apply_of_exists_add _ _ $ exists_add_of_le h @[simp] lemma monomial_mul_mod_monomial (s : σ →₀ ℕ) (x : mv_polynomial σ R) : (monomial s 1 * x) %ᵐᵒⁿᵒᵐⁱᵃˡ s = 0 := x.of'_mul_mod_of _ @[simp] lemma mul_monomial_mod_monomial (s : σ →₀ ℕ) (x : mv_polynomial σ R): (x * monomial s 1) %ᵐᵒⁿᵒᵐⁱᵃˡ s = 0 := x.mul_of'_mod_of _ @[simp] lemma monomial_mod_monomial (s : σ →₀ ℕ) : (monomial s (1 : R)) %ᵐᵒⁿᵒᵐⁱᵃˡ s = 0 := add_monoid_algebra.of'_mod_of _ lemma div_monomial_add_mod_monomial (x : mv_polynomial σ R) (s : σ →₀ ℕ) : monomial s 1 * (x /ᵐᵒⁿᵒᵐⁱᵃˡ s) + x %ᵐᵒⁿᵒᵐⁱᵃˡ s = x := add_monoid_algebra.div_of_add_mod_of x s lemma mod_monomial_add_div_monomial (x : mv_polynomial σ R) (s : σ →₀ ℕ) : x %ᵐᵒⁿᵒᵐⁱᵃˡ s + monomial s 1 * (x /ᵐᵒⁿᵒᵐⁱᵃˡ s) = x := add_monoid_algebra.mod_of_add_div_of x s lemma monomial_one_dvd_iff_mod_monomial_eq_zero {i : σ →₀ ℕ} {x : mv_polynomial σ R} : monomial i (1 : R) ∣ x ↔ x %ᵐᵒⁿᵒᵐⁱᵃˡ i = 0 := add_monoid_algebra.of'_dvd_iff_mod_of_eq_zero end copied_declarations section X_lemmas local infix ` /ᵐᵒⁿᵒᵐⁱᵃˡ `:70 := div_monomial local infix ` %ᵐᵒⁿᵒᵐⁱᵃˡ `:70 := mod_monomial @[simp] lemma X_mul_div_monomial (i : σ) (x : mv_polynomial σ R) : (X i * x) /ᵐᵒⁿᵒᵐⁱᵃˡ (finsupp.single i 1) = x := div_monomial_monomial_mul _ _ @[simp] lemma X_div_monomial (i : σ) : (X i : mv_polynomial σ R) /ᵐᵒⁿᵒᵐⁱᵃˡ (finsupp.single i 1) = 1 := (div_monomial_monomial (finsupp.single i 1)) @[simp] lemma mul_X_div_monomial (x : mv_polynomial σ R) (i : σ) : (x * X i) /ᵐᵒⁿᵒᵐⁱᵃˡ (finsupp.single i 1) = x := div_monomial_mul_monomial _ _ @[simp] lemma X_mul_mod_monomial (i : σ) (x : mv_polynomial σ R) : (X i * x) %ᵐᵒⁿᵒᵐⁱᵃˡ (finsupp.single i 1) = 0 := monomial_mul_mod_monomial _ _ @[simp] lemma mul_X_mod_monomial (x : mv_polynomial σ R) (i : σ) : (x * X i) %ᵐᵒⁿᵒᵐⁱᵃˡ (finsupp.single i 1) = 0 := mul_monomial_mod_monomial _ _ @[simp] lemma mod_monomial_X (i : σ) : (X i : mv_polynomial σ R) %ᵐᵒⁿᵒᵐⁱᵃˡ (finsupp.single i 1) = 0 := monomial_mod_monomial _ lemma div_monomial_add_mod_monomial_single (x : mv_polynomial σ R) (i : σ) : X i * (x /ᵐᵒⁿᵒᵐⁱᵃˡ finsupp.single i 1) + x %ᵐᵒⁿᵒᵐⁱᵃˡ finsupp.single i 1 = x := div_monomial_add_mod_monomial _ _ lemma mod_monomial_add_div_monomial_single (x : mv_polynomial σ R) (i : σ) : x %ᵐᵒⁿᵒᵐⁱᵃˡ finsupp.single i 1 + X i * (x /ᵐᵒⁿᵒᵐⁱᵃˡ finsupp.single i 1) = x := mod_monomial_add_div_monomial _ _ lemma X_dvd_iff_mod_monomial_eq_zero {i : σ} {x : mv_polynomial σ R} : X i ∣ x ↔ x %ᵐᵒⁿᵒᵐⁱᵃˡ finsupp.single i 1 = 0 := monomial_one_dvd_iff_mod_monomial_eq_zero end X_lemmas /-! ### Some results about dvd (`∣`) on `monomial` and `X` -/ lemma monomial_dvd_monomial {r s : R} {i j : σ →₀ ℕ} : monomial i r ∣ monomial j s ↔ (s = 0 ∨ i ≤ j) ∧ r ∣ s := begin split, { rintro ⟨x, hx⟩, rw mv_polynomial.ext_iff at hx, have hj := hx j, have hi := hx i, classical, simp_rw [coeff_monomial, if_pos] at hj hi, simp_rw [coeff_monomial_mul', if_pos] at hi hj, split_ifs at hi hj with hi hi, { exact ⟨or.inr hi, _, hj⟩ }, { exact ⟨or.inl hj, hj.symm ▸ dvd_zero _⟩ } }, { rintro ⟨h | hij, d, rfl⟩, { simp_rw [h, monomial_zero, dvd_zero] }, { refine ⟨monomial (j - i) d, _⟩, rw [monomial_mul, add_tsub_cancel_of_le hij] } } end @[simp] lemma monomial_one_dvd_monomial_one [nontrivial R] {i j : σ →₀ ℕ} : monomial i (1 : R) ∣ monomial j 1 ↔ i ≤ j := begin rw monomial_dvd_monomial, simp_rw [one_ne_zero, false_or, dvd_rfl, and_true], end @[simp] lemma X_dvd_X [nontrivial R] {i j : σ} : (X i : mv_polynomial σ R) ∣ (X j : mv_polynomial σ R) ↔ i = j := begin refine monomial_one_dvd_monomial_one.trans _, simp_rw [finsupp.single_le_iff, nat.one_le_iff_ne_zero, finsupp.single_apply_ne_zero, ne.def, one_ne_zero, not_false_iff, and_true], end @[simp] lemma X_dvd_monomial {i : σ} {j : σ →₀ ℕ} {r : R} : (X i : mv_polynomial σ R) ∣ monomial j r ↔ (r = 0 ∨ j i ≠ 0) := begin refine monomial_dvd_monomial.trans _, simp_rw [one_dvd, and_true, finsupp.single_le_iff, nat.one_le_iff_ne_zero], end end mv_polynomial
0c53bbd2b34e11852c40e0326d37d5c503bae188
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Meta/Tactic/Apply.lean
99bafafb81c423183b194482911820cf6208af28
[ "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
4,200
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.FindMVar import Lean.Meta.ExprDefEq import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Util namespace Lean namespace Meta /- Compute the number of expected arguments and whether the result type is of the form (?m ...) where ?m is an unassigned metavariable. -/ private def getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) := withReducible $ forallTelescopeReducing e $ fun xs body => pure (xs.size, body.getAppFn.isMVar) private def getExpectedNumArgs (e : Expr) : MetaM Nat := do (numArgs, _) ← getExpectedNumArgsAux e; pure numArgs private def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α := throwTacticEx `apply mvarId ("failed to unify" ++ indentExpr eType ++ Format.line ++ "with" ++ indentExpr targetType) def synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := newMVars.size.forM $ fun i => when (binderInfos.get! i).isInstImplicit $ do let mvar := newMVars.get! i; mvarType ← inferType mvar; mvarVal ← synthInstance mvarType; unlessM (isDefEq mvar mvarVal) $ throwTacticEx tacticName mvarId ("failed to assign synthesized instance") def appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do parentTag ← getMVarTag mvarId; if newMVars.size == 1 then -- if there is only one subgoal, we inherit the parent tag setMVarTag (newMVars.get! 0).mvarId! parentTag else unless parentTag.isAnonymous $ newMVars.size.forM $ fun i => let newMVarId := (newMVars.get! i).mvarId!; unlessM (isExprMVarAssigned newMVarId) $ unless (binderInfos.get! i).isInstImplicit $ do currTag ← getMVarTag newMVarId; setMVarTag newMVarId (appendTag parentTag currTag) def postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do synthAppInstances tacticName mvarId newMVars binderInfos; -- TODO: default and auto params appendParentTag mvarId newMVars binderInfos private def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool := otherMVars.anyM $ fun otherMVar => if mvar == otherMVar then pure false else do otherMVarType ← inferType otherMVar; pure $ (otherMVarType.findMVar? $ fun mvarId => mvarId == mvar.mvarId!).isSome private def reorderNonDependentFirst (newMVars : Array Expr) : MetaM (List MVarId) := do (nonDeps, deps) ← newMVars.foldlM (fun (acc : Array MVarId × Array MVarId) (mvar : Expr) => do let (nonDeps, deps) := acc; let currMVarId := mvar.mvarId!; condM (dependsOnOthers mvar newMVars) (pure (nonDeps, deps.push currMVarId)) (pure (nonDeps.push currMVarId, deps))) (#[], #[]); pure $ nonDeps.toList ++ deps.toList inductive ApplyNewGoals | nonDependentFirst | nonDependentOnly | all def apply (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) := withMVarContext mvarId $ do checkNotAssigned mvarId `apply; targetType ← getMVarType mvarId; eType ← inferType e; (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType; numArgs ← if !hasMVarHead then pure numArgs else do { targetTypeNumArgs ← getExpectedNumArgs targetType; pure (numArgs - targetTypeNumArgs) }; (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType (some numArgs); unlessM (isDefEq eType targetType) $ throwApplyError mvarId eType targetType; postprocessAppMVars `apply mvarId newMVars binderInfos; e ← instantiateMVars e; assignExprMVar mvarId (mkAppN e newMVars); newMVars ← newMVars.filterM $ fun mvar => not <$> isExprMVarAssigned mvar.mvarId!; otherMVarIds ← getMVarsNoDelayed e; -- TODO: add option `ApplyNewGoals` and implement other orders newMVarIds ← reorderNonDependentFirst newMVars; let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId; pure $ newMVarIds ++ otherMVarIds.toList end Meta end Lean
f14874d052ebac19c6e0642c8c052ea4293a465f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/default.lean
71f92b175117345144d536f1c798fa30ac5c7b83
[]
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
440
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Michael Howes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.type_tags import Mathlib.algebra.group.conj import Mathlib.algebra.group.with_one import Mathlib.algebra.group.units_hom import Mathlib.PostPort namespace Mathlib
850d0b972ee8cc915f1f58c82174995a7f3ed1c2
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/examples/vector.lean
d593dbe0bc5f08b62bd6997e9b264c56006c64b4
[ "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
13,178
lean
/- 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, Leonardo de Moura This file demonstrates how to encode vectors using indexed inductive families. In standard library we do not use this approach. -/ import data.nat data.list data.fin open nat prod fin inductive vector (A : Type) : nat → Type := | nil {} : vector A zero | cons : Π {n}, A → vector A n → vector A (succ n) namespace vector notation a :: b := cons a b notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l variables {A B C : Type} protected definition is_inhabited [instance] [h : inhabited A] : ∀ (n : nat), inhabited (vector A n) | 0 := inhabited.mk [] | (n+1) := inhabited.mk (inhabited.value h :: inhabited.value (is_inhabited n)) theorem vector0_eq_nil : ∀ (v : vector A 0), v = [] | [] := rfl definition head : Π {n : nat}, vector A (succ n) → A | n (a::v) := a definition tail : Π {n : nat}, vector A (succ n) → vector A n | n (a::v) := v theorem head_cons {n : nat} (h : A) (t : vector A n) : head (h :: t) = h := rfl theorem tail_cons {n : nat} (h : A) (t : vector A n) : tail (h :: t) = t := rfl theorem eta : ∀ {n : nat} (v : vector A (succ n)), head v :: tail v = v | n (a::v) := rfl definition last : Π {n : nat}, vector A (succ n) → A | last [a] := a | last (a::v) := last v theorem last_singleton (a : A) : last [a] = a := rfl theorem last_cons {n : nat} (a : A) (v : vector A (succ n)) : last (a :: v) = last v := rfl definition const : Π (n : nat), A → vector A n | 0 a := [] | (succ n) a := a :: const n a theorem head_const (n : nat) (a : A) : head (const (succ n) a) = a := rfl theorem last_const : ∀ (n : nat) (a : A), last (const (succ n) a) = a | 0 a := rfl | (n+1) a := last_const n a definition nth : Π {n : nat}, vector A n → fin n → A | ⌞0⌟ [] i := elim0 i | ⌞n+1⌟ (a :: v) (mk 0 _) := a | ⌞n+1⌟ (a :: v) (mk (succ i) h) := nth v (mk_pred i h) lemma nth_zero {n : nat} (a : A) (v : vector A n) (h : 0 < succ n) : nth (a::v) (mk 0 h) = a := rfl lemma nth_succ {n : nat} (a : A) (v : vector A n) (i : nat) (h : succ i < succ n) : nth (a::v) (mk (succ i) h) = nth v (mk_pred i h) := rfl definition tabulate : Π {n : nat}, (fin n → A) → vector A n | 0 f := [] | (n+1) f := f (fin.zero n) :: tabulate (λ i : fin n, f (succ i)) theorem nth_tabulate : ∀ {n : nat} (f : fin n → A) (i : fin n), nth (tabulate f) i = f i | 0 f i := elim0 i | (n+1) f (mk 0 h) := by reflexivity | (n+1) f (mk (succ i) h) := begin change nth (f (fin.zero n) :: tabulate (λ i : fin n, f (succ i))) (mk (succ i) h) = f (mk (succ i) h), rewrite nth_succ, rewrite nth_tabulate end definition map (f : A → B) : Π {n : nat}, vector A n → vector B n | map [] := [] | map (a::v) := f a :: map v theorem map_nil (f : A → B) : map f [] = [] := rfl theorem map_cons {n : nat} (f : A → B) (h : A) (t : vector A n) : map f (h :: t) = f h :: map f t := rfl theorem nth_map (f : A → B) : ∀ {n : nat} (v : vector A n) (i : fin n), nth (map f v) i = f (nth v i) | 0 v i := elim0 i | (succ n) (a :: t) (mk 0 h) := by reflexivity | (succ n) (a :: t) (mk (succ i) h) := by rewrite [map_cons, *nth_succ, nth_map] section open function theorem map_id : ∀ {n : nat} (v : vector A n), map id v = v | 0 [] := rfl | (succ n) (x::xs) := by rewrite [map_cons, map_id] theorem map_map (g : B → C) (f : A → B) : ∀ {n :nat} (v : vector A n), map g (map f v) = map (g ∘ f) v | 0 [] := rfl | (succ n) (a :: l) := show (g ∘ f) a :: map g (map f l) = map (g ∘ f) (a :: l), by rewrite (map_map l) end definition map2 (f : A → B → C) : Π {n : nat}, vector A n → vector B n → vector C n | map2 [] [] := [] | map2 (a::va) (b::vb) := f a b :: map2 va vb theorem map2_nil (f : A → B → C) : map2 f [] [] = [] := rfl theorem map2_cons {n : nat} (f : A → B → C) (h₁ : A) (h₂ : B) (t₁ : vector A n) (t₂ : vector B n) : map2 f (h₁ :: t₁) (h₂ :: t₂) = f h₁ h₂ :: map2 f t₁ t₂ := rfl definition append : Π {n m : nat}, vector A n → vector A m → vector A (n ⊕ m) | 0 m [] w := w | (succ n) m (a::v) w := a :: (append v w) theorem append_nil_left {n : nat} (v : vector A n) : append [] v = v := rfl theorem append_cons {n m : nat} (h : A) (t : vector A n) (v : vector A m) : append (h::t) v = h :: (append t v) := rfl theorem map_append (f : A → B) : ∀ {n m : nat} (v : vector A n) (w : vector A m), map f (append v w) = append (map f v) (map f w) | 0 m [] w := rfl | (n+1) m (h :: t) w := begin change (f h :: map f (append t w) = f h :: append (map f t) (map f w)), rewrite map_append end definition unzip : Π {n : nat}, vector (A × B) n → vector A n × vector B n | unzip [] := ([], []) | unzip ((a, b) :: v) := (a :: pr₁ (unzip v), b :: pr₂ (unzip v)) theorem unzip_nil : unzip (@nil (A × B)) = ([], []) := rfl theorem unzip_cons {n : nat} (a : A) (b : B) (v : vector (A × B) n) : unzip ((a, b) :: v) = (a :: pr₁ (unzip v), b :: pr₂ (unzip v)) := rfl definition zip : Π {n : nat}, vector A n → vector B n → vector (A × B) n | zip [] [] := [] | zip (a::va) (b::vb) := ((a, b) :: zip va vb) theorem zip_nil_nil : zip (@nil A) (@nil B) = nil := rfl theorem zip_cons_cons {n : nat} (a : A) (b : B) (va : vector A n) (vb : vector B n) : zip (a::va) (b::vb) = ((a, b) :: zip va vb) := rfl theorem unzip_zip : ∀ {n : nat} (v₁ : vector A n) (v₂ : vector B n), unzip (zip v₁ v₂) = (v₁, v₂) | 0 [] [] := rfl | (n+1) (a::va) (b::vb) := calc unzip (zip (a :: va) (b :: vb)) = (a :: pr₁ (unzip (zip va vb)), b :: pr₂ (unzip (zip va vb))) : rfl ... = (a :: pr₁ (va, vb), b :: pr₂ (va, vb)) : by rewrite unzip_zip ... = (a :: va, b :: vb) : rfl theorem zip_unzip : ∀ {n : nat} (v : vector (A × B) n), zip (pr₁ (unzip v)) (pr₂ (unzip v)) = v | 0 [] := rfl | (n+1) ((a, b) :: v) := calc zip (pr₁ (unzip ((a, b) :: v))) (pr₂ (unzip ((a, b) :: v))) = (a, b) :: zip (pr₁ (unzip v)) (pr₂ (unzip v)) : rfl ... = (a, b) :: v : by rewrite zip_unzip /- Concat -/ definition concat : Π {n : nat}, vector A n → A → vector A (succ n) | concat [] a := [a] | concat (b::v) a := b :: concat v a theorem concat_nil (a : A) : concat [] a = [a] := rfl theorem concat_cons {n : nat} (b : A) (v : vector A n) (a : A) : concat (b :: v) a = b :: concat v a := rfl theorem last_concat : ∀ {n : nat} (v : vector A n) (a : A), last (concat v a) = a | 0 [] a := rfl | (n+1) (b::v) a := calc last (concat (b::v) a) = last (concat v a) : rfl ... = a : last_concat v a /- Reverse -/ definition reverse : Π {n : nat}, vector A n → vector A n | 0 [] := [] | (n+1) (x :: xs) := concat (reverse xs) x theorem reverse_concat : Π {n : nat} (xs : vector A n) (a : A), reverse (concat xs a) = a :: reverse xs | 0 [] a := rfl | (n+1) (x :: xs) a := begin change (concat (reverse (concat xs a)) x = a :: reverse (x :: xs)), rewrite reverse_concat end theorem reverse_reverse : Π {n : nat} (xs : vector A n), reverse (reverse xs) = xs | 0 [] := rfl | (n+1) (x :: xs) := begin change (reverse (concat (reverse xs) x) = x :: xs), rewrite [reverse_concat, reverse_reverse] end /- list <-> vector -/ definition of_list : Π (l : list A), vector A (list.length l) | list.nil := [] | (list.cons a l) := a :: (of_list l) definition to_list : Π {n : nat}, vector A n → list A | 0 [] := list.nil | (n+1) (a :: vs) := list.cons a (to_list vs) theorem to_list_of_list : ∀ (l : list A), to_list (of_list l) = l | list.nil := rfl | (list.cons a l) := begin change (list.cons a (to_list (of_list l)) = list.cons a l), rewrite to_list_of_list end theorem to_list_nil : to_list [] = (list.nil : list A) := rfl theorem length_to_list : ∀ {n : nat} (v : vector A n), list.length (to_list v) = n | 0 [] := rfl | (n+1) (a :: vs) := begin change (succ (list.length (to_list vs)) = succ n), rewrite length_to_list end theorem heq_of_list_eq : ∀ {n m} {v₁ : vector A n} {v₂ : vector A m}, to_list v₁ = to_list v₂ → n = m → v₁ == v₂ | 0 0 [] [] h₁ h₂ := !heq.refl | 0 (m+1) [] (y::ys) h₁ h₂ := by contradiction | (n+1) 0 (x::xs) [] h₁ h₂ := by contradiction | (n+1) (m+1) (x::xs) (y::ys) h₁ h₂ := have e₁ : n = m, from succ.inj h₂, have e₂ : x = y, begin unfold to_list at h₁, injection h₁, assumption end, have e₃ : to_list xs = to_list ys, begin unfold to_list at h₁, injection h₁, assumption end, have xs == ys, from heq_of_list_eq e₃ e₁, have y :: xs == y :: ys, begin clear heq_of_list_eq h₁ h₂ e₃, revert xs ys this, induction e₁, intro xs ys h, rewrite [eq_of_heq h] end, show x :: xs == y :: ys, by rewrite e₂; exact this theorem list_eq_of_heq {n m} {v₁ : vector A n} {v₂ : vector A m} : v₁ == v₂ → n = m → to_list v₁ = to_list v₂ := begin intro h₁ h₂, revert v₁ v₂ h₁, subst n, intro v₁ v₂ h₁, rewrite [eq_of_heq h₁] end theorem of_list_to_list {n : nat} (v : vector A n) : of_list (to_list v) == v := begin apply heq_of_list_eq, rewrite to_list_of_list, rewrite length_to_list end theorem to_list_append : ∀ {n m : nat} (v₁ : vector A n) (v₂ : vector A m), to_list (append v₁ v₂) = list.append (to_list v₁) (to_list v₂) | 0 m [] ys := rfl | (succ n) m (x::xs) ys := begin unfold append, unfold to_list at {1,2}, krewrite [to_list_append xs ys] end theorem to_list_map (f : A → B) : ∀ {n : nat} (v : vector A n), to_list (map f v) = list.map f (to_list v) | 0 [] := rfl | (succ n) (x::xs) := begin unfold [map, to_list], rewrite to_list_map end theorem to_list_concat : ∀ {n : nat} (v : vector A n) (a : A), to_list (concat v a) = list.concat a (to_list v) | 0 [] a := rfl | (succ n) (x::xs) a := begin unfold [concat, to_list], rewrite to_list_concat end theorem to_list_reverse : ∀ {n : nat} (v : vector A n), to_list (reverse v) = list.reverse (to_list v) | 0 [] := rfl | (succ n) (x::xs) := begin unfold [reverse], rewrite [to_list_concat, to_list_reverse] end theorem append_nil_right {n : nat} (v : vector A n) : append v [] == v := begin apply heq_of_list_eq, rewrite [to_list_append, to_list_nil, list.append_nil_right], rewrite [-add_eq_addl] end theorem append.assoc {n₁ n₂ n₃ : nat} (v₁ : vector A n₁) (v₂ : vector A n₂) (v₃ : vector A n₃) : append v₁ (append v₂ v₃) == append (append v₁ v₂) v₃ := begin apply heq_of_list_eq, rewrite [*to_list_append, list.append.assoc], rewrite [-*add_eq_addl, add.assoc] end theorem reverse_append {n m : nat} (v : vector A n) (w : vector A m) : reverse (append v w) == append (reverse w) (reverse v) := begin apply heq_of_list_eq, rewrite [to_list_reverse, to_list_append, list.reverse_append, to_list_append, *to_list_reverse], rewrite [-*add_eq_addl, add.comm] end theorem concat_eq_append {n : nat} (v : vector A n) (a : A) : concat v a == append v [a] := begin apply heq_of_list_eq, rewrite [to_list_concat, to_list_append, list.concat_eq_append], rewrite [-add_eq_addl] end /- decidable equality -/ open decidable definition decidable_eq [H : decidable_eq A] : ∀ {n : nat} (v₁ v₂ : vector A n), decidable (v₁ = v₂) | ⌞0⌟ [] [] := by left; reflexivity | ⌞n+1⌟ (a::v₁) (b::v₂) := match H a b with | inl Hab := match decidable_eq v₁ v₂ with | inl He := by left; congruence; repeat assumption | inr Hn := by right; intro h; injection h; contradiction end | inr Hnab := by right; intro h; injection h; contradiction end section open equiv function definition vector_equiv_of_equiv {A B : Type} : A ≃ B → ∀ n, vector A n ≃ vector B n | (mk f g l r) n := mk (map f) (map g) begin intros, rewrite [map_map, id_of_left_inverse l, map_id], reflexivity end begin intros, rewrite [map_map, id_of_right_inverse r, map_id], reflexivity end end end vector
288926776f789b8e88d6f00f977ab3656b0eaba6
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/algebra/module.lean
9affa9a6f4e2c7509171fb7241bad6ca3cae789d
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
29,708
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import group_theory.group_action /-! # Modules over a ring In this file we define * `semimodule R M` : an additive commutative monoid `M` is a `semimodule` over a `semiring` `R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. * `module R M` : same as `semimodule R M` but assumes that `R` is a `ring` and `M` is an additive commutative group. * `vector_space k M` : same as `semimodule k M` and `module k M` but assumes that `k` is a `field` and `M` is an additive commutative group. * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `submodule R M` : a subset of `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Implementation notes * `vector_space` and `module` are abbreviations for `semimodule R M`. ## TODO * `submodule R M` was written before bundled `submonoid`s, so it does not extend it. ## Tags semimodule, module, vector space, submodule, subspace, linear map -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} section prio set_option default_priority 100 -- see Note [default priority] /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[protect_proj] class semimodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) end prio section add_comm_monoid variables [semiring R] [add_comm_monoid M] [semimodule R M] (r s : R) (x y : M) theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (R) @[simp] theorem zero_smul : (0 : R) • x = 0 := semimodule.zero_smul x theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] /-- Pullback a `semimodule` structure along an injective additive monoid homomorphism. -/ protected def function.injective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `semimodule` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_mul_action f smul } variable (M) /-- `(•)` as an `add_monoid_hom`. -/ def smul_add_hom : R →+ M →+ M := { to_fun := const_smul_hom M, map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] } variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid section add_comm_group variables (R M) [semiring R] [add_comm_group M] /-- A structure containing most informations as in a semimodule, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a semimodule structure by checking less properties, in `semimodule.of_core`. -/ @[nolint has_inhabited_instance] structure semimodule.core extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `semimodule` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `semimodule.core`, when the underlying space is an `add_comm_group`. -/ def semimodule.of_core (H : semimodule.core R M) : semimodule R M := by letI := H.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } variable [semimodule R M] @[simp] theorem smul_neg (r : R) (x : M) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero (by simp [← smul_add]) theorem smul_sub (r : R) (x y : M) : r • (x - y) = r • x - r • y := by simp [smul_add, sub_eq_add_neg]; rw smul_neg end add_comm_group /-- Modules are defined as an `abbreviation` for semimodules, if the base semiring is a ring. (A previous definition made `module` a structure defined to be `semimodule`.) This has as advantage that modules are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for modules as well. A cosmetic disadvantage is that one can not extend modules as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "module definition" /-- A module is the same as a semimodule, except the scalar semiring is actually a ring. This is the traditional generalization of spaces like `ℤ^n`, which have a natural addition operation and a way to multiply them by elements of a ring, but no multiplication operation between vectors. -/ abbreviation module (R : Type u) (M : Type v) [ring R] [add_comm_group M] := semimodule R M /-- To prove two module structures on a fixed `add_comm_group` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℤ M` is a subsingleton. @[ext] lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ }, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E] {c : R} {x : E} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨λ h, classical.or_iff_not_imp_left.2 $ λ hc, (units.mk0 c hc).smul_eq_zero.1 h, λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩ end module section set_option default_priority 910 instance semiring.to_semimodule [semiring R] : semimodule R R := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero } end @[simp] lemma smul_eq_mul [semiring R] {a a' : R} : a • a' = a * a' := rfl /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_semimodule [semiring R] [semiring S] (f : R →+* S) : semimodule R S := { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul], zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul], smul_zero := λ r, mul_zero (f r) } /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] := (to_fun : M → M₂) (map_add' : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (map_smul' : ∀(c : R) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ @[simp] lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl end section -- We can infer the module structure implicitly from the linear maps, -- rather than via typeclass resolution. variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} lemma coe_injective (H : ⇑f = g) : f = g := by cases f; cases g; congr'; exact H @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H lemma coe_fn_congr : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl } , ext⟩ variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ((f.to_add_monoid_hom) : M → M₂) = f := rfl @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f} end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end --TODO: move lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Ring of linear endomorphismsms of a module. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M set_option old_structure_cmd true /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] extends add_submonoid M : Type v := (smul_mem' : ∀ (c:R) {x}, x ∈ carrier → c • x ∈ carrier) /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid namespace submodule variables [semiring R] [add_comm_monoid M] [semimodule R M] instance : has_coe_t (submodule R M) (set M) := ⟨λ s, s.carrier⟩ instance : has_mem M (submodule R M) := ⟨λ x p, x ∈ (p : set M)⟩ instance : has_coe_to_sort (submodule R M) := ⟨_, λ p, {x : M // x ∈ p}⟩ variables (p q : submodule R M) @[simp, norm_cast] theorem coe_sort_coe : ↥(p : set M) = p := rfl variables {p q} protected theorem «exists» {q : p → Prop} : (∃ x, q x) ↔ (∃ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.exists protected theorem «forall» {q : p → Prop} : (∀ x, q x) ↔ (∀ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.forall theorem coe_injective : injective (coe : submodule R M → set M) := λ p q h, by cases p; cases q; congr' @[simp, norm_cast] theorem coe_set_eq : (p : set M) = q ↔ p = q := coe_injective.eq_iff theorem ext'_iff : p = q ↔ (p : set M) = q := coe_set_eq.symm @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := coe_injective $ set.ext h theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, ext'_iff.2 $ add_submonoid.ext'_iff.1 h @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff end submodule namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {semimodule_M : semimodule R M} variables {p q : submodule R M} variables {r : R} {x y : M} variables (p) @[simp] theorem mem_coe : x ∈ (p : set M) ↔ x ∈ p := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ p := p.zero_mem' lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add_mem' h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := p.to_add_submonoid.sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' (u : units R) : (u:R) • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_mem ↑u⁻¹ h, p.smul_mem u⟩ instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance : has_scalar R p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_coe {x y : p} : (x : M) = y ↔ x = y := subtype.ext_iff_val.symm @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := @coe_eq_coe _ _ _ _ _ _ x 0 @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 @[simp] protected lemma eta (x : p) (hx : (x : M) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance : semimodule R p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((submodule.subtype p) : p → M) = subtype.val := rfl end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {semimodule_M : semimodule R M} variables (p p' : submodule R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul R; exact p.smul_mem _ hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy) @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := p.to_add_subgroup.neg_mem_iff lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩ lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl end add_comm_group end submodule -- TODO: Do we want one-sided ideals? /-- Ideal in a commutative ring is an additive subgroup `s` such that `a * b ∈ s` whenever `b ∈ s`. We define `ideal R` as `submodule R R`. -/ @[reducible] def ideal (R : Type u) [comm_ring R] := submodule R R namespace ideal variables [comm_ring R] (I : ideal R) {a b : R} protected lemma zero_mem : (0 : R) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal /-- Vector spaces are defined as an `abbreviation` for semimodules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "vector space definition" /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ abbreviation vector_space (R : Type u) (M : Type v) [field R] [add_comm_group M] := semimodule R M /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [vector_space R M] := submodule R M namespace submodule variables [division_ring R] [add_comm_group M] [module R M] variables (p : submodule R M) {r : R} {x y : M} theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := p.smul_mem_iff' (units.mk0 r r0) end submodule namespace add_comm_monoid open add_monoid variables [add_comm_monoid M] /-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/ -- We don't make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℕ`. def nat_semimodule : semimodule ℕ M := { smul := nsmul, smul_add := λ _ _ _, nsmul_add _ _ _, add_smul := λ _ _ _, add_nsmul _ _ _, mul_smul := λ _ _ _, mul_nsmul _ _ _, one_smul := one_nsmul, zero_smul := zero_nsmul, smul_zero := nsmul_zero } end add_comm_monoid namespace add_comm_group variables [add_comm_group M] /-- The natural ℤ-module structure on any `add_comm_group`. -/ -- We don't immediately make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℤ`. -- We do turn it into a global instance, but only at the end of this file, -- and I remain dubious whether this is a good idea. def int_module : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } instance : subsingleton (module ℤ M) := begin split, intros P Q, ext, -- isn't that lovely: `r • m = r • m` have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m }, begin rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m], rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m], end, have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m }, begin intro n, induction n with n ih, { erw [zero_smul, zero_smul], }, { rw [int.coe_nat_succ, add_smul, add_smul], erw ih, rw [one_smul], } end, cases r, { rw [int.of_nat_eq_coe, nat_smul], }, { rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], } end end add_comm_group section local attribute [instance] add_comm_monoid.nat_semimodule lemma semimodule.smul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma semimodule.nsmul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n •ℕ b = (n : R) • b := semimodule.smul_eq_smul R n b lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) : n • x = n •ℕ x := rfl end section local attribute [instance] add_comm_group.int_module lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {M : Type*} [add_comm_group M] [module R M] (n : ℤ) (b : M) : gsmul n b = (n : R) • b := begin cases n, { apply semimodule.nsmul_eq_smul, }, { dsimp, rw semimodule.nsmul_eq_smul R, push_cast, rw neg_smul, } end lemma module.gsmul_eq_smul {M : Type*} [add_comm_group M] [module ℤ M] (n : ℤ) (b : M) : gsmul n b = n • b := by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id] end -- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here -- come from whatever the local `module ℤ` structure actually is. lemma add_monoid_hom.map_int_module_smul [add_comm_group M] [add_comm_group M₂] [module ℤ M] [module ℤ M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [← module.gsmul_eq_smul, f.map_gsmul] lemma add_monoid_hom.map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul] lemma add_monoid_hom.map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← semimodule.nsmul_eq_smul, f.map_nsmul] lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x -- We finally turn on these instances globally: attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := ⟨f, f.map_add, f.map_rat_module_smul⟩
ad31d5fdc2a16942674c649b71877f3625b91066
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/analysis/normed_space/real_inner_product.lean
2e03ccdeb0548abc86d3c744b14eb89c0193595c
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
21,550
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import analysis.convex algebra.quadratic_discriminant analysis.complex.exponential analysis.specific_limits import tactic.monotonicity /-! # Inner Product Space This file defines real inner product space and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. ## Main statements Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. ## Implementation notes We decide to develop the theory of real inner product spaces and that of complex inner product spaces separately. ## Tags inner product space, norm, orthogonal projection ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: http://www.lri.fr/~sboldo/elfic/index.html -/ noncomputable theory open real set lattice open_locale topological_space universes u v w variables {α : Type u} {F : Type v} {G : Type w} class has_inner (α : Type*) := (inner : α → α → ℝ) export has_inner (inner) /-- An inner product space is a real vector space with an additional operation called inner product. Inner product spaces over complex vector space will be defined in another file. -/ class inner_product_space (α : Type*) extends add_comm_group α, vector_space ℝ α, has_inner α := (comm : ∀ x y, inner x y = inner y x) (nonneg : ∀ x, 0 ≤ inner x x) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = r * inner x y) variable [inner_product_space α] section basic_properties lemma inner_comm (x y : α) : inner x y = inner y x := inner_product_space.comm x y lemma inner_self_nonneg {x : α} : 0 ≤ inner x x := inner_product_space.nonneg _ lemma inner_add_left {x y z : α} : inner (x + y) z = inner x z + inner y z := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : α} : inner x (y + z) = inner x y + inner x z := by { rw [inner_comm, inner_add_left], simp [inner_comm] } lemma inner_smul_left {x y : α} {r : ℝ} : inner (r • x) y = r * inner x y := inner_product_space.smul_left _ _ _ lemma inner_smul_right {x y : α} {r : ℝ} : inner x (r • y) = r * inner x y := by { rw [inner_comm, inner_smul_left, inner_comm] } @[simp] lemma inner_zero_left {x : α} : inner 0 x = 0 := by { rw [← zero_smul ℝ (0:α), inner_smul_left, zero_mul] } @[simp] lemma inner_zero_right {x : α} : inner x 0 = 0 := by { rw [inner_comm, inner_zero_left] } lemma inner_self_eq_zero (x : α) : inner x x = 0 ↔ x = 0 := iff.intro (inner_product_space.definite _) (by { rintro rfl, exact inner_zero_left }) @[simp] lemma inner_neg_left {x y : α} : inner (-x) y = -inner x y := by { rw [← neg_one_smul ℝ x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : α} : inner x (-y) = -inner x y := by { rw [inner_comm, inner_neg_left, inner_comm] } @[simp] lemma inner_neg_neg {x y : α} : inner (-x) (-y) = inner x y := by simp lemma inner_sub_left {x y z : α} : inner (x - y) z = inner x z - inner y z := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : α} : inner x (y - z) = inner x y - inner x z := by { simp [sub_eq_add_neg, inner_add_right] } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : α} : inner (x + y) (x + y) = inner x x + 2 * inner x y + inner y y := by { simpa [inner_add_left, inner_add_right, two_mul] using inner_comm _ _ } /-- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : α} : inner (x - y) (x - y) = inner x x - 2 * inner x y + inner y y := by { simp only [inner_sub_left, inner_sub_right, two_mul], simpa using inner_comm _ _ } /-- Parallelogram law -/ lemma parallelogram_law {x y : α} : inner (x + y) (x + y) + inner (x - y) (x - y) = 2 * (inner x x + inner y y) := by { simp [inner_add_add_self, inner_sub_sub_self, two_mul] } /-- Cauchy–Schwarz inequality -/ lemma inner_mul_inner_self_le (x y : α) : inner x y * inner x y ≤ inner x x * inner y y := begin have : ∀ t, 0 ≤ inner y y * t * t + 2 * inner x y * t + inner x x, from assume t, calc 0 ≤ inner (x+t•y) (x+t•y) : inner_self_nonneg ... = inner y y * t * t + 2 * inner x y * t + inner x x : by { simp only [inner_add_add_self, inner_smul_right, inner_smul_left], ring }, have := discriminant_le_zero this, rw discrim at this, have h : (2 * inner x y)^2 - 4 * inner y y * inner x x = 4 * (inner x y * inner x y - inner x x * inner y y) := by ring, rw h at this, linarith end end basic_properties section norm /-- An inner product naturally induces a norm. -/ instance inner_product_space_has_norm : has_norm α := ⟨λx, sqrt (inner x x)⟩ lemma norm_eq_sqrt_inner {x : α} : ∥x∥ = sqrt (inner x x) := rfl lemma inner_self_eq_norm_square (x : α) : inner x x = ∥x∥ * ∥x∥ := (mul_self_sqrt inner_self_nonneg).symm /-- Expand the square -/ lemma norm_add_pow_two {x y : α} : ∥x + y∥^2 = ∥x∥^2 + 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_add_add_self } /-- Same lemma as above but in a different form -/ lemma norm_add_mul_self {x y : α} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_sub_pow_two {x y : α} : ∥x - y∥^2 = ∥x∥^2 - 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_sub_sub_self } /-- Same lemma as above but in a different form -/ lemma norm_sub_mul_self {x y : α} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : α) : abs (inner x y) ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin rw abs_mul_abs_self, have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = inner x x * inner y y, simp only [inner_self_eq_norm_square], ring, rw this, exact inner_mul_inner_self_le _ _ end lemma parallelogram_law_with_norm {x y : α} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { simp only [(inner_self_eq_norm_square _).symm], exact parallelogram_law } /-- An inner product space forms a normed group w.r.t. its associated norm. -/ instance inner_product_space_is_normed_group : normed_group α := normed_group.of_core α { norm_eq_zero_iff := assume x, iff.intro (λ h : sqrt (inner x x) = 0, (inner_self_eq_zero x).1 $ (sqrt_eq_zero inner_self_nonneg).1 h ) (by {rintro rfl, show sqrt (inner (0:α) 0) = 0, simp }), triangle := assume x y, begin have := calc ∥x + y∥ * ∥x + y∥ = inner (x + y) (x + y) : (inner_self_eq_norm_square _).symm ... = inner x x + 2 * inner x y + inner y y : inner_add_add_self ... ≤ inner x x + 2 * (∥x∥ * ∥y∥) + inner y y : by linarith [abs_inner_le_norm x y, le_abs_self (inner x y)] ... = (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥) : by { simp only [inner_self_eq_norm_square], ring }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λx, show sqrt (inner (-x) (-x)) = sqrt (inner x x), by simp } /-- An inner product space forms a normed space over reals w.r.t. its associated norm. -/ instance inner_product_space_is_normed_space : normed_space ℝ α := { norm_smul := assume r x, begin rw [norm_eq_sqrt_inner, sqrt_eq_iff_mul_self_eq, inner_smul_left, inner_smul_right, inner_self_eq_norm_square], exact calc abs(r) * ∥x∥ * (abs(r) * ∥x∥) = (abs(r) * abs(r)) * (∥x∥ * ∥x∥) : by ring ... = r * (r * (∥x∥ * ∥x∥)) : by { rw abs_mul_abs_self, ring }, exact inner_self_nonneg, exact mul_nonneg (abs_nonneg _) (sqrt_nonneg _) end } end norm section orthogonal open filter /-- Existence of minimizers Let `u` be a point in an inner product space, and let `K` be a nonempty complete convex subset. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ theorem exists_norm_eq_infi_of_complete_convex {K : set α} (ne : nonempty K) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt ne (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (𝓝 δ), have h : tendsto (λ n:ℕ, δ) at_top (𝓝 δ), exact tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (𝓝 δ), convert tendsto_add h tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero], exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (by { rw mem_at_top_sets, use 0, assume n hn, exact δ_le _ }) (by { rw mem_at_top_sets, use 0, assume n hn, exact le_of_lt (hw _) }), -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):α)), rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):α), let wq := ((w q):α), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (abs((2:ℝ)) * ∥u - half•(wq + wp)∥) * (abs((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw abs_of_nonneg, exact add_nonneg zero_le_one zero_le_one } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by { rw [norm_smul], refl } ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel two_ne_zero, ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, show wp - wq = (u - wq) - (u - wp), abel, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) (le_of_lt nat.one_div_pos_of_nat)) (le_of_lt nat.one_div_pos_of_nat)), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), convert tendsto_mul (@tendsto_const_nhds _ _ _ (8 * δ) _) tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero], have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), convert tendsto_mul (@tendsto_const_nhds _ _ _ (4:ℝ) _) tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero], have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), convert tendsto_mul this tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero], convert tendsto_add eq₁ eq₂, simp only [add_zero], -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous_sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (𝓝 ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique at_top_ne_bot this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers in the above theorem -/ theorem norm_eq_infi_iff_inner_le_zero {K : set α} (ne : nonempty K) (h : convex K) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) (w - v) ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := inner (u - v) (w - v), let q := ∥w - v∥^2, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw eq, apply δ_le', apply (convex_iff K).1 h hw hv, repeat { exact subtype.mem _ }, exact le_of_lt hθ₁, exact hθ₂, end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), rw [smul_sub, sub_smul, one_smul], simp, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+abs(θ)*∥w-v∥*(abs(θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:α) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:α) - v) + ∥(w:α) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end /-- Existence of minimizers. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (K : subspace ℝ α) (ne : nonempty K) (h : is_complete (↑K : set α)) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (↑K : set α), ∥u - w∥ := exists_norm_eq_infi_of_complete_convex ne h (convex_submodule _) /-- Characterization of minimizers in the above theorem. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` if and only if for all `w ∈ K`, `inner (u - v) w = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero (K : subspace ℝ α) (ne : nonempty K) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set α), ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) w = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, rw norm_eq_infi_iff_inner_le_zero at h, exact h, exact ne, exact convex_submodule _, exact hv, assume w hw, have le : inner (u - v) w ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : inner (u - v) w ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj', add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_inner_le_zero, exact ne, exact convex_submodule _, exact hv end end orthogonal
f543d8c940086bcb5defb60e6907ba2d5ab5272d
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/set_theory/ordinal_arithmetic.lean
23fcb85d1b485defc8b5abc9cff89b4eab2c854a
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
70,457
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.ordinal /-! # Ordinal arithmetic Ordinals have an addition (corresponding to disjoint union) that turns them into an additive monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns them into a monoid. One can also define correspondingly a subtraction, a division, a successor function, a power function and a logarithm function. We also define limit ordinals and prove the basic induction principle on ordinals separating successor ordinals and limit ordinals, in `limit_rec_on`. ## Main definitions and results * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. * `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`. * `o₁ * o₂` is the lexicographic order on `o₂ × o₁`. * `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the divisibility predicate, and a modulo operation. * `succ o = o + 1` is the successor of `o`. * `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`. We also define the power function and the logarithm function on ordinals, and discuss the properties of casts of natural numbers of and of `omega` with respect to these operations. Some properties of the operations are also used to discuss general tools on ordinals: * `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor. * `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. * `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. * `nfp f a`: the next fixed point of a function `f` on ordinals, above `a`. It behaves well for normal functions. * `CNF b o` is the Cantor normal form of the ordinal `o` in base `b`. * `sup`: the supremum of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`. * `bsup`: the supremum of a set of ordinals indexed by ordinals less than a given ordinal `o`. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} namespace ordinal /-! ### Further properties of addition on ordinals -/ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := by unfold succ; simp only [lift_add, lift_one] theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c := ⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨ have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a, by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply] using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂) ((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a, have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin intro b, cases e : f (sum.inr b), { rw ← fl at e, have := f.inj' e, contradiction }, { exact ⟨_, rfl⟩ } end, let g (b) := (this b).1 in have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2, ⟨⟨⟨g, λ x y h, by injection f.inj' (by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩, λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding, initial_seg.coe_fn_to_rel_embedding, function.embedding.coe_fn_mk] using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩, λ a b H, begin rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩, { rw fl at h, cases h }, { rw fr at h, exact ⟨a', sum.inr.inj h⟩ } end⟩⟩, λ h, add_le_add_left h _⟩ theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) := (add_assoc _ _ _).symm @[simp] theorem succ_zero : succ 0 = 1 := zero_add _ theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 := by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero] theorem succ_pos (o : ordinal) : 0 < succ o := lt_of_le_of_lt (ordinal.zero_le _) (lt_succ_self _) theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp only [succ, card_add, card_one] theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c := by simp only [le_antisymm_iff, add_le_add_iff_left] theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c := by rw [← not_le, ← not_le, add_le_add_iff_left] theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c := lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _) @[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b := by rw [lt_succ, succ_le] @[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 succ_lt_succ theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b := by simp only [le_antisymm_iff, succ_le_succ] theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b := by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero], rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]] theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by simp only [le_antisymm_iff, add_le_add_iff_right] /-! ### The zero ordinal -/ @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ h, begin refine le_antisymm (le_of_not_lt $ λ hn, mk_ne_zero_iff.2 _ h) (ordinal.zero_le _), rw [← succ_le, succ_zero] at hn, cases hn with f, exact ⟨f punit.star⟩ end, λ e, by simp only [e, card_zero]⟩ @[simp] theorem type_eq_zero_of_empty [is_well_order α r] [is_empty α] : type r = 0 := card_eq_zero.symm.mpr (mk_eq_zero _) @[simp] theorem type_eq_zero_iff_is_empty [is_well_order α r] : type r = 0 ↔ is_empty α := (@card_eq_zero (type r)).symm.trans mk_eq_zero_iff theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α := (not_congr (@card_eq_zero (type r))).symm.trans mk_ne_zero_iff protected lemma one_ne_zero : (1 : ordinal) ≠ 0 := type_ne_zero_iff_nonempty.2 ⟨punit.star⟩ instance : nontrivial ordinal.{u} := ⟨⟨1, 0, ordinal.one_ne_zero⟩⟩ theorem zero_lt_one : (0 : ordinal) < 1 := lt_iff_le_and_ne.2 ⟨ordinal.zero_le _, ne.symm $ ordinal.one_ne_zero⟩ /-! ### The predecessor of an ordinal -/ /-- The ordinal predecessor of `o` is `o'` if `o = succ o'`, and `o` otherwise. -/ def pred (o : ordinal.{u}) : ordinal.{u} := if h : ∃ a, o = succ a then classical.some h else o @[simp] theorem pred_succ (o) : pred (succ o) = o := by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩; simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm theorem pred_le_self (o) : pred o ≤ o := if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _) else by rw [pred, dif_neg h] theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a := ⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e, λ h, dif_neg h⟩ theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a := iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le]) (iff_not_comm.1 pred_eq_iff_not_succ).symm theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a := ⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩ theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o := ⟨lt_trans (lt_succ_self _), λ l, lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩ theorem lt_pred {a b} : a < pred b ↔ succ a < b := if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in by rw [e, pred_succ, succ_lt_succ] else by simp only [pred, dif_neg h, succ_lt_of_not_succ h] theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b := le_iff_le_iff_lt_iff_lt.2 lt_pred @[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) := ⟨λ ⟨a, h⟩, let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $ h.symm ▸ lt_succ_self _ in ⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩, λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩ @[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) := if h : ∃ a, o = succ a then by cases h with a e; simp only [e, pred_succ, lift_succ] else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)] /-! ### Limit ordinals -/ /-- A limit ordinal is an ordinal which is not zero and not a successor. -/ def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o theorem not_zero_is_limit : ¬ is_limit 0 | ⟨h, _⟩ := h rfl theorem not_succ_is_limit (o) : ¬ is_limit (succ o) | ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _)) theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a | ⟨a, e⟩ := not_succ_is_limit a (e ▸ h) theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o := ⟨lt_trans (lt_succ_self _), h.2 _⟩ theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a := le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a := ⟨λ h x l, le_trans (le_of_lt l) h, λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn, not_lt_of_le (H _ hn) (lt_succ_self _)⟩ theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x := by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a) @[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o := and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0) ⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h), λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in by rw [← e, ← lift_succ, lift_lt]; rw [← e, lift_lt] at h; exact H a' h⟩ theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o := lt_of_le_of_ne (ordinal.zero_le _) h.1.symm theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o := by simpa only [succ_zero] using h.2 _ h.pos theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := h.pos | (n+1) := h.2 _ (is_limit.nat_lt n) theorem zero_or_succ_or_limit (o : ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o := if o0 : o = 0 then or.inl o0 else if h : ∃ a, o = succ a then or.inr (or.inl h) else or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ /-- Main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/ @[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*} (o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o)) (H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o := wf.fix (λ o IH, if o0 : o = 0 then by rw o0; exact H₁ else if h : ∃ a, o = succ a then by rw ← succ_pred_iff_is_succ.2 h; exact H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h) else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o @[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ := by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl @[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) : @limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) := begin have h : ∃ a, succ o = succ a := ⟨_, rfl⟩, rw [limit_rec_on, well_founded.fix_eq, dif_neg (succ_ne_zero o), dif_pos h], generalize : limit_rec_on._proof_2 (succ o) h = h₂, generalize : limit_rec_on._proof_3 (succ o) h = h₃, revert h₂ h₃, generalize e : pred (succ o) = o', intros, rw pred_succ at e, subst o', refl end @[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) : @limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) := by rw [limit_rec_on, well_founded.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl lemma has_succ_of_is_limit {α} {r : α → α → Prop} [wo : is_well_order α r] (h : (type r).is_limit) (x : α) : ∃y, r x y := begin use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)), convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein] end lemma type_subrel_lt (o : ordinal.{u}) : type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u+1} o := begin refine quotient.induction_on o _, rintro ⟨α, r, wo⟩, resetI, apply quotient.sound, constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (typein_iso r) end lemma mk_initial_seg (o : ordinal.{u}) : #{o' : ordinal | o' < o} = cardinal.lift.{u+1} o.card := by rw [lift_card, ←type_subrel_lt, card_type] /-! ### Normal ordinal functions -/ /-- A normal ordinal function is a strictly increasing function which is order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. -/ def is_normal (f : ordinal → ordinal) : Prop := (∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2 theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} : a < f o ↔ ∃ b < o, a < f b := not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b := strict_mono.lt_iff_lt $ λ a b, limit_rec_on b (not.elim (not_lt_of_le $ ordinal.zero_le _)) (λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim (λ h, lt_trans (IH h) (H.1 _)) (λ e, e ▸ H.1 _)) (λ b l IH h, lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 (le_refl _) _ (l.2 _ h))) theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_iff theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b := by simp only [le_antisymm_iff, H.le_iff] theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a := limit_rec_on a (ordinal.zero_le _) (λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _)) (λ a l IH, (limit_le l).2 $ λ b h, le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h) theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f a ≤ o := ⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h, λ h, begin revert H₂, apply limit_rec_on S, { intro H₂, cases p0 with x px, have := ordinal.le_zero.1 ((H₂ _).1 (ordinal.zero_le _) _ px), rw this at px, exact h _ px }, { intros S _ H₂, rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) }, { intros S L _ H₂, apply (H.2 _ L _).2, intros a h', rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) } end⟩ theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o := (H.le_set (λ x, ∃ y, p y ∧ x = g y) (let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _ (λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1, λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans ⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩ theorem is_normal.refl : is_normal id := ⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩ theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) : is_normal (λ x, f (g x)) := ⟨λ x, H₁.lt_iff.2 (H₂.1 _), λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩ theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) := ⟨ne_of_gt $ lt_of_le_of_lt (ordinal.zero_le _) $ H.lt_iff.2 l.pos, λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩ theorem add_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c := ⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin resetI, suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l), { cases enum _ _ l with x x, { cases this (enum s 0 h.pos) }, { exact irrefl _ (this _) } }, intros x, rw [← typein_lt_typein (sum.lex r s), typein_enum], have := H _ (h.2 _ (typein_lt_type s x)), rw [add_succ, succ_le] at this, refine lt_of_le_of_lt (type_le'.2 ⟨rel_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this, { rcases a with ⟨a | b, h⟩, { exact sum.inl a }, { exact sum.inr ⟨b, by cases h; assumption⟩ } }, { rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂; rintro ⟨⟩; constructor; assumption } end) h H⟩ theorem add_is_normal (a : ordinal) : is_normal ((+) a) := ⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _), λ b l c, add_le_of_limit l⟩ theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) := (add_is_normal a).is_limit /-! ### Subtraction on ordinals-/ /-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/ def sub (a b : ordinal.{u}) : ordinal.{u} := omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩ instance : has_sub ordinal := ⟨sub⟩ theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) := omin_mem {o | a ≤ b+o} _ theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c := ⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _), λ h, omin_le h⟩ theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le sub_le theorem add_sub_cancel (a b : ordinal) : a + b - a = b := le_antisymm (sub_le.2 $ le_refl _) ((add_le_add_iff_left a).1 $ le_add_sub _ _) theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b := h ▸ add_sub_cancel _ _ theorem sub_le_self (a b : ordinal) : a - b ≤ a := sub_le.2 $ le_add_left _ _ protected theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a := le_antisymm begin rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l, { simp only [e, add_zero, h] }, { rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self }, { exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) } end (le_add_sub _ _) @[simp] theorem sub_zero (a : ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a @[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 := by rw ← ordinal.le_zero; apply sub_le_self @[simp] theorem sub_self (a : ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0 protected theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b := ⟨λ h, by simpa only [h, add_zero] using le_add_sub a b, λ h, by rwa [← ordinal.le_zero, sub_le, add_zero]⟩ theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) := eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c := by rw [← sub_sub, add_sub_cancel] theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) := ⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero, λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩ @[simp] theorem one_add_omega : 1 + omega.{u} = omega := begin refine le_antisymm _ (le_add_left _ _), rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add], have : is_well_order unit empty_relation := by apply_instance, refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩, { apply sum.rec, exact λ _, 0, exact nat.succ }, { intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H; [cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] } end @[simp, priority 990] theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o := by rw [← ordinal.add_sub_cancel_of_le h, ← add_assoc, one_add_omega] /-! ### Multiplication of ordinals-/ /-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on `o₂ × o₁`. -/ instance : monoid ordinal.{u} := { mul := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.prod_lex_congr g f⟩, one := 1, mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin rcases a with ⟨⟨a₁, a₂⟩, a₃⟩, rcases b with ⟨⟨b₁, b₂⟩, b₃⟩, simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc] end⟩⟩, mul_one := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩; simp only [prod.lex_def, empty_relation, false_or]; simp only [eq_self_iff_true, true_and]; refl⟩⟩, one_mul := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩; simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ } @[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem card_mul (a b) : card (a * b) = card a * card b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, mul_comm (mk β) (mk α) @[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty @[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def, sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr, sum_prod_distrib_apply_left, sum_prod_distrib_apply_right]; simp only [sum.inl.inj_iff, true_or, false_and, false_or] end⟩⟩ @[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a := by simp only [mul_add, mul_one] @[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _ theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, (f a.1, a.2)) (λ a b h, _)⟩, clear_, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.2 h') }, { exact prod.lex.right _ h' } end theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, (a.1, f a.2)) (λ a b h, _)⟩, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ h' }, { exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.2 h') } end theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d := le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁) private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s] {c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c) (l : c < type r * type s) : false := begin suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l), { cases enum _ _ l with b a, exact irrefl _ (this _ _) }, intros a b, rw [← typein_lt_typein (prod.lex s r), typein_enum], have := H _ (h.2 _ (typein_lt_type s b)), rw [mul_succ] at this, have := lt_of_lt_of_le ((add_lt_add_iff_left _).2 (typein_lt_type _ a)) this, refine lt_of_le_of_lt _ this, refine (type_le'.2 _), constructor, refine rel_embedding.of_monotone (λ a, _) (λ a b, _), { rcases a with ⟨⟨b', a'⟩, h⟩, by_cases e : b = b', { refine sum.inr ⟨a', _⟩, subst e, cases h with _ _ _ _ h _ _ _ h, { exact (irrefl _ h).elim }, { exact h } }, { refine sum.inl (⟨b', _⟩, a'), cases h with _ _ _ _ h _ _ _ h, { exact h }, { exact (e rfl).elim } } }, { rcases a with ⟨⟨b₁, a₁⟩, h₁⟩, rcases b with ⟨⟨b₂, a₂⟩, h₂⟩, intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂, { substs b₁ b₂, simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true, dif_pos, sum.lex_inr_inr] using h }, { subst b₁, simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true, or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢, cases h₂; [exact asymm h h₂_h, exact e₂ rfl] }, { simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] }, { simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk, sum.lex_inl_inl] using h } } end theorem mul_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c := ⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _, by exactI mul_le_of_limit_aux) h H⟩ theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) := ⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h, λ b l c, mul_le_of_limit l⟩ theorem lt_mul_of_limit {a b c : ordinal.{u}} (h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h) theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c := (mul_is_normal a0).lt_iff theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c := (mul_is_normal a0).le_iff theorem mul_lt_mul_of_pos_left {a b c : ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b := (mul_lt_mul_iff_left c0).2 h theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁ theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by simpa only [ordinal.pos_iff_ne_zero] using mul_pos theorem le_of_mul_le_mul_left {a b c : ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b := le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c := (mul_is_normal a0).inj theorem mul_is_limit {a b : ordinal} (a0 : 0 < a) : is_limit b → is_limit (a * b) := (mul_is_normal a0).is_limit theorem mul_is_limit_left {a b : ordinal} (l : is_limit a) (b0 : 0 < b) : is_limit (a * b) := begin rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb, { exact (lt_irrefl _).elim b0 }, { rw mul_succ, exact add_is_limit _ l }, { exact mul_is_limit l.pos lb } end /-! ### Division on ordinals -/ protected lemma div_aux (a b : ordinal.{u}) (h : b ≠ 0) : set.nonempty {o | a < b * succ o} := ⟨a, succ_le.1 $ by simpa only [succ_zero, one_mul] using mul_le_mul_right (succ a) (succ_le.2 (ordinal.pos_iff_ne_zero.2 h))⟩ /-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/ protected def div (a b : ordinal.{u}) : ordinal.{u} := if h : b = 0 then 0 else omin {o | a < b * succ o} (ordinal.div_aux a b h) instance : has_div ordinal := ⟨ordinal.div⟩ @[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl lemma div_def (a) {b : ordinal} (h : b ≠ 0) : a / b = omin {o | a < b * succ o} (ordinal.div_aux a b h) := dif_neg h theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by rw div_def a h; exact omin_mem {o | a < b * succ o} _ theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by simpa only [mul_succ] using lt_mul_succ_div a h theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c := ⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h), λ h, by rw div_def a b0; exact omin_le h⟩ theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by rw [← not_le, div_le c0, not_lt] theorem le_div {a b c : ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := begin apply limit_rec_on a, { simp only [mul_zero, ordinal.zero_le] }, { intros, rw [succ_le, lt_div c0] }, { simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} } end theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c := lt_iff_lt_of_le_iff_le $ le_div b0 theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c := if b0 : b = 0 then by simp only [b0, div_zero, ordinal.zero_le] else (div_le b0).2 $ lt_of_le_of_lt h $ mul_lt_mul_of_pos_left (lt_succ_self _) (ordinal.pos_iff_ne_zero.2 b0) theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b := lt_imp_lt_of_le_imp_le div_le_of_le_mul @[simp] theorem zero_div (a : ordinal) : 0 / a = 0 := ordinal.le_zero.1 $ div_le_of_le_mul $ ordinal.zero_le _ theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a := if b0 : b = 0 then by simp only [b0, zero_mul, ordinal.zero_le] else (le_div b0).1 (le_refl _) theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := begin apply le_antisymm, { apply (div_le b0).2, rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left], apply lt_mul_div_add _ b0 }, { rw [le_div b0, mul_add, add_le_add_iff_left], apply mul_div_le } end theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 := begin rw [← ordinal.le_zero, div_le $ ordinal.pos_iff_ne_zero.1 $ lt_of_le_of_lt (ordinal.zero_le _) h], simpa only [succ_zero, mul_one] using h end @[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a := by simpa only [add_zero, zero_div] using mul_add_div a b0 0 @[simp] theorem div_one (a : ordinal) : a / 1 = a := by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero @[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 := by simpa only [mul_one] using mul_div_cancel 1 h theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c := if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else eq_of_forall_ge_iff $ λ d, by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0] theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) := begin split; intro h, { by_cases h' : b = 0, { rw [h', add_zero] at h, right, exact ⟨h', h⟩ }, left, rw [←add_sub_cancel a b], apply sub_is_limit h, suffices : a + 0 < a + b, simpa only [add_zero], rwa [add_lt_add_iff_left, ordinal.pos_iff_ne_zero] }, rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero] end theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c) | a _ c ⟨b, rfl⟩ := ⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩ theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c := (dvd_add_iff h₁).2 theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩ theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 := ⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩ theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩ theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b | a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0] theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b | a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a (one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0)) theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b := if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂) /-- `a % b` is the unique ordinal `o'` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩ theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl @[simp] theorem mod_zero (a : ordinal) : a % 0 = a := by simp only [mod_def, div_zero, zero_mul, sub_zero] theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a := by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero] @[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 := by simp only [mod_def, zero_div, mul_zero, sub_self] theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a := ordinal.add_sub_cancel_of_le $ mul_div_le _ _ theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b := (add_lt_add_iff_left (b * (a / b))).1 $ by rw div_add_mod; exact lt_mul_div_add a h @[simp] theorem mod_self (a : ordinal) : a % a = 0 := if a0 : a = 0 then by simp only [a0, zero_mod] else by simp only [mod_def, div_self a0, mul_one, sub_self] @[simp] theorem mod_one (a : ordinal) : a % 1 = 0 := by simp only [mod_def, div_one, one_mul, sub_self] /-! ### Supremum of a family of ordinals -/ /-- The supremum of a family of ordinals -/ def sup {ι} (f : ι → ordinal) : ordinal := omin {c | ∀ i, f i ≤ c} ⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $ cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩ theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f := omin_mem {c | ∀ i, f i ≤ c} _ theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩ theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i := by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a) theorem is_normal.sup {f} (H : is_normal f) {ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) := eq_of_forall_ge_iff $ λ a, by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)]; intros; simp only [sup_le, true_implies_iff] theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord := eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le] lemma sup_succ {ι} (f : ι → ordinal) : sup (λ i, succ (f i)) ≤ succ (sup f) := by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup } lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α) (h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) := begin apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h, refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y, apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self end /-- The supremum of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. (This is not a special case of `sup` over the subtype, because `{a // a < o} : Type (u+1)` and `sup` only works over families in `Type u`.) -/ def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} := match o, o.out, o.out_eq with | _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _)) end theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a := match o, o.out, o.out_eq, f : ∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}), bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with | _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI ⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩ end theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) : bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) := eq_of_forall_ge_iff $ λ o, by rw [bsup_le, sup_le]; exact ⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩ theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f := bsup_le.1 (le_refl _) _ _ theorem lt_bsup {o : ordinal} {f : Π a < o, ordinal} (hf : ∀{a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha') (ho : o.is_limit) (i h) : f i h < bsup o f := lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h) theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (λ x _, x) = o := begin apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt, rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (λ x _, x)), apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption end theorem is_normal.bsup {f} (H : is_normal f) {o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0), f (bsup o g) = bsup o (λ a h, f (g a h)) := induction_on o $ λ α r _ g h, by resetI; rw [bsup_type, H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type] theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) : bsup.{u} o (λx _, f x) = f o := by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id h] } /-! ### Ordinal exponential -/ /-- The ordinal exponential, defined by transfinite recursion. -/ def power (a b : ordinal) : ordinal := if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b) instance : has_pow ordinal ordinal := ⟨power⟩ local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a := by simp only [pow, power, if_pos rfl] @[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 := by rwa [zero_power', ordinal.sub_eq_zero_iff_le, one_le_iff_ne_zero] @[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 := by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero], simp only [pow, power, if_neg h, limit_rec_on_zero]] @[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a := if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero] else by simp only [pow, power, limit_rec_on_succ, if_neg h] theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b = bsup.{u u} b (λ c _, a ^ c) := by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c := by rw [power_limit a0 h, bsup_le] theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) : a < b ^ c ↔ ∃ c' < c, a < b ^ c' := by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and] @[simp] theorem power_one (a : ordinal) : a ^ 1 = a := by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul] @[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 := begin apply limit_rec_on a, { simp only [power_zero] }, { intros _ ih, simp only [power_succ, ih, mul_one] }, refine λ b l IH, eq_of_forall_ge_iff (λ c, _), rw [power_le_of_limit ordinal.one_ne_zero l], exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos, λ H b' h, by rwa IH _ h⟩, end theorem power_pos {a : ordinal} (b) (a0 : 0 < a) : 0 < a ^ b := begin have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]}, apply limit_rec_on b, { exact h0 }, { intros b IH, rw [power_succ], exact mul_pos IH a0 }, { exact λ b l _, (lt_power_of_limit (ordinal.pos_iff_ne_zero.1 a0) l).2 ⟨0, l.pos, h0⟩ }, end theorem power_ne_zero {a : ordinal} (b) (a0 : a ≠ 0) : a ^ b ≠ 0 := ordinal.pos_iff_ne_zero.1 $ power_pos b $ ordinal.pos_iff_ne_zero.2 a0 theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) := have a0 : 0 < a, from lt_trans zero_lt_one h, ⟨λ b, by simpa only [mul_one, power_succ] using (mul_lt_mul_iff_left (power_pos b a0)).2 h, λ b l c, power_le_of_limit (ne_of_gt a0) l⟩ theorem power_lt_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b < a ^ c ↔ b < c := (power_is_normal a1).lt_iff theorem power_le_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c := (power_is_normal a1).le_iff theorem power_right_inj {a b c : ordinal} (a1 : 1 < a) : a ^ b = a ^ c ↔ b = c := (power_is_normal a1).inj theorem power_is_limit {a b : ordinal} (a1 : 1 < a) : is_limit b → is_limit (a ^ b) := (power_is_normal a1).is_limit theorem power_is_limit_left {a b : ordinal} (l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) := begin rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l', { exact absurd e hb }, { rw power_succ, exact mul_is_limit (power_pos _ l.pos) l }, { exact power_is_limit l.one_lt l' } end theorem power_le_power_right {a b c : ordinal} (h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c := begin cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁, { exact (power_le_power_iff_right h₁).2 h₂ }, { subst a, simp only [one_power] } end theorem power_le_power_left {a b : ordinal} (c) (ab : a ≤ b) : a ^ c ≤ b ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, { subst c, simp only [power_zero] }, { simp only [zero_power c0, ordinal.zero_le] } }, { apply limit_rec_on c, { simp only [power_zero] }, { intros c IH, simpa only [power_succ] using mul_le_mul IH ab }, { exact λ c l IH, (power_le_of_limit a0 l).2 (λ b' h, le_trans (IH _ h) (power_le_power_right (lt_of_lt_of_le (ordinal.pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } } end theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b := (power_is_normal a1).le_self _ theorem power_lt_power_left_of_succ {a b c : ordinal} (ab : a < b) : a ^ succ c < b ^ succ c := by rw [power_succ, power_succ]; exact lt_of_le_of_lt (mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab) (mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (ordinal.zero_le _) ab))) theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]}, have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le (ordinal.pos_iff_ne_zero.2 c0) (le_add_left _ _)), simp only [zero_power c0, zero_power this, mul_zero] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power, mul_one] }, apply limit_rec_on c, { simp only [add_zero, power_zero, mul_one] }, { intros c IH, rw [add_succ, power_succ, IH, power_succ, mul_assoc] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (add_is_normal b)).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (((mul_is_normal $ power_pos b (ordinal.pos_iff_ne_zero.2 a0)).trans (power_is_normal a1)).limit_le l).symm } end theorem power_dvd_power (a) {b c : ordinal} (h : b ≤ c) : a ^ b ∣ a ^ c := by { rw [← ordinal.add_sub_cancel_of_le h, power_add], apply dvd_mul_right } theorem power_dvd_power_iff {a b c : ordinal} (a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c := ⟨λ h, le_of_not_lt $ λ hn, not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $ le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h, power_dvd_power _⟩ theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c := begin by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]}, by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]}, simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power] }, apply limit_rec_on c, { simp only [mul_zero, power_zero] }, { intros c IH, rw [mul_succ, power_add, IH, power_succ] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (mul_is_normal (ordinal.pos_iff_ne_zero.2 b0))).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (power_le_of_limit (power_ne_zero _ a0) l).symm } end /-! ### Ordinal logarithm -/ /-- The ordinal logarithm is the solution `u` to the equation `x = b ^ u * v + w` where `v < b` and `w < b`. -/ def log (b : ordinal) (x : ordinal) : ordinal := if h : 1 < b then pred $ omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩ else 0 @[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 := by simp only [log, dif_neg b1] theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x = pred (omin {o | x < b^o} (log._proof_1 b x b1)) := by simp only [log, dif_pos b1] @[simp] theorem log_zero (b : ordinal) : log b 0 = 0 := if b1 : 1 < b then by rw [log_def b1, ← ordinal.le_zero, pred_le]; apply omin_le; change 0<b^succ 0; rw [succ_zero, power_one]; exact lt_trans zero_lt_one b1 else by simp only [log_not_one_lt b1] theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) = omin {o | x < b^o} (log._proof_1 b x b1) := begin let t := omin {o | x < b^o} (log._proof_1 b x b1), have : x < b ^ t := omin_mem {o | x < b^o} _, rcases zero_or_succ_or_limit t with h|h|h, { refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim, simpa only [h, power_zero] }, { rw [show log b x = pred t, from log_def b1 x, succ_pred_iff_is_succ.2 h] }, { rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩, exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) } end theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) : x < b ^ succ (log b x) := begin cases lt_or_eq_of_le (ordinal.zero_le x) with x0 x0, { rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ }, { subst x, apply power_pos _ (lt_trans zero_lt_one b1) } end theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) : b ^ log b x ≤ x := begin by_cases b0 : b = 0, { rw [b0, zero_power'], refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _), have := @omin_le {o | x < b^o} _ _ h, rwa ← succ_log_def b1 x0 at this }, { rw [← b1, one_power], exact one_le_iff_pos.2 x0 } end theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : c ≤ log b x ↔ b ^ c ≤ x := ⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0), λ h, le_of_not_lt $ λ hn, not_le_of_lt (lt_power_succ_log b1 x) $ le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩ theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : log b x < c ↔ x < b ^ c := lt_iff_lt_of_le_iff_le (le_log b1 x0) theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) : log b x ≤ log b y := if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else have x0 : 0 < x, from ordinal.pos_iff_ne_zero.2 x0, if b1 : 1 < b then (le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy else by simp only [log_not_one_lt b1, ordinal.zero_le] theorem log_le_self (b x : ordinal) : log b x ≤ x := if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else if b1 : 1 < b then le_trans (le_power_self _ b1) (power_log_le b (ordinal.pos_iff_ne_zero.2 x0)) else by simp only [log_not_one_lt b1, ordinal.zero_le] /-! ### The Cantor normal form -/ theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : o % b ^ log b o < o := lt_of_lt_of_le (mod_lt _ $ power_ne_zero _ b0) (power_log_le _ $ ordinal.pos_iff_ne_zero.2 o0) /-- Proving properties of ordinals by induction over their Cantor normal form. -/ @[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0) {C : ordinal → Sort*} (H0 : C 0) (H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o) : ∀ o, C o | o := if o0 : o = 0 then by rw o0; exact H0 else have _, from CNF_aux b0 o0, H o o0 this (CNF_rec (o % b ^ log b o)) using_well_founded {dec_tac := `[assumption]} @[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 := by rw [CNF_rec, dif_pos rfl]; refl @[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) : @CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) := by rw [CNF_rec, dif_neg o0] /-- The Cantor normal form of an ordinal is the list of coefficients in the base-`b` expansion of `o`. CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/ noncomputable def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) := if b0 : b = 0 then [] else CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o @[simp] theorem zero_CNF (o) : CNF 0 o = [] := dif_pos rfl @[simp] theorem CNF_zero (b) : CNF b 0 = [] := if b0 : b = 0 then dif_pos b0 else (dif_neg b0).trans $ CNF_rec_zero _ theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) := by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0] theorem one_CNF {o : ordinal} (o0 : o ≠ 0) : CNF 1 o = [(0, o)] := by rw [CNF_ne_zero ordinal.one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one, CNF_zero, div_one] theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) : (CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o := CNF_rec b0 (by rw CNF_zero; refl) (λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o theorem CNF_pairwise_aux (b := omega) (o) : (∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧ (CNF b o).pairwise (λ p q, q.1 < p.1) := begin by_cases b0 : b = 0, { simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine CNF_rec b0 _ _ o, { simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim }, intros o o0 H IH, cases IH with IH₁ IH₂, simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true], refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩, { exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) }, { refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _), { rw ordinal.pos_iff_ne_zero, intro e, rw e at m, simpa only [CNF_zero] using m }, { exact mod_lt _ (power_ne_zero _ b0) } } }, { by_cases o0 : o = 0, { simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim }, rw [← b1, one_CNF o0], simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and, list.pairwise_singleton] } end theorem CNF_pairwise (b := omega) (o) : (CNF b o).pairwise (λ p q, prod.fst q < p.1) := (CNF_pairwise_aux _ _).2 theorem CNF_fst_le_log (b := omega) (o) : ∀ p ∈ CNF b o, prod.fst p ≤ log b o := (CNF_pairwise_aux _ _).1 theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o := le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _) theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) : ∀ p ∈ CNF b o, prod.snd p < b := begin have b0 := ne_of_gt (lt_trans zero_lt_one b1), refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o, intros o o0 H IH, simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, forall_eq_or_imp, iff_true_intro IH, and_true], rw [div_lt (power_ne_zero _ b0), ← power_succ], exact lt_power_succ_log b1 _, end theorem CNF_sorted (b := omega) (o) : ((CNF b o).map prod.fst).sorted (>) := by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o /-! ### Casting naturals into ordinals, compatibility with operations -/ @[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n := by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero], rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]] @[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n := by induction n with n IH; [simp only [pow_zero, nat.cast_zero, power_zero, nat.cast_one], rw [pow_succ', nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]] @[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n := by rw [← cardinal.ord_nat, ← cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le] @[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n := by simp only [lt_iff_le_not_le, nat_cast_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n := by simp only [le_antisymm_iff, nat_cast_le] @[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 := @nat_cast_inj n 0 theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 := not_congr nat_cast_eq_zero @[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n := @nat_cast_lt 0 n @[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n := (_root_.le_total m n).elim (λ h, by rw [nat.sub_eq_zero_iff_le.2 h, ordinal.sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl) (λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add, add_sub_cancel_of_le h, ordinal.add_sub_cancel_of_le (nat_cast_le.2 h)]) @[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n := if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else have n0':_, from nat_cast_ne_zero.2 n0, le_antisymm (by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm]; apply nat.div_mul_le_self) (by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul, nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)]; apply nat.lt_succ_self) @[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n := by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add, nat.div_add_mod] @[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o := ⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h, λ h, card_nat n ▸ card_le_card h⟩ @[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o := by rw [← succ_le, ← cardinal.succ_le, ← cardinal.nat_succ, nat_le_card]; refl @[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n := lt_iff_lt_of_le_iff_le nat_le_card @[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n := le_iff_le_iff_lt_iff_lt.2 nat_lt_card @[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n := by simp only [le_antisymm_iff, card_le_nat, nat_le_card] @[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n := by rw [← card_eq_nat, card_type, mk_fin] @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n with n ih; [simp only [nat.cast_zero, lift_zero], simp only [nat.cast_succ, lift_add, ih, lift_one]] theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n := by simp only [type_fin, lift_nat_cast] theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α := by rw [← card_eq_nat, card_type, fintype_card] end ordinal /-! ### Properties of `omega` -/ namespace cardinal open ordinal @[simp] theorem ord_omega : ord.{u} omega = ordinal.omega := le_antisymm (ord_le.2 $ le_refl _) $ le_of_forall_lt $ λ o h, begin rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩, rw [lt_ord, ← lift_card, ← lift_omega.{0 u}, lift_lt, ← typein_enum (<) h'], exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩ end @[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c := by rw [add_comm, ← card_ord c, ← card_one, ← card_add, one_add_of_omega_le]; rwa [← ord_omega, ord_le_ord] end cardinal namespace ordinal theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n := by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat] theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega := lt_omega.2 ⟨_, rfl⟩ theorem omega_pos : 0 < omega := nat_lt_omega 0 theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1 theorem omega_is_limit : is_limit omega := ⟨omega_ne_zero, λ o h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e]; exact nat_lt_omega (n+1)⟩ theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ H, le_of_forall_lt $ λ a h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e, ← succ_le]; exact H (n+1)⟩ theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := lt_of_le_of_ne (ordinal.zero_le o) h.1.symm | (n+1) := h.2 _ (nat_lt_limit n) theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o := omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega := begin rcases lt_omega.1 h with ⟨n, rfl⟩, clear h, induction n with n IH, { rw [nat.cast_zero, zero_add] }, { rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] } end theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega end theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a := begin refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩, { refine (limit_le l).2 (λ x hx, le_of_lt _), rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero, mul_succ, add_le_of_limit omega_is_limit], intros b hb, rcases lt_omega.1 hb with ⟨n, rfl⟩, exact le_trans (add_le_add_right (mul_div_le _ _) _) (le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) }, { rcases h with ⟨a0, b, rfl⟩, refine mul_is_limit_left omega_is_limit (ordinal.pos_iff_ne_zero.2 $ mt _ a0), intro e, simp only [e, mul_zero] } end local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega end theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b := begin refine le_antisymm _ (le_add_left _ _), revert h, apply limit_rec_on b, { intro h, rw [power_zero, ← succ_zero, lt_succ, ordinal.le_zero] at h, rw [h, zero_add] }, { intros b _ h, rw [power_succ] at h, rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩, refine le_trans (add_le_add_right (le_of_lt ax) _) _, rw [power_succ, ← mul_add, add_omega xo] }, { intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩, refine (((add_is_normal a).trans (power_is_normal one_lt_omega)) .limit_le l).2 (λ y yb, _), let z := max x y, have := IH z (max_lt xb yb) (lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)), exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _) (le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) } end theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) : a + b < omega ^ c := by rwa [← add_omega_power h₁, add_lt_add_iff_left] theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c := by rw [← ordinal.add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁] theorem add_absorp_iff {o : ordinal} (o0 : 0 < o) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a := ⟨λ H, ⟨log omega o, begin refine ((lt_or_eq_of_le (power_log_le _ o0)) .resolve_left $ λ h, _).symm, have := H _ h, have := lt_power_succ_log one_lt_omega o, rw [power_succ, lt_mul_of_limit omega_is_limit] at this, rcases this with ⟨a, ao, h'⟩, rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao, revert h', apply not_lt_of_le, suffices e : omega ^ log omega o * ↑n + o = o, { simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o }, induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]}, simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH] end⟩, λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩ theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a) (l : is_limit c) (IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c := le_antisymm ((mul_le_of_limit l).2 $ λ c' h, begin apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)), rw IH _ h, apply le_trans (add_le_add_left _ _), { rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) }, { rw ← ba, exact le_add_right _ _ } end) (mul_le_mul_right _ (le_add_right _ _)) theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := begin apply limit_rec_on c, { simp only [succ_zero, mul_one] }, { intros c IH, rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] }, { intros c l IH, have := add_mul_limit_aux ba l IH, rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] } end theorem add_mul_limit {a b c : ordinal} (ba : b + a = a) (l : is_limit c) : (a + b) * c = a * c := add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba) theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega := le_antisymm ((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb)) (by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0)) theorem mul_lt_omega_power {a b c : ordinal} (c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c := if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l, { exact (lt_irrefl _).elim c0 }, { rw power_succ at ha, rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt omega_is_limit).1 ha with ⟨n, hn, an⟩, refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _, rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)], exact mul_lt_omega hn hb }, { rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩, refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _, rw [← power_succ, power_lt_power_iff_right one_lt_omega], exact l.2 _ hx } end theorem mul_omega_dvd {a : ordinal} (a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b | _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha] theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) : a * omega ^ omega ^ b = omega ^ omega ^ b := begin by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h}, refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)), rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h with ⟨x, xb, ax⟩, refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _, rw [← power_add, add_omega_power xb] end theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega := le_antisymm ((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2 (λ b hb, le_of_lt (power_lt_omega h hb))) (le_power_self _ a1) /-! ### Fixed points of normal functions -/ /-- The next fixed point function, the least fixed point of the normal function `f` above `a`. -/ def nfp (f : ordinal → ordinal) (a : ordinal) := sup (λ n : ℕ, f^[n] a) theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := le_sup _ n theorem le_nfp_self (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := lt_sup.trans $ iff.trans (by exact ⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩, λ ⟨n, h⟩, ⟨n+1, by rw iterate_succ'; exact H.lt_iff.2 h⟩⟩) lt_sup.symm theorem is_normal.nfp_le {f} (H : is_normal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_nfp theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := sup_le.2 $ λ i, begin induction i with i IH generalizing a, {exact ab}, exact IH (le_trans (H.le_iff.2 ab) h), end theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a := begin refine le_antisymm _ (H.le_self _), cases le_or_lt (f a) a with aa aa, { rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) }, rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l, { refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1), simp only [e, ordinal.zero_le] }, { have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]), rw [e, lt_succ] at this, have ab : a ≤ b, { rw [← lt_succ, ← e], exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) }, refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this)) (le_trans this (le_of_lt _)), simp only [e, lt_succ_self] }, { exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) } end theorem is_normal.le_nfp {f} (H : is_normal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨le_trans (H.le_self _), λ h, by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a := le_antisymm (sup_le.mpr $ λ i, by rw [iterate_fixed h]) (le_nfp_self f a) /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp f 0) (λ a IH, nfp f (succ IH)) (λ a l, bsup.{u u} a) @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_limit (f) {o} : is_limit o → deriv f o = bsup.{u u} o (λ a _, deriv f a) := limit_rec_on_limit _ _ _ _ theorem deriv_is_normal (f) : is_normal (deriv f) := ⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self, λ o l a, by rw [deriv_limit _ l, bsup_le]⟩ theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o := begin apply limit_rec_on o, { rw [deriv_zero, H.nfp_fp] }, { intros o ih, rw [deriv_succ, H.nfp_fp] }, intros o l IH, rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1], refine eq_of_forall_ge_iff (λ c, _), simp only [bsup_le, IH] {contextual:=tt} end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a ≤ a ↔ ∃ o, a = deriv f o := ⟨λ ha, begin suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o, from this a ((deriv_is_normal _).le_self _), intro o, apply limit_rec_on o, { intros h₁, refine ⟨0, le_antisymm h₁ _⟩, rw deriv_zero, exact H.nfp_le_fp (ordinal.zero_le _) ha }, { intros o IH h₁, cases le_or_lt a (deriv f o), {exact IH h}, refine ⟨succ o, le_antisymm h₁ _⟩, rw deriv_succ, exact H.nfp_le_fp (succ_le.2 h) ha }, { intros o l IH h₁, cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩}, rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩ end ordinal
5ba2d87c5d14d56c9210b045efb0035dc2f41e12
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/data/basic.lean
7ab1e456103ea99bbb2a60b517eb657f508a37a8
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
569
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.data.setoid init.data.quot init.data.bool.basic init.data.unit import init.data.nat.basic init.data.prod init.data.sum.basic import init.data.sigma.basic init.data.subtype.basic import init.data.fin.basic init.data.list.basic init.data.char.basic import init.data.string.basic init.data.option.basic init.data.set import init.data.unsigned.basic init.data.ordering init.data.to_string
1cc0740222d0f9bc32b4a7c089958b63b14bd6ac
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/sites/sheaf_of_types.lean
651743405a2cd14963cd20e20f28793a20cdb26a
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,829
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.pretopology import category_theory.limits.shapes.types import category_theory.full_subcategory /-! # Sheaves of types on a Grothendieck topology Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians) on a category equipped with a Grothendieck topology, as well as a range of equivalent conditions useful in different situations. First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular presieve `R` on `X`: * A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in `R`. See `family_of_elements`. * The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of `x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`. See `family_of_elements.compatible`. * An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in `R`, the restriction of `t` on `f` is `x_f`. See `family_of_elements.is_amalgamation`. We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation, and it is a *sheaf* for `R` if every compatible family has a unique amalgamation. See `is_separated_for` and `is_sheaf_for`. In the special case where `R` is a sieve, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of `x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`). See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`. In the special case where `C` has pullbacks, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`, the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g` along `π₂ : pullback f g ⟶ Z`. See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`. Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the topology. See `is_sheaf`. In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for every sieve in the pretopology. See `is_sheaf_pretopology`. We also provide equivalent conditions to satisfy alternate definitions given in the literature. * Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with `is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.) The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries the same information as the unique existence.) * Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf` are equivalent. There are also alternate definitions given: - Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in `yoneda_condition_iff_sheaf_condition`. - Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence in `equalizer.sieve.sheaf_condition`. - Matching family for presieves with pullback: `pullback_compatible_iff`. - Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous. - Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition` combined with the previous. ## Implementation The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u₁ v)`. This doesn't seem to make a big difference, other than making a couple of definitions noncomputable, but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements, which can be convenient. ## References * [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk: Chapter III, Section 4. * [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1. * https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site) * https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology) -/ universes w v₁ v₂ u₁ u₂ namespace category_theory open opposite category_theory category limits sieve classical namespace presieve variables {C : Type u₁} [category.{v₁} C] variables {P Q U : Cᵒᵖ ⥤ Type w} variables {X Y : C} {S : sieve X} {R : presieve X} variables (J J₂ : grothendieck_topology C) /-- A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X` consists of an element of `P Y` for every `f : Y ⟶ X` in `R`. A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one (resp, at most one) amalgamation. This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant]. -/ def family_of_elements (P : Cᵒᵖ ⥤ Type w) (R : presieve X) := Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y) instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩ /-- A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve `R₁`. -/ def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) : family_of_elements P R₂ → family_of_elements P R₁ := λ x Y f hf, x f (h _ hf) /-- A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂` commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and restricting the element of `P Y₂` along `g₂` are the same. In special cases, this condition can be simplified, see `pullback_compatible_iff` and `compatible_iff_sieve_compatible`. This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab: https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents -/ def family_of_elements.compatible (x : family_of_elements P R) : Prop := ∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂) /-- If the category `C` has pullbacks, this is an alternative condition for a family of elements to be compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the given elements for `f` and `g` to the pullback agree. This is equivalent to being compatible (provided `C` has pullbacks), shown in `pullback_compatible_iff`. This is the definition for a "matching" family given in [MM92], Chapter III, Section 4, Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`, using the notation defined there. -/ def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop := ∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂) lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] : x.compatible ↔ x.pullback_compatible := begin split, { intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂, apply t, apply pullback.condition }, { intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm, rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂, ←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] } end /-- The restriction of a compatible family is compatible. -/ lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) {x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible := λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm /-- Extend a family of elements to the sieve generated by an arrow set. This is the construction described as "easy" in Lemma C2.1.3 of [Elephant]. -/ noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) : family_of_elements P (generate R) := λ Z f hf, P.map (some (some_spec hf)).op (x _ (some_spec (some_spec (some_spec hf))).1) /-- The extension of a compatible family to the generated sieve is compatible. -/ lemma family_of_elements.compatible.sieve_extend (x : family_of_elements P R) (hx : x.compatible) : x.sieve_extend.compatible := begin intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←(some_spec (some_spec (some_spec h₁))).2, ←(some_spec (some_spec (some_spec h₂))).2, ←assoc, ←assoc] at comm, dsimp [family_of_elements.sieve_extend], rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply], apply hx _ _ _ _ comm, end /-- The extension of a family agrees with the original family. -/ lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) : x.sieve_extend f ⟨_, 𝟙 _, f, hf, id_comp _⟩ = x f hf := begin have h : (generate R) f := ⟨_, _, _, hf, id_comp _⟩, change P.map (some (some_spec h)).op (x _ _) = x f hf, rw t (some (some_spec h)) (𝟙 _) _ hf _, { simp }, simp_rw [id_comp], apply (some_spec (some_spec (some_spec h))).2, end /-- The restriction of an extension is the original. -/ @[simp] lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) : x.sieve_extend.restrict (le_generate R) = x := begin ext Y f hf, exact extend_agrees t hf, end /-- If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the consistency condition can be simplified. This is an equivalent condition, see `compatible_iff_sieve_compatible`. This is the notion of "matching" given for families on sieves given in [MM92], Chapter III, Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family. See also the discussion before Lemma C2.1.4 of [Elephant]. -/ def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop := ∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) lemma compatible_iff_sieve_compatible (x : family_of_elements P S) : x.compatible ↔ x.sieve_compatible := begin split, { intros h Y Z f g hf, simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) }, { intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k, simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] } end lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S} (t : x.compatible) : x.sieve_compatible := (compatible_iff_sieve_compatible x).1 t /-- Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are equal when restricted to `R`. -/ lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)} (t₁ : x₁.compatible) (t₂ : x₂.compatible) : x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ := begin intro h, ext Z f ⟨Y, f, g, hg, rfl⟩, rw compatible_iff_sieve_compatible at t₁ t₂, erw [t₁ g f ⟨_, _, g, hg, id_comp _⟩, t₂ g f ⟨_, _, g, hg, id_comp _⟩], congr' 1, apply congr_fun (congr_fun (congr_fun h _) g) hg, end /-- Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted to `R` and then extended back up to `S`, the resulting extension equals `x`. -/ @[simp] lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) : (x.restrict (le_generate R)).sieve_extend = x := begin apply restrict_inj, { exact (t.restrict (le_generate R)).sieve_extend _ }, { exact t }, rw restrict_extend, exact t.restrict (le_generate R), end lemma family_of_elements.comp_of_compatible (S : sieve X) {x : family_of_elements P S} (t : x.compatible) {f : Y ⟶ X} (hf : S f) {Z} (g : Z ⟶ Y) : x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) := by simpa using t (𝟙 _) g (S.downward_closed hf g) hf (category.id_comp _) section functor_pullback variables {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {Z : D} variables {T : presieve (F.obj Z)} {x : family_of_elements P T} /-- Given a family of elements of a sieve `S` on `F(X)`, we can realize it as a family of elements of `S.functor_pullback F`. -/ def family_of_elements.functor_pullback (x : family_of_elements P T) : family_of_elements (F.op ⋙ P) (T.functor_pullback F) := λ Y f hf, x (F.map f) hf lemma family_of_elements.compatible.functor_pullback (h : x.compatible) : (x.functor_pullback F).compatible := begin intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq, exact h (F.map g₁) (F.map g₂) h₁ h₂ (by simp only [← F.map_comp, eq]) end end functor_pullback /-- Given a family of elements of a sieve `S` on `X` whose values factors through `F`, we can realize it as a family of elements of `S.functor_pushforward F`. Since the preimage is obtained by choice, this is not well-defined generally. -/ noncomputable def family_of_elements.functor_pushforward {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {X : D} {T : presieve X} (x : family_of_elements (F.op ⋙ P) T) : family_of_elements P (T.functor_pushforward F) := λ Y f h, by { obtain ⟨Z, g, h, h₁, _⟩ := get_functor_pushforward_structure h, exact P.map h.op (x g h₁) } section pullback /-- Given a family of elements of a sieve `S` on `X`, and a map `Y ⟶ X`, we can obtain a family of elements of `S.pullback f` by taking the same elements. -/ def family_of_elements.pullback (f : Y ⟶ X) (x : family_of_elements P S) : family_of_elements P (S.pullback f) := λ _ g hg, x (g ≫ f) hg lemma family_of_elements.compatible.pullback (f : Y ⟶ X) {x : family_of_elements P S} (h : x.compatible) : (x.pullback f).compatible := begin simp only [compatible_iff_sieve_compatible] at h ⊢, intros W Z f₁ f₂ hf, unfold family_of_elements.pullback, rw ← (h (f₁ ≫ f) f₂ hf), simp only [category.assoc], end end pullback /-- Given a morphism of presheaves `f : P ⟶ Q`, we can take a family of elements valued in `P` to a family of elements valued in `Q` by composing with `f`. -/ def family_of_elements.comp_presheaf_map (f : P ⟶ Q) (x : family_of_elements P R) : family_of_elements Q R := λ Y g hg, f.app (op Y) (x g hg) @[simp] lemma family_of_elements.comp_presheaf_map_id (x : family_of_elements P R) : x.comp_presheaf_map (𝟙 P) = x := rfl @[simp] lemma family_of_elements.comp_prersheaf_map_comp (x : family_of_elements P R) (f : P ⟶ Q) (g : Q ⟶ U) : (x.comp_presheaf_map f).comp_presheaf_map g = x.comp_presheaf_map (f ≫ g) := rfl lemma family_of_elements.compatible.comp_presheaf_map (f : P ⟶ Q) {x : family_of_elements P R} (h : x.compatible) : (x.comp_presheaf_map f).compatible := begin intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq, unfold family_of_elements.comp_presheaf_map, rwa [← functor_to_types.naturality, ← functor_to_types.naturality, h], end /-- The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`. This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents, and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4, equation (2). -/ def family_of_elements.is_amalgamation (x : family_of_elements P R) (t : P.obj (op X)) : Prop := ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h lemma family_of_elements.is_amalgamation.comp_presheaf_map {x : family_of_elements P R} {t} (f : P ⟶ Q) (h : x.is_amalgamation t) : (x.comp_presheaf_map f).is_amalgamation (f.app (op X) t) := begin intros Y g hg, dsimp [family_of_elements.comp_presheaf_map], change (f.app _ ≫ Q.map _) _ = _, simp [← f.naturality, h g hg], end lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R) (h : ∃ t, x.is_amalgamation t) : x.compatible := begin cases h with t ht, intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm], simp, end lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) (x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) : (x.restrict h).is_amalgamation t := λ Y f hf, ht f (h Y hf) lemma is_amalgamation_sieve_extend {R : presieve X} (x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) : x.sieve_extend.is_amalgamation t := begin intros Y f hf, dsimp [family_of_elements.sieve_extend], rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, (some_spec (some_spec (some_spec hf))).2], end /-- A presheaf is separated for a presieve if there is at most one amalgamation. -/ def is_separated_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop := ∀ (x : family_of_elements P R) (t₁ t₂), x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂ lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R) {t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) : t₁ = t₂ := hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl) lemma is_separated_for_iff_generate : is_separated_for P R ↔ is_separated_for P (generate R) := begin split, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.restrict (le_generate R)) t₁ t₂ _ _, { exact is_amalgamation_restrict _ x t₁ ht₁ }, { exact is_amalgamation_restrict _ x t₂ ht₂ } }, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.sieve_extend), { exact is_amalgamation_sieve_extend x t₁ ht₁ }, { exact is_amalgamation_sieve_extend x t₂ ht₂ } } end lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type w) : is_separated_for P (⊤ : presieve X) := λ x t₁ t₂ h₁ h₂, begin have q₁ := h₁ (𝟙 X) (by simp), have q₂ := h₂ (𝟙 X) (by simp), simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂, rw [q₁, q₂], end /-- We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique amalgamation. This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents. Using `compatible_iff_sieve_compatible`, this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4. -/ def is_sheaf_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop := ∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t /-- This is an equivalent condition to be a sheaf, which is useful for the abstraction to local operators on elementary toposes. However this definition is defined only for sieves, not presieves. The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`. This version is also useful to establish that being a sheaf is preserved under isomorphism of presheaves. See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of [Elephant]. This is also a direct reformulation of https://stacks.math.columbia.edu/tag/00Z8. -/ def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v₁) (S : sieve X) : Prop := ∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f -- TODO: We can generalize the universe parameter v₁ above by composing with -- appropriate `ulift_functor`s. /-- (Implementation). This is a (primarily internal) equivalence between natural transformations and compatible families. Cf the discussion after Lemma 7.47.10 in https://stacks.math.columbia.edu/tag/00YW. See also the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4. -/ def nat_trans_equiv_compatible_family {P : Cᵒᵖ ⥤ Type v₁} : (S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} := { to_fun := λ α, begin refine ⟨λ Y f hf, _, _⟩, { apply α.app (op Y) ⟨_, hf⟩ }, { rw compatible_iff_sieve_compatible, intros Y Z f g hf, dsimp, rw ← functor_to_types.naturality _ _ α g.op, refl } end, inv_fun := λ t, { app := λ Y f, t.1 _ f.2, naturality' := λ Y Z g, begin ext ⟨f, hf⟩, apply t.2.to_sieve_compatible _, end }, left_inv := λ α, begin ext X ⟨_, _⟩, refl end, right_inv := begin rintro ⟨x, hx⟩, refl, end } /-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/ lemma extension_iff_amalgamation {P : Cᵒᵖ ⥤ Type v₁} (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) : S.functor_inclusion ≫ g = x ↔ (nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) := begin change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩, split, { rintro rfl Y f hf, rw yoneda_equiv_naturality, dsimp, simp }, -- See note [dsimp, simp]. { intro h, ext Y ⟨f, hf⟩, have : _ = x.app Y _ := h f hf, rw yoneda_equiv_naturality at this, rw ← this, dsimp, simp }, -- See note [dsimp, simp]. end /-- The yoneda version of the sheaf condition is equivalent to the sheaf condition. C2.1.4 of [Elephant]. -/ lemma is_sheaf_for_iff_yoneda_sheaf_condition {P : Cᵒᵖ ⥤ Type v₁} : is_sheaf_for P S ↔ yoneda_sheaf_condition P S := begin rw [is_sheaf_for, yoneda_sheaf_condition], simp_rw [extension_iff_amalgamation], rw equiv.forall_congr_left' nat_trans_equiv_compatible_family, rw subtype.forall, apply ball_congr, intros x hx, rw equiv.exists_unique_congr_left _, simp, end /-- If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor) to `P` can be (uniquely) extended to all of `yoneda.obj X`. f S → P ↓ ↗ yX -/ noncomputable def is_sheaf_for.extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (f : S.functor ⟶ P) : yoneda.obj X ⟶ P := classical.some (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists /-- Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie that the triangle below commutes, provided `P` is a sheaf for `S` f S → P ↓ ↗ yX -/ @[simp, reassoc] lemma is_sheaf_for.functor_inclusion_comp_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (f : S.functor ⟶ P) : S.functor_inclusion ≫ h.extend f = f := classical.some_spec (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists /-- The extension of `f` to `yoneda.obj X` is unique. -/ lemma is_sheaf_for.unique_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) {f : S.functor ⟶ P} (t : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t = f) : t = h.extend f := ((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f)) /-- If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X` to `P` agree when restricted to the subfunctor given by `S`, they are equal. -/ lemma is_sheaf_for.hom_ext {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) : t₁ = t₂ := (h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm /-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/ lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for : is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔ is_sheaf_for P R := begin rw [is_separated_for, ←forall_and_distrib], apply forall_congr, intro x, split, { intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 }, { intros h, refine ⟨_, (exists_of_exists_unique ∘ h)⟩, intros t₁ t₂ ht₁ ht₂, apply (h _).unique ht₁ ht₂, exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ } end /-- If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`. -/ lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) : (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) → is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, exact and.intro t, end /-- If `P` is a sheaf for `R`, it is separated for `R`. -/ lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R := λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1 /-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/ noncomputable def is_sheaf_for.amalgamate (t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) : P.obj (op X) := classical.some (t x hx).exists lemma is_sheaf_for.is_amalgamation (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) : x.is_amalgamation (t.amalgamate x hx) := classical.some_spec (t x hx).exists @[simp] lemma is_sheaf_for.valid_glue (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) : P.map f.op (t.amalgamate x hx) = x f Hf := t.is_amalgamation hx f Hf /-- C2.1.3 in [Elephant] -/ lemma is_sheaf_for_iff_generate (R : presieve X) : is_sheaf_for P R ↔ is_sheaf_for P (generate R) := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_iff_generate, apply and_congr (iff.refl _), split, { intros q x hx, apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))), intros t ht, simpa [hx] using is_amalgamation_sieve_extend _ _ ht }, { intros q x hx, apply exists_imp_exists _ (q _ (hx.sieve_extend _)), intros t ht, simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht }, end /-- Every presheaf is a sheaf for the family {𝟙 X}. [Elephant] C2.1.5(i) -/ lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type w) : is_sheaf_for P (presieve.singleton (𝟙 X)) := begin intros x hx, refine ⟨x _ (presieve.singleton_self _), _, _⟩, { rintro _ _ ⟨rfl, rfl⟩, simp }, { intros t ht, simpa using ht _ (presieve.singleton_self _) } end /-- Every presheaf is a sheaf for the maximal sieve. [Elephant] C2.1.5(ii) -/ lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type w) : is_sheaf_for P ((⊤ : sieve X) : presieve X) := begin rw ← generate_of_singleton_split_epi (𝟙 X), rw ← is_sheaf_for_iff_generate, apply is_sheaf_for_singleton_iso, end /-- If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that "being a sheaf for a presieve" is a mathematical or hygenic property. -/ lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R := begin intros h x hx, let x' := x.comp_presheaf_map i.inv, have : x'.compatible := family_of_elements.compatible.comp_presheaf_map i.inv hx, obtain ⟨t, ht1, ht2⟩ := h x' this, use i.hom.app _ t, fsplit, { convert family_of_elements.is_amalgamation.comp_presheaf_map i.hom ht1, dsimp [x'], simp }, { intros y hy, rw (show y = (i.inv.app (op X) ≫ i.hom.app (op X)) y, by simp), simp [ ht2 (i.inv.app _ y) (family_of_elements.is_amalgamation.comp_presheaf_map i.inv hy)] } end /-- If a presieve `R` on `X` has a subsieve `S` such that: * `P` is a sheaf for `S`. * For every `f` in `R`, `P` is separated for the pullback of `S` along `f`, then `P` is a sheaf for `R`. This is closely related to [Elephant] C2.1.6(i). -/ lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (hS : is_sheaf_for P S) (trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) : is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, split, { intros x t₁ t₂ ht₁ ht₂, exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁) (is_amalgamation_restrict h x t₂ ht₂) }, { intros x hx, use hS.amalgamate _ (hx.restrict h), intros W j hj, apply (trans hj).ext, intros Y f hf, rw [←functor_to_types.map_comp_apply, ←op_comp, hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict, ←hx (𝟙 _) f _ _ (id_comp _)], simp }, end /-- If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which contains `S`. This is closely related to [Elephant] C2.1.6. -/ lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) : is_sheaf_for P R := is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for) /-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/ def is_separated (P : Cᵒᵖ ⥤ Type w) : Prop := ∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S /-- A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology. If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to check the sheaf condition at presieves in the pretopology. -/ def is_sheaf (P : Cᵒᵖ ⥤ Type w) : Prop := ∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type w} (hp : is_sheaf J P) (R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R := (is_sheaf_for_iff_generate R).2 $ hp _ hr lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type w) {J₁ J₂ : grothendieck_topology C} : J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P := λ h t X S hS, t S (h _ hS) lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type w) (h : is_sheaf J P) : is_separated J P := λ X S hS, (h S hS).is_separated_for /-- The property of being a sheaf is preserved by isomorphism. -/ lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' := λ X S hS, is_sheaf_for_iso i (h S hS) lemma is_sheaf_of_yoneda {P : Cᵒᵖ ⥤ Type v₁} (h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) : is_sheaf J P := λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS) /-- For a topology generated by a basis, it suffices to check the sheaf condition on the basis presieves only. -/ lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) : is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) := begin split, { intros PJ X R hR, rw is_sheaf_for_iff_generate, apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ }, { rintro PK X S ⟨R, hR, RS⟩, have gRS : ⇑(generate R) ≤ S, { apply gi_generate.gc.monotone_u, rwa sets_iff_generate }, apply is_sheaf_for_subsieve P gRS _, intros Y f, rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate], exact PK (pullback_arrows f R) (K.pullbacks f R hR) } end /-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/ lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P := λ X, by simp [is_sheaf_for_top_sieve] end presieve namespace equalizer variables {C : Type u₁} [category.{v₁} C] (P : Cᵒᵖ ⥤ Type (max v₁ u₁)) {X : C} (R : presieve X) (S : sieve X) noncomputable theory /-- The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def first_obj : Type (max v₁ u₁) := ∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) /-- Show that `first_obj` is isomorphic to `family_of_elements`. -/ @[simps] def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P := { hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t, inv := pi.lift (λ f x, x _ f.2.2), hom_inv_id' := begin ext ⟨Y, f, hf⟩ p, simpa, end, inv_hom_id' := begin ext x Y f hf, apply limits.types.limit.lift_π_apply, end } instance : inhabited (first_obj P (⊥ : presieve X)) := ((first_obj_eq_family P _).to_equiv).inhabited /-- The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def fork_map : P.obj (op X) ⟶ first_obj P R := pi.lift (λ f, P.map f.2.1.op) /-! This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and the definition of `is_sheaf_for`. -/ namespace sieve /-- The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used to check a family is compatible. -/ def second_obj : Type (max v₁ u₁) := ∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1)) /-- The map `p` of Equations (3,4) [MM92]. -/ def first_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f})) instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `a` of Equations (3,4) [MM92]. -/ def second_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op) lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S := begin apply limit.hom_ext, rintro ⟨Y, Z, g, f, hf⟩, simp [first_map, second_map, fork_map], end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P S) : ((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x := begin rw presieve.compatible_iff_sieve_compatible, split, { intro t, ext ⟨Y, Z, g, f, hf⟩, simpa [first_map, second_map] using t _ g hf }, { intros t Y Z f g hf, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨Y, Z, g, f, hf⟩ } end /-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/ lemma equalizer_sheaf_condition : presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) := begin rw [types.type_equalizer_iff_unique, ← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm], simp_rw ← compatible_iff, simp only [inv_hom_id_apply, iso.to_equiv_symm_fun], apply ball_congr, intros x tx, apply exists_unique_congr, intro t, rw ← iso.to_equiv_symm_fun, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [first_obj_eq_family, fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [first_obj_eq_family, fork_map] } end end sieve /-! This section establishes the equivalence between the sheaf condition of https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`. -/ namespace presieve variables [has_pullbacks C] /-- The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which contains the data used to check a family of elements for a presieve is compatible. -/ def second_obj : Type (max v₁ u₁) := ∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})), P.obj (op (pullback fg.1.2.1 fg.2.2.1))) /-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VL. -/ def first_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op) instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VL. -/ def second_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op) lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R := begin apply limit.hom_ext, rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩, simp only [first_map, second_map, fork_map], simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe], rw [← P.map_comp, ← op_comp, pullback.condition], simp, end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P R) : ((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x := begin rw presieve.pullback_compatible_iff, split, { intro t, ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩, simpa [first_map, second_map] using t hf hg }, { intros t Y Z f g hf hg, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨⟨Y, f, hf⟩, Z, g, hg⟩ } end /-- `P` is a sheaf for `R`, iff the fork given by `w` is an equalizer. See https://stacks.math.columbia.edu/tag/00VM. -/ lemma sheaf_condition : R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) := begin rw types.type_equalizer_iff_unique, erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm, simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply], apply ball_congr, intros x hx, apply exists_unique_congr, intros t, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [fork_map] } end end presieve end equalizer variables {C : Type u₁} [category.{v₁} C] variables (J : grothendieck_topology C) /-- The category of sheaves on a grothendieck topology. -/ @[derive category] def SheafOfTypes (J : grothendieck_topology C) : Type (max u₁ v₁ (w+1)) := {P : Cᵒᵖ ⥤ Type w // presieve.is_sheaf J P} /-- The inclusion functor from sheaves to presheaves. -/ @[simps {rhs_md := semireducible}, derive [full, faithful]] def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type w) := full_subcategory_inclusion (presieve.is_sheaf J) /-- The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category of presheaves. -/ @[simps] def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type w) := { functor := SheafOfTypes_to_presheaf _, inverse := { obj := λ P, ⟨P, presieve.is_sheaf_bot⟩, map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f }, unit_iso := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } }, counit_iso := iso.refl _ } instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) := ⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩ end category_theory
9c1e401d827e0aba6d4fc4931d299787d8c70289
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/measure_theory/measure/vector_measure.lean
0060ee50931632c3dbe1463efe8b584863770aae
[ "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
47,374
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.integral.lebesgue /-! # Vector valued measures This file defines vector valued measures, which are σ-additive functions from a set to a add monoid `M` such that it maps the empty set and non-measurable sets to zero. In the case that `M = ℝ`, we called the vector measure a signed measure and write `signed_measure α`. Similarly, when `M = ℂ`, we call the measure a complex measure and write `complex_measure α`. ## Main definitions * `measure_theory.vector_measure` is a vector valued, σ-additive function that maps the empty and non-measurable set to zero. * `measure_theory.vector_measure.map` is the pushforward of a vector measure along a function. * `measure_theory.vector_measure.restrict` is the restriction of a vector measure on some set. ## Notation * `v ≤[i] w` means that the vector measure `v` restricted on the set `i` is less than or equal to the vector measure `w` restricted on `i`, i.e. `v.restrict i ≤ w.restrict i`. ## Implementation notes We require all non-measurable sets to be mapped to zero in order for the extensionality lemma to only compare the underlying functions for measurable sets. We use `has_sum` instead of `tsum` in the definition of vector measures in comparison to `measure` since this provides summablity. ## Tags vector measure, signed measure, complex measure -/ noncomputable theory open_locale classical big_operators nnreal ennreal measure_theory namespace measure_theory variables {α β : Type*} {m : measurable_space α} /-- A vector measure on a measurable space `α` is a σ-additive `M`-valued function (for some `M` an add monoid) such that the empty set and non-measurable sets are mapped to zero. -/ structure vector_measure (α : Type*) [measurable_space α] (M : Type*) [add_comm_monoid M] [topological_space M] := (measure_of' : set α → M) (empty' : measure_of' ∅ = 0) (not_measurable' ⦃i : set α⦄ : ¬ measurable_set i → measure_of' i = 0) (m_Union' ⦃f : ℕ → set α⦄ : (∀ i, measurable_set (f i)) → pairwise (disjoint on f) → has_sum (λ i, measure_of' (f i)) (measure_of' (⋃ i, f i))) /-- A `signed_measure` is a `ℝ`-vector measure. -/ abbreviation signed_measure (α : Type*) [measurable_space α] := vector_measure α ℝ /-- A `complex_measure` is a `ℂ`-vector_measure. -/ abbreviation complex_measure (α : Type*) [measurable_space α] := vector_measure α ℂ open set measure_theory namespace vector_measure section variables {M : Type*} [add_comm_monoid M] [topological_space M] include m instance : has_coe_to_fun (vector_measure α M) := ⟨λ _, set α → M, vector_measure.measure_of'⟩ initialize_simps_projections vector_measure (measure_of' → apply) @[simp] lemma measure_of_eq_coe (v : vector_measure α M) : v.measure_of' = v := rfl @[simp] lemma empty (v : vector_measure α M) : v ∅ = 0 := v.empty' lemma not_measurable (v : vector_measure α M) {i : set α} (hi : ¬ measurable_set i) : v i = 0 := v.not_measurable' hi lemma m_Union (v : vector_measure α M) {f : ℕ → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : has_sum (λ i, v (f i)) (v (⋃ i, f i)) := v.m_Union' hf₁ hf₂ lemma of_disjoint_Union_nat [t2_space M] (v : vector_measure α M) {f : ℕ → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : v (⋃ i, f i) = ∑' i, v (f i) := (v.m_Union hf₁ hf₂).tsum_eq.symm lemma coe_injective : @function.injective (vector_measure α M) (set α → M) coe_fn := λ v w h, by { cases v, cases w, congr' } lemma ext_iff' (v w : vector_measure α M) : v = w ↔ ∀ i : set α, v i = w i := by rw [← coe_injective.eq_iff, function.funext_iff] lemma ext_iff (v w : vector_measure α M) : v = w ↔ ∀ i : set α, measurable_set i → v i = w i := begin split, { rintro rfl _ _, refl }, { rw ext_iff', intros h i, by_cases hi : measurable_set i, { exact h i hi }, { simp_rw [not_measurable _ hi] } } end @[ext] lemma ext {s t : vector_measure α M} (h : ∀ i : set α, measurable_set i → s i = t i) : s = t := (ext_iff s t).2 h variables [t2_space M] {v : vector_measure α M} {f : ℕ → set α} lemma has_sum_of_disjoint_Union [encodable β] {f : β → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : has_sum (λ i, v (f i)) (v (⋃ i, f i)) := begin set g := λ i : ℕ, ⋃ (b : β) (H : b ∈ encodable.decode₂ β i), f b with hg, have hg₁ : ∀ i, measurable_set (g i), { exact λ _, measurable_set.Union (λ b, measurable_set.Union_Prop $ λ _, hf₁ b) }, have hg₂ : pairwise (disjoint on g), { exact encodable.Union_decode₂_disjoint_on hf₂ }, have := v.of_disjoint_Union_nat hg₁ hg₂, rw [hg, encodable.Union_decode₂] at this, have hg₃ : (λ (i : β), v (f i)) = (λ i, v (g (encodable.encode i))), { ext, rw hg, simp only, congr, ext y, simp only [exists_prop, mem_Union, option.mem_def], split, { intro hy, refine ⟨x, (encodable.decode₂_is_partial_inv _ _).2 rfl, hy⟩ }, { rintro ⟨b, hb₁, hb₂⟩, rw (encodable.decode₂_is_partial_inv _ _) at hb₁, rwa ← encodable.encode_injective hb₁ } }, rw [summable.has_sum_iff, this, ← tsum_Union_decode₂], { exact v.empty }, { rw hg₃, change summable ((λ i, v (g i)) ∘ encodable.encode), rw function.injective.summable_iff encodable.encode_injective, { exact (v.m_Union hg₁ hg₂).summable }, { intros x hx, convert v.empty, simp only [Union_eq_empty, option.mem_def, not_exists, mem_range] at ⊢ hx, intros i hi, exact false.elim ((hx i) ((encodable.decode₂_is_partial_inv _ _).1 hi)) } } end lemma of_disjoint_Union [encodable β] {f : β → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : v (⋃ i, f i) = ∑' i, v (f i) := (has_sum_of_disjoint_Union hf₁ hf₂).tsum_eq.symm lemma of_union {A B : set α} (h : disjoint A B) (hA : measurable_set A) (hB : measurable_set B) : v (A ∪ B) = v A + v B := begin rw [union_eq_Union, of_disjoint_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [λ b, bool.cases_on b hB hA, pairwise_disjoint_on_bool.2 h] end lemma of_add_of_diff {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h : A ⊆ B) : v A + v (B \ A) = v B := begin rw [← of_union disjoint_diff hA (hB.diff hA), union_diff_cancel h], apply_instance, end lemma of_diff {M : Type*} [add_comm_group M] [topological_space M] [t2_space M] {v : vector_measure α M} {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h : A ⊆ B) : v (B \ A) = v B - (v A) := begin rw [← of_add_of_diff hA hB h, add_sub_cancel'], apply_instance, end lemma of_diff_of_diff_eq_zero {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h' : v (B \ A) = 0) : v (A \ B) + v B = v A := begin symmetry, calc v A = v (A \ B ∪ A ∩ B) : by simp only [set.diff_union_inter] ... = v (A \ B) + v (A ∩ B) : by { rw of_union, { rw disjoint.comm, exact set.disjoint_of_subset_left (A.inter_subset_right B) set.disjoint_diff }, { exact hA.diff hB }, { exact hA.inter hB } } ... = v (A \ B) + v (A ∩ B ∪ B \ A) : by { rw [of_union, h', add_zero], { exact set.disjoint_of_subset_left (A.inter_subset_left B) set.disjoint_diff }, { exact hA.inter hB }, { exact hB.diff hA } } ... = v (A \ B) + v B : by { rw [set.union_comm, set.inter_comm, set.diff_union_inter] } end lemma of_Union_nonneg {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] {v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, 0 ≤ v (f i)) : 0 ≤ v (⋃ i, f i) := (v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonneg hf₃ lemma of_Union_nonpos {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] {v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, v (f i) ≤ 0) : v (⋃ i, f i) ≤ 0 := (v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonpos hf₃ lemma of_nonneg_disjoint_union_eq_zero {s : signed_measure α} {A B : set α} (h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B) (hA₂ : 0 ≤ s A) (hB₂ : 0 ≤ s B) (hAB : s (A ∪ B) = 0) : s A = 0 := begin rw of_union h hA₁ hB₁ at hAB, linarith, apply_instance, end lemma of_nonpos_disjoint_union_eq_zero {s : signed_measure α} {A B : set α} (h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B) (hA₂ : s A ≤ 0) (hB₂ : s B ≤ 0) (hAB : s (A ∪ B) = 0) : s A = 0 := begin rw of_union h hA₁ hB₁ at hAB, linarith, apply_instance, end end section add_comm_monoid variables {M : Type*} [add_comm_monoid M] [topological_space M] include m instance : has_zero (vector_measure α M) := ⟨⟨0, rfl, λ _ _, rfl, λ _ _ _, has_sum_zero⟩⟩ instance : inhabited (vector_measure α M) := ⟨0⟩ @[simp] lemma coe_zero : ⇑(0 : vector_measure α M) = 0 := rfl lemma zero_apply (i : set α) : (0 : vector_measure α M) i = 0 := rfl variables [has_continuous_add M] /-- The sum of two vector measure is a vector measure. -/ def add (v w : vector_measure α M) : vector_measure α M := { measure_of' := v + w, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi, w.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.add (v.m_Union hf₁ hf₂) (w.m_Union hf₁ hf₂) } instance : has_add (vector_measure α M) := ⟨add⟩ @[simp] lemma coe_add (v w : vector_measure α M) : ⇑(v + w) = v + w := rfl lemma add_apply (v w : vector_measure α M) (i : set α) :(v + w) i = v i + w i := rfl instance : add_comm_monoid (vector_measure α M) := function.injective.add_comm_monoid _ coe_injective coe_zero coe_add /-- `coe_fn` is an `add_monoid_hom`. -/ @[simps] def coe_fn_add_monoid_hom : vector_measure α M →+ (set α → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } end add_comm_monoid section add_comm_group variables {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] include m /-- The negative of a vector measure is a vector measure. -/ def neg (v : vector_measure α M) : vector_measure α M := { measure_of' := -v, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.neg $ v.m_Union hf₁ hf₂ } instance : has_neg (vector_measure α M) := ⟨neg⟩ @[simp] lemma coe_neg (v : vector_measure α M) : ⇑(-v) = - v := rfl lemma neg_apply (v : vector_measure α M) (i : set α) :(-v) i = - v i := rfl /-- The difference of two vector measure is a vector measure. -/ def sub (v w : vector_measure α M) : vector_measure α M := { measure_of' := v - w, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi, w.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.sub (v.m_Union hf₁ hf₂) (w.m_Union hf₁ hf₂) } instance : has_sub (vector_measure α M) := ⟨sub⟩ @[simp] lemma coe_sub (v w : vector_measure α M) : ⇑(v - w) = v - w := rfl lemma sub_apply (v w : vector_measure α M) (i : set α) : (v - w) i = v i - w i := rfl instance : add_comm_group (vector_measure α M) := function.injective.add_comm_group _ coe_injective coe_zero coe_add coe_neg coe_sub end add_comm_group section distrib_mul_action variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [distrib_mul_action R M] variables [topological_space R] [has_continuous_smul R M] include m /-- Given a real number `r` and a signed measure `s`, `smul r s` is the signed measure corresponding to the function `r • s`. -/ def smul (r : R) (v : vector_measure α M) : vector_measure α M := { measure_of' := r • v, empty' := by rw [pi.smul_apply, empty, smul_zero], not_measurable' := λ _ hi, by rw [pi.smul_apply, v.not_measurable hi, smul_zero], m_Union' := λ _ hf₁ hf₂, has_sum.smul (v.m_Union hf₁ hf₂) } instance : has_scalar R (vector_measure α M) := ⟨smul⟩ @[simp] lemma coe_smul (r : R) (v : vector_measure α M) : ⇑(r • v) = r • v := rfl lemma smul_apply (r : R) (v : vector_measure α M) (i : set α) : (r • v) i = r • v i := rfl instance [has_continuous_add M] : distrib_mul_action R (vector_measure α M) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul end distrib_mul_action section module variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [module R M] variables [topological_space R] [has_continuous_smul R M] include m instance [has_continuous_add M] : module R (vector_measure α M) := function.injective.module R coe_fn_add_monoid_hom coe_injective coe_smul end module end vector_measure namespace measure include m /-- A finite measure coerced into a real function is a signed measure. -/ @[simps] def to_signed_measure (μ : measure α) [hμ : is_finite_measure μ] : signed_measure α := { measure_of' := λ i : set α, if measurable_set i then (μ.measure_of i).to_real else 0, empty' := by simp [μ.empty], not_measurable' := λ _ hi, if_neg hi, m_Union' := begin intros _ hf₁ hf₂, rw [μ.m_Union hf₁ hf₂, ennreal.tsum_to_real_eq, if_pos (measurable_set.Union hf₁), summable.has_sum_iff], { congr, ext n, rw if_pos (hf₁ n) }, { refine @summable_of_nonneg_of_le _ (ennreal.to_real ∘ μ ∘ f) _ _ _ _, { intro, split_ifs, exacts [ennreal.to_real_nonneg, le_refl _] }, { intro, split_ifs, exacts [le_refl _, ennreal.to_real_nonneg] }, exact summable_measure_to_real hf₁ hf₂ }, { intros a ha, apply ne_of_lt hμ.measure_univ_lt_top, rw [eq_top_iff, ← ha, outer_measure.measure_of_eq_coe, coe_to_outer_measure], exact measure_mono (set.subset_univ _) } end } lemma to_signed_measure_apply_measurable {μ : measure α} [is_finite_measure μ] {i : set α} (hi : measurable_set i) : μ.to_signed_measure i = (μ i).to_real := if_pos hi -- Without this lemma, `singular_part_neg` in `measure_theory.decomposition.lebesgue` is -- extremely slow lemma to_signed_measure_congr {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] (h : μ = ν) : μ.to_signed_measure = ν.to_signed_measure := by { congr, exact h } lemma to_signed_measure_eq_to_signed_measure_iff {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] : μ.to_signed_measure = ν.to_signed_measure ↔ μ = ν := begin refine ⟨λ h, _, λ h, _⟩, { ext1 i hi, have : μ.to_signed_measure i = ν.to_signed_measure i, { rw h }, rwa [to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi, ennreal.to_real_eq_to_real] at this; { exact measure_ne_top _ _ } }, { congr, assumption } end @[simp] lemma to_signed_measure_zero : (0 : measure α).to_signed_measure = 0 := by { ext i hi, simp } @[simp] lemma to_signed_measure_add (μ ν : measure α) [is_finite_measure μ] [is_finite_measure ν] : (μ + ν).to_signed_measure = μ.to_signed_measure + ν.to_signed_measure := begin ext i hi, rw [to_signed_measure_apply_measurable hi, add_apply, ennreal.to_real_add (ne_of_lt (measure_lt_top _ _ )) (ne_of_lt (measure_lt_top _ _)), vector_measure.add_apply, to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi], all_goals { apply_instance } end @[simp] lemma to_signed_measure_smul (μ : measure α) [is_finite_measure μ] (r : ℝ≥0) : (r • μ).to_signed_measure = r • μ.to_signed_measure := begin ext i hi, rw [to_signed_measure_apply_measurable hi, vector_measure.smul_apply, to_signed_measure_apply_measurable hi, coe_nnreal_smul, pi.smul_apply, ennreal.to_real_smul], end /-- A measure is a vector measure over `ℝ≥0∞`. -/ @[simps] def to_ennreal_vector_measure (μ : measure α) : vector_measure α ℝ≥0∞ := { measure_of' := λ i : set α, if measurable_set i then μ i else 0, empty' := by simp [μ.empty], not_measurable' := λ _ hi, if_neg hi, m_Union' := λ _ hf₁ hf₂, begin rw summable.has_sum_iff ennreal.summable, { rw [if_pos (measurable_set.Union hf₁), measure_theory.measure_Union hf₂ hf₁], exact tsum_congr (λ n, if_pos (hf₁ n)) }, end } lemma to_ennreal_vector_measure_apply_measurable {μ : measure α} {i : set α} (hi : measurable_set i) : μ.to_ennreal_vector_measure i = μ i := if_pos hi @[simp] lemma to_ennreal_vector_measure_zero : (0 : measure α).to_ennreal_vector_measure = 0 := by { ext i hi, simp } @[simp] lemma to_ennreal_vector_measure_add (μ ν : measure α) : (μ + ν).to_ennreal_vector_measure = μ.to_ennreal_vector_measure + ν.to_ennreal_vector_measure := begin refine measure_theory.vector_measure.ext (λ i hi, _), rw [to_ennreal_vector_measure_apply_measurable hi, add_apply, vector_measure.add_apply, to_ennreal_vector_measure_apply_measurable hi, to_ennreal_vector_measure_apply_measurable hi] end lemma to_signed_measure_sub_apply {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] {i : set α} (hi : measurable_set i) : (μ.to_signed_measure - ν.to_signed_measure) i = (μ i).to_real - (ν i).to_real := begin rw [vector_measure.sub_apply, to_signed_measure_apply_measurable hi, measure.to_signed_measure_apply_measurable hi, sub_eq_add_neg] end end measure namespace vector_measure open measure section /-- A vector measure over `ℝ≥0∞` is a measure. -/ def ennreal_to_measure {m : measurable_space α} (v : vector_measure α ℝ≥0∞) : measure α := of_measurable (λ s _, v s) v.empty (λ f hf₁ hf₂, v.of_disjoint_Union_nat hf₁ hf₂) lemma ennreal_to_measure_apply {m : measurable_space α} {v : vector_measure α ℝ≥0∞} {s : set α} (hs : measurable_set s) : ennreal_to_measure v s = v s := by rw [ennreal_to_measure, of_measurable_apply _ hs] /-- The equiv between `vector_measure α ℝ≥0∞` and `measure α` formed by `measure_theory.vector_measure.ennreal_to_measure` and `measure_theory.measure.to_ennreal_vector_measure`. -/ @[simps] def equiv_measure [measurable_space α] : vector_measure α ℝ≥0∞ ≃ measure α := { to_fun := ennreal_to_measure, inv_fun := to_ennreal_vector_measure, left_inv := λ _, ext (λ s hs, by rw [to_ennreal_vector_measure_apply_measurable hs, ennreal_to_measure_apply hs]), right_inv := λ _, measure.ext (λ s hs, by rw [ennreal_to_measure_apply hs, to_ennreal_vector_measure_apply_measurable hs]) } end section variables [measurable_space α] [measurable_space β] variables {M : Type*} [add_comm_monoid M] [topological_space M] variables (v : vector_measure α M) /-- The pushforward of a vector measure along a function. -/ def map (v : vector_measure α M) (f : α → β) : vector_measure β M := if hf : measurable f then { measure_of' := λ s, if measurable_set s then v (f ⁻¹' s) else 0, empty' := by simp, not_measurable' := λ i hi, if_neg hi, m_Union' := begin intros g hg₁ hg₂, convert v.m_Union (λ i, hf (hg₁ i)) (λ i j hij x hx, hg₂ i j hij hx), { ext i, rw if_pos (hg₁ i) }, { rw [preimage_Union, if_pos (measurable_set.Union hg₁)] } end } else 0 lemma map_not_measurable {f : α → β} (hf : ¬ measurable f) : v.map f = 0 := dif_neg hf lemma map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : v.map f s = v (f ⁻¹' s) := by { rw [map, dif_pos hf], exact if_pos hs } @[simp] lemma map_id : v.map id = v := ext (λ i hi, by rw [map_apply v measurable_id hi, preimage_id]) @[simp] lemma map_zero (f : α → β) : (0 : vector_measure α M).map f = 0 := begin by_cases hf : measurable f, { ext i hi, rw [map_apply _ hf hi, zero_apply, zero_apply] }, { exact dif_neg hf } end /-- The restriction of a vector measure on some set. -/ def restrict (v : vector_measure α M) (i : set α) : vector_measure α M := if hi : measurable_set i then { measure_of' := λ s, if measurable_set s then v (s ∩ i) else 0, empty' := by simp, not_measurable' := λ i hi, if_neg hi, m_Union' := begin intros f hf₁ hf₂, convert v.m_Union (λ n, (hf₁ n).inter hi) (hf₂.mono $ λ i j, disjoint.mono inf_le_left inf_le_left), { ext n, rw if_pos (hf₁ n) }, { rw [Union_inter, if_pos (measurable_set.Union hf₁)] } end } else 0 lemma restrict_not_measurable {i : set α} (hi : ¬ measurable_set i) : v.restrict i = 0 := dif_neg hi lemma restrict_apply {i : set α} (hi : measurable_set i) {j : set α} (hj : measurable_set j) : v.restrict i j = v (j ∩ i) := by { rw [restrict, dif_pos hi], exact if_pos hj } lemma restrict_eq_self {i : set α} (hi : measurable_set i) {j : set α} (hj : measurable_set j) (hij : j ⊆ i) : v.restrict i j = v j := by rw [restrict_apply v hi hj, inter_eq_left_iff_subset.2 hij] @[simp] lemma restrict_empty : v.restrict ∅ = 0 := ext (λ i hi, by rw [restrict_apply v measurable_set.empty hi, inter_empty, v.empty, zero_apply]) @[simp] lemma restrict_univ : v.restrict univ = v := ext (λ i hi, by rw [restrict_apply v measurable_set.univ hi, inter_univ]) @[simp] lemma restrict_zero {i : set α} : (0 : vector_measure α M).restrict i = 0 := begin by_cases hi : measurable_set i, { ext j hj, rw [restrict_apply 0 hi hj], refl }, { exact dif_neg hi } end section has_continuous_add variables [has_continuous_add M] lemma map_add (v w : vector_measure α M) (f : α → β) : (v + w).map f = v.map f + w.map f := begin by_cases hf : measurable f, { ext i hi, simp [map_apply _ hf hi] }, { simp [map, dif_neg hf] } end /-- `vector_measure.map` as an additive monoid homomorphism. -/ @[simps] def map_gm (f : α → β) : vector_measure α M →+ vector_measure β M := { to_fun := λ v, v.map f, map_zero' := map_zero f, map_add' := λ _ _, map_add _ _ f } lemma restrict_add (v w : vector_measure α M) (i : set α) : (v + w).restrict i = v.restrict i + w.restrict i := begin by_cases hi : measurable_set i, { ext j hj, simp [restrict_apply _ hi hj] }, { simp [restrict_not_measurable _ hi] } end /--`vector_measure.restrict` as an additive monoid homomorphism. -/ @[simps] def restrict_gm (i : set α) : vector_measure α M →+ vector_measure α M := { to_fun := λ v, v.restrict i, map_zero' := restrict_zero, map_add' := λ _ _, restrict_add _ _ i } end has_continuous_add end section variables [measurable_space β] variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [distrib_mul_action R M] variables [topological_space R] [has_continuous_smul R M] include m @[simp] lemma map_smul {v : vector_measure α M} {f : α → β} (c : R) : (c • v).map f = c • v.map f := begin by_cases hf : measurable f, { ext i hi, simp [map_apply _ hf hi] }, { simp only [map, dif_neg hf], -- `smul_zero` does not work since we do not require `has_continuous_add` ext i hi, simp } end @[simp] lemma restrict_smul {v :vector_measure α M} {i : set α} (c : R) : (c • v).restrict i = c • v.restrict i := begin by_cases hi : measurable_set i, { ext j hj, simp [restrict_apply _ hi hj] }, { simp only [restrict_not_measurable _ hi], -- `smul_zero` does not work since we do not require `has_continuous_add` ext j hj, simp } end end section variables [measurable_space β] variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [module R M] variables [topological_space R] [has_continuous_smul R M] [has_continuous_add M] include m /-- `vector_measure.map` as a linear map. -/ @[simps] def mapₗ (f : α → β) : vector_measure α M →ₗ[R] vector_measure β M := { to_fun := λ v, v.map f, map_add' := λ _ _, map_add _ _ f, map_smul' := λ _ _, map_smul _ } /-- `vector_measure.restrict` as an additive monoid homomorphism. -/ @[simps] def restrictₗ (i : set α) : vector_measure α M →ₗ[R] vector_measure α M := { to_fun := λ v, v.restrict i, map_add' := λ _ _, restrict_add _ _ i, map_smul' := λ _ _, restrict_smul _ } end section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] include m /-- Vector measures over a partially ordered monoid is partially ordered. This definition is consistent with `measure.partial_order`. -/ instance : partial_order (vector_measure α M) := { le := λ v w, ∀ i, measurable_set i → v i ≤ w i, le_refl := λ v i hi, le_refl _, le_trans := λ u v w h₁ h₂ i hi, le_trans (h₁ i hi) (h₂ i hi), le_antisymm := λ v w h₁ h₂, ext (λ i hi, le_antisymm (h₁ i hi) (h₂ i hi)) } variables {u v w : vector_measure α M} lemma le_iff : v ≤ w ↔ ∀ i, measurable_set i → v i ≤ w i := iff.rfl lemma le_iff' : v ≤ w ↔ ∀ i, v i ≤ w i := begin refine ⟨λ h i, _, λ h i hi, h i⟩, by_cases hi : measurable_set i, { exact h i hi }, { rw [v.not_measurable hi, w.not_measurable hi] } end end localized "notation v ` ≤[`:50 i:50 `] `:0 w:50 := measure_theory.vector_measure.restrict v i ≤ measure_theory.vector_measure.restrict w i" in measure_theory section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] variables (v w : vector_measure α M) lemma restrict_le_restrict_iff {i : set α} (hi : measurable_set i) : v ≤[i] w ↔ ∀ ⦃j⦄, measurable_set j → j ⊆ i → v j ≤ w j := ⟨λ h j hj₁ hj₂, (restrict_eq_self v hi hj₁ hj₂) ▸ (restrict_eq_self w hi hj₁ hj₂) ▸ h j hj₁, λ h, le_iff.1 (λ j hj, (restrict_apply v hi hj).symm ▸ (restrict_apply w hi hj).symm ▸ h (hj.inter hi) (set.inter_subset_right j i))⟩ lemma subset_le_of_restrict_le_restrict {i : set α} (hi : measurable_set i) (hi₂ : v ≤[i] w) {j : set α} (hj : j ⊆ i) : v j ≤ w j := begin by_cases hj₁ : measurable_set j, { exact (restrict_le_restrict_iff _ _ hi).1 hi₂ hj₁ hj }, { rw [v.not_measurable hj₁, w.not_measurable hj₁] }, end lemma restrict_le_restrict_of_subset_le {i : set α} (h : ∀ ⦃j⦄, measurable_set j → j ⊆ i → v j ≤ w j) : v ≤[i] w := begin by_cases hi : measurable_set i, { exact (restrict_le_restrict_iff _ _ hi).2 h }, { rw [restrict_not_measurable v hi, restrict_not_measurable w hi], exact le_refl _ }, end lemma restrict_le_restrict_subset {i j : set α} (hi₁ : measurable_set i) (hi₂ : v ≤[i] w) (hij : j ⊆ i) : v ≤[j] w := restrict_le_restrict_of_subset_le v w (λ k hk₁ hk₂, subset_le_of_restrict_le_restrict v w hi₁ hi₂ (set.subset.trans hk₂ hij)) lemma le_restrict_empty : v ≤[∅] w := begin intros j hj, rw [restrict_empty, restrict_empty] end lemma le_restrict_univ_iff_le : v ≤[univ] w ↔ v ≤ w := begin split, { intros h s hs, have := h s hs, rwa [restrict_apply _ measurable_set.univ hs, inter_univ, restrict_apply _ measurable_set.univ hs, inter_univ] at this }, { intros h s hs, rw [restrict_apply _ measurable_set.univ hs, inter_univ, restrict_apply _ measurable_set.univ hs, inter_univ], exact h s hs } end end section variables {M : Type*} [topological_space M] [ordered_add_comm_group M] [topological_add_group M] variables (v w : vector_measure α M) lemma neg_le_neg {i : set α} (hi : measurable_set i) (h : v ≤[i] w) : -w ≤[i] -v := begin intros j hj₁, rw [restrict_apply _ hi hj₁, restrict_apply _ hi hj₁, neg_apply, neg_apply], refine neg_le_neg _, rw [← restrict_apply _ hi hj₁, ← restrict_apply _ hi hj₁], exact h j hj₁, end @[simp] lemma neg_le_neg_iff {i : set α} (hi : measurable_set i) : -w ≤[i] -v ↔ v ≤[i] w := ⟨λ h, neg_neg v ▸ neg_neg w ▸ neg_le_neg _ _ hi h, λ h, neg_le_neg _ _ hi h⟩ end section variables {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] variables (v w : vector_measure α M) {i j : set α} lemma restrict_le_restrict_Union {f : ℕ → set α} (hf₁ : ∀ n, measurable_set (f n)) (hf₂ : ∀ n, v ≤[f n] w) : v ≤[⋃ n, f n] w := begin refine restrict_le_restrict_of_subset_le v w (λ a ha₁ ha₂, _), have ha₃ : (⋃ n, a ∩ disjointed f n) = a, { rwa [← inter_Union, Union_disjointed, inter_eq_left_iff_subset] }, have ha₄ : pairwise (disjoint on (λ n, a ∩ disjointed f n)), { exact (disjoint_disjointed _).mono (λ i j, disjoint.mono inf_le_right inf_le_right) }, rw [← ha₃, v.of_disjoint_Union_nat _ ha₄, w.of_disjoint_Union_nat _ ha₄], refine tsum_le_tsum (λ n, (restrict_le_restrict_iff v w (hf₁ n)).1 (hf₂ n) _ _) _ _, { exact (ha₁.inter (measurable_set.disjointed hf₁ n)) }, { exact set.subset.trans (set.inter_subset_right _ _) (disjointed_subset _ _) }, { refine (v.m_Union (λ n, _) _).summable, { exact ha₁.inter (measurable_set.disjointed hf₁ n) }, { exact (disjoint_disjointed _).mono (λ i j, disjoint.mono inf_le_right inf_le_right) } }, { refine (w.m_Union (λ n, _) _).summable, { exact ha₁.inter (measurable_set.disjointed hf₁ n) }, { exact (disjoint_disjointed _).mono (λ i j, disjoint.mono inf_le_right inf_le_right) } }, { intro n, exact (ha₁.inter (measurable_set.disjointed hf₁ n)) }, { exact λ n, ha₁.inter (measurable_set.disjointed hf₁ n) } end lemma restrict_le_restrict_encodable_Union [encodable β] {f : β → set α} (hf₁ : ∀ b, measurable_set (f b)) (hf₂ : ∀ b, v ≤[f b] w) : v ≤[⋃ b, f b] w := begin rw ← encodable.Union_decode₂, refine restrict_le_restrict_Union v w _ _, { intro n, measurability }, { intro n, cases encodable.decode₂ β n with b, { simp }, { simp [hf₂ b] } } end lemma restrict_le_restrict_union (hi₁ : measurable_set i) (hi₂ : v ≤[i] w) (hj₁ : measurable_set j) (hj₂ : v ≤[j] w) : v ≤[i ∪ j] w := begin rw union_eq_Union, refine restrict_le_restrict_encodable_Union v w _ _, { measurability }, { rintro (_ | _); simpa } end end section variables {M : Type*} [topological_space M] [ordered_add_comm_monoid M] variables (v w : vector_measure α M) {i j : set α} lemma nonneg_of_zero_le_restrict (hi₂ : 0 ≤[i] v) : 0 ≤ v i := begin by_cases hi₁ : measurable_set i, { exact (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hi₁ set.subset.rfl }, { rw v.not_measurable hi₁ }, end lemma nonpos_of_restrict_le_zero (hi₂ : v ≤[i] 0) : v i ≤ 0 := begin by_cases hi₁ : measurable_set i, { exact (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hi₁ set.subset.rfl }, { rw v.not_measurable hi₁ } end lemma zero_le_restrict_not_measurable (hi : ¬ measurable_set i) : 0 ≤[i] v := begin rw [restrict_zero, restrict_not_measurable _ hi], exact le_refl _, end lemma restrict_le_zero_of_not_measurable (hi : ¬ measurable_set i) : v ≤[i] 0 := begin rw [restrict_zero, restrict_not_measurable _ hi], exact le_refl _, end lemma measurable_of_not_zero_le_restrict (hi : ¬ 0 ≤[i] v) : measurable_set i := not.imp_symm (zero_le_restrict_not_measurable _) hi lemma measurable_of_not_restrict_le_zero (hi : ¬ v ≤[i] 0) : measurable_set i := not.imp_symm (restrict_le_zero_of_not_measurable _) hi lemma zero_le_restrict_subset (hi₁ : measurable_set i) (hij : j ⊆ i) (hi₂ : 0 ≤[i] v): 0 ≤[j] v := restrict_le_restrict_of_subset_le _ _ (λ k hk₁ hk₂, (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hk₁ (set.subset.trans hk₂ hij)) lemma restrict_le_zero_subset (hi₁ : measurable_set i) (hij : j ⊆ i) (hi₂ : v ≤[i] 0): v ≤[j] 0 := restrict_le_restrict_of_subset_le _ _ (λ k hk₁ hk₂, (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hk₁ (set.subset.trans hk₂ hij)) end section variables {M : Type*} [topological_space M] [linear_ordered_add_comm_monoid M] variables (v w : vector_measure α M) {i j : set α} include m lemma exists_pos_measure_of_not_restrict_le_zero (hi : ¬ v ≤[i] 0) : ∃ j : set α, measurable_set j ∧ j ⊆ i ∧ 0 < v j := begin have hi₁ : measurable_set i := measurable_of_not_restrict_le_zero _ hi, rw [restrict_le_restrict_iff _ _ hi₁] at hi, push_neg at hi, obtain ⟨j, hj₁, hj₂, hj⟩ := hi, exact ⟨j, hj₁, hj₂, hj⟩, end end section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] [covariant_class M M (+) (≤)] [has_continuous_add M] include m instance covariant_add_le : covariant_class (vector_measure α M) (vector_measure α M) (+) (≤) := ⟨λ u v w h i hi, add_le_add_left (h i hi) _⟩ end section variables {L M N : Type*} variables [add_comm_monoid L] [topological_space L] [add_comm_monoid M] [topological_space M] [add_comm_monoid N] [topological_space N] include m /-- A vector measure `v` is absolutely continuous with respect to a measure `μ` if for all sets `s`, `μ s = 0`, we have `v s = 0`. -/ def absolutely_continuous (v : vector_measure α M) (w : vector_measure α N) := ∀ ⦃s : set α⦄, w s = 0 → v s = 0 infix ` ≪ `:50 := absolutely_continuous namespace absolutely_continuous variables {v : vector_measure α M} {w : vector_measure α N} lemma mk (h : ∀ ⦃s : set α⦄, measurable_set s → w s = 0 → v s = 0) : v ≪ w := begin intros s hs, by_cases hmeas : measurable_set s, { exact h hmeas hs }, { exact not_measurable v hmeas } end lemma eq {w : vector_measure α M} (h : v = w) : v ≪ w := λ s hs, h.symm ▸ hs @[refl] lemma refl (v : vector_measure α M) : v ≪ v := eq rfl @[trans] lemma trans {u : vector_measure α L} (huv : u ≪ v) (hvw : v ≪ w) : u ≪ w := λ _ hs, huv $ hvw hs lemma zero (v : vector_measure α N) : (0 : vector_measure α M) ≪ v := λ s _, vector_measure.zero_apply s lemma neg_left {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v : vector_measure α M} {w : vector_measure α N} (h : v ≪ w) : -v ≪ w := λ s hs, by { rw [neg_apply, h hs, neg_zero] } lemma neg_right {N : Type*} [add_comm_group N] [topological_space N] [topological_add_group N] {v : vector_measure α M} {w : vector_measure α N} (h : v ≪ w) : v ≪ -w := begin intros s hs, rw [neg_apply, neg_eq_zero] at hs, exact h hs end lemma add [has_continuous_add M] {v₁ v₂ : vector_measure α M} {w : vector_measure α N} (hv₁ : v₁ ≪ w) (hv₂ : v₂ ≪ w) : v₁ + v₂ ≪ w := λ s hs, by { rw [add_apply, hv₁ hs, hv₂ hs, zero_add] } lemma sub {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v₁ v₂ : vector_measure α M} {w : vector_measure α N} (hv₁ : v₁ ≪ w) (hv₂ : v₂ ≪ w) : v₁ - v₂ ≪ w := λ s hs, by { rw [sub_apply, hv₁ hs, hv₂ hs, zero_sub, neg_zero] } lemma smul {R : Type*} [semiring R] [distrib_mul_action R M] [topological_space R] [has_continuous_smul R M] {r : R} {v : vector_measure α M} {w : vector_measure α N} (h : v ≪ w) : r • v ≪ w := λ s hs, by { rw [smul_apply, h hs, smul_zero] } lemma map [measure_space β] (h : v ≪ w) (f : α → β) : v.map f ≪ w.map f := begin by_cases hf : measurable f, { refine mk (λ s hs hws, _), rw map_apply _ hf hs at hws ⊢, exact h hws }, { intros s hs, rw [map_not_measurable v hf, zero_apply] } end lemma ennreal_to_measure {μ : vector_measure α ℝ≥0∞} : (∀ ⦃s : set α⦄, μ.ennreal_to_measure s = 0 → v s = 0) ↔ v ≪ μ := begin split; intro h, { refine mk (λ s hmeas hs, h _), rw [← hs, ennreal_to_measure_apply hmeas] }, { intros s hs, by_cases hmeas : measurable_set s, { rw ennreal_to_measure_apply hmeas at hs, exact h hs }, { exact not_measurable v hmeas } }, end end absolutely_continuous /-- Two vector measures `v` and `w` are said to be mutually singular if there exists a measurable set `s`, such that for all `t ⊆ s`, `v t = 0` and for all `t ⊆ sᶜ`, `w t = 0`. We note that we do not require the measurability of `t` in the definition since this makes it easier to use. This is equivalent to the definition which requires measurability. To prove `mutually_singular` with the measurability condition, use `measure_theory.vector_measure.mutually_singular.mk`. -/ def mutually_singular (v : vector_measure α M) (w : vector_measure α N) : Prop := ∃ (s : set α), measurable_set s ∧ (∀ t ⊆ s, v t = 0) ∧ (∀ t ⊆ sᶜ, w t = 0) localized "infix ` ⊥ᵥ `:60 := measure_theory.vector_measure.mutually_singular" in measure_theory namespace mutually_singular variables {v v₁ v₂ : vector_measure α M} {w w₁ w₂ : vector_measure α N} lemma mk (s : set α) (hs : measurable_set s) (h₁ : ∀ t ⊆ s, measurable_set t → v t = 0) (h₂ : ∀ t ⊆ sᶜ, measurable_set t → w t = 0) : v ⊥ᵥ w := begin refine ⟨s, hs, λ t hst, _, λ t hst, _⟩; by_cases ht : measurable_set t, { exact h₁ t hst ht }, { exact not_measurable v ht }, { exact h₂ t hst ht }, { exact not_measurable w ht } end lemma symm (h : v ⊥ᵥ w) : w ⊥ᵥ v := let ⟨s, hmeas, hs₁, hs₂⟩ := h in ⟨sᶜ, hmeas.compl, hs₂, λ t ht, hs₁ _ (compl_compl s ▸ ht : t ⊆ s)⟩ lemma zero_right : v ⊥ᵥ (0 : vector_measure α N) := ⟨∅, measurable_set.empty, λ t ht, (subset_empty_iff.1 ht).symm ▸ v.empty, λ _ _, zero_apply _⟩ lemma zero_left : (0 : vector_measure α M) ⊥ᵥ w := zero_right.symm lemma add_left [t2_space N] [has_continuous_add M] (h₁ : v₁ ⊥ᵥ w) (h₂ : v₂ ⊥ᵥ w) : v₁ + v₂ ⊥ᵥ w := begin obtain ⟨u, hmu, hu₁, hu₂⟩ := h₁, obtain ⟨v, hmv, hv₁, hv₂⟩ := h₂, refine mk (u ∩ v) (hmu.inter hmv) (λ t ht hmt, _) (λ t ht hmt, _), { rw [add_apply, hu₁ _ (subset_inter_iff.1 ht).1, hv₁ _ (subset_inter_iff.1 ht).2, zero_add] }, { rw compl_inter at ht, rw [(_ : t = (uᶜ ∩ t) ∪ (vᶜ \ uᶜ ∩ t)), of_union _ (hmu.compl.inter hmt) ((hmv.compl.diff hmu.compl).inter hmt), hu₂, hv₂, add_zero], { exact subset.trans (inter_subset_left _ _) (diff_subset _ _) }, { exact inter_subset_left _ _ }, { apply_instance }, { exact disjoint.mono (inter_subset_left _ _) (inter_subset_left _ _) disjoint_diff }, { apply subset.antisymm; intros x hx, { by_cases hxu' : x ∈ uᶜ, { exact or.inl ⟨hxu', hx⟩ }, rcases ht hx with (hxu | hxv), exacts [false.elim (hxu' hxu), or.inr ⟨⟨hxv, hxu'⟩, hx⟩] }, { rcases hx; exact hx.2 } } }, end lemma add_right [t2_space M] [has_continuous_add N] (h₁ : v ⊥ᵥ w₁) (h₂ : v ⊥ᵥ w₂) : v ⊥ᵥ w₁ + w₂ := (add_left h₁.symm h₂.symm).symm lemma smul_right {R : Type*} [semiring R] [distrib_mul_action R N] [topological_space R] [has_continuous_smul R N] (r : R) (h : v ⊥ᵥ w) : v ⊥ᵥ r • w := let ⟨s, hmeas, hs₁, hs₂⟩ := h in ⟨s, hmeas, hs₁, λ t ht, by simp only [coe_smul, pi.smul_apply, hs₂ t ht, smul_zero]⟩ lemma smul_left {R : Type*} [semiring R] [distrib_mul_action R M] [topological_space R] [has_continuous_smul R M] (r : R) (h : v ⊥ᵥ w) : r • v ⊥ᵥ w := (smul_right r h.symm).symm lemma neg_left {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v : vector_measure α M} {w : vector_measure α N} (h : v ⊥ᵥ w) : -v ⊥ᵥ w := begin obtain ⟨u, hmu, hu₁, hu₂⟩ := h, refine ⟨u, hmu, λ s hs, _, hu₂⟩, rw [neg_apply v s, neg_eq_zero], exact hu₁ s hs end lemma neg_right {N : Type*} [add_comm_group N] [topological_space N] [topological_add_group N] {v : vector_measure α M} {w : vector_measure α N} (h : v ⊥ᵥ w) : v ⊥ᵥ -w := h.symm.neg_left.symm @[simp] lemma neg_left_iff {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v : vector_measure α M} {w : vector_measure α N} : -v ⊥ᵥ w ↔ v ⊥ᵥ w := ⟨λ h, neg_neg v ▸ h.neg_left, neg_left⟩ @[simp] lemma neg_right_iff {N : Type*} [add_comm_group N] [topological_space N] [topological_add_group N] {v : vector_measure α M} {w : vector_measure α N} : v ⊥ᵥ -w ↔ v ⊥ᵥ w := ⟨λ h, neg_neg w ▸ h.neg_right, neg_right⟩ end mutually_singular section trim omit m /-- Restriction of a vector measure onto a sub-σ-algebra. -/ @[simps] def trim {m n : measurable_space α} (v : vector_measure α M) (hle : m ≤ n) : @vector_measure α m M _ _ := { measure_of' := λ i, if measurable_set[m] i then v i else 0, empty' := by rw [if_pos measurable_set.empty, v.empty], not_measurable' := λ i hi, by rw if_neg hi, m_Union' := λ f hf₁ hf₂, begin have hf₁' : ∀ k, measurable_set[n] (f k) := λ k, hle _ (hf₁ k), convert v.m_Union hf₁' hf₂, { ext n, rw if_pos (hf₁ n) }, { rw if_pos (@measurable_set.Union _ _ m _ _ hf₁) } end } variables {n : measurable_space α} {v : vector_measure α M} lemma trim_eq_self : v.trim le_rfl = v := begin ext1 i hi, exact if_pos hi, end @[simp] lemma zero_trim (hle : m ≤ n) : (0 : vector_measure α M).trim hle = 0 := begin ext1 i hi, exact if_pos hi, end lemma trim_measurable_set_eq (hle : m ≤ n) {i : set α} (hi : measurable_set[m] i) : v.trim hle i = v i := if_pos hi lemma restrict_trim (hle : m ≤ n) {i : set α} (hi : measurable_set[m] i) : @vector_measure.restrict α m M _ _ (v.trim hle) i = (v.restrict i).trim hle := begin ext j hj, rw [restrict_apply, trim_measurable_set_eq hle hj, restrict_apply, trim_measurable_set_eq], all_goals { measurability } end end trim end end vector_measure namespace signed_measure open vector_measure open_locale measure_theory include m /-- The underlying function for `signed_measure.to_measure_of_zero_le`. -/ def to_measure_of_zero_le' (s : signed_measure α) (i : set α) (hi : 0 ≤[i] s) (j : set α) (hj : measurable_set j) : ℝ≥0∞ := @coe ℝ≥0 ℝ≥0∞ _ ⟨s.restrict i j, le_trans (by simp) (hi j hj)⟩ /-- Given a signed measure `s` and a positive measurable set `i`, `to_measure_of_zero_le` provides the measure, mapping measurable sets `j` to `s (i ∩ j)`. -/ def to_measure_of_zero_le (s : signed_measure α) (i : set α) (hi₁ : measurable_set i) (hi₂ : 0 ≤[i] s) : measure α := measure.of_measurable (s.to_measure_of_zero_le' i hi₂) (by { simp_rw [to_measure_of_zero_le', s.restrict_apply hi₁ measurable_set.empty, set.empty_inter i, s.empty], refl }) begin intros f hf₁ hf₂, have h₁ : ∀ n, measurable_set (i ∩ f n) := λ n, hi₁.inter (hf₁ n), have h₂ : pairwise (disjoint on λ (n : ℕ), i ∩ f n), { rintro n m hnm x ⟨⟨_, hx₁⟩, _, hx₂⟩, exact hf₂ n m hnm ⟨hx₁, hx₂⟩ }, simp only [to_measure_of_zero_le', s.restrict_apply hi₁ (measurable_set.Union hf₁), set.inter_comm, set.inter_Union, s.of_disjoint_Union_nat h₁ h₂, ennreal.some_eq_coe, id.def], have h : ∀ n, 0 ≤ s (i ∩ f n) := λ n, s.nonneg_of_zero_le_restrict (s.zero_le_restrict_subset hi₁ (inter_subset_left _ _) hi₂), rw [nnreal.coe_tsum_of_nonneg h, ennreal.coe_tsum], { refine tsum_congr (λ n, _), simp_rw [s.restrict_apply hi₁ (hf₁ n), set.inter_comm] }, { exact (nnreal.summable_coe_of_nonneg h).2 (s.m_Union h₁ h₂).summable } end variables (s : signed_measure α) {i j : set α} lemma to_measure_of_zero_le_apply (hi : 0 ≤[i] s) (hi₁ : measurable_set i) (hj₁ : measurable_set j) : s.to_measure_of_zero_le i hi₁ hi j = @coe ℝ≥0 ℝ≥0∞ _ ⟨s (i ∩ j), nonneg_of_zero_le_restrict s (zero_le_restrict_subset s hi₁ (set.inter_subset_left _ _) hi)⟩ := by simp_rw [to_measure_of_zero_le, measure.of_measurable_apply _ hj₁, to_measure_of_zero_le', s.restrict_apply hi₁ hj₁, set.inter_comm] /-- Given a signed measure `s` and a negative measurable set `i`, `to_measure_of_le_zero` provides the measure, mapping measurable sets `j` to `-s (i ∩ j)`. -/ def to_measure_of_le_zero (s : signed_measure α) (i : set α) (hi₁ : measurable_set i) (hi₂ : s ≤[i] 0) : measure α := to_measure_of_zero_le (-s) i hi₁ $ (@neg_zero (vector_measure α ℝ) _) ▸ neg_le_neg _ _ hi₁ hi₂ lemma to_measure_of_le_zero_apply (hi : s ≤[i] 0) (hi₁ : measurable_set i) (hj₁ : measurable_set j) : s.to_measure_of_le_zero i hi₁ hi j = @coe ℝ≥0 ℝ≥0∞ _ ⟨-s (i ∩ j), neg_apply s (i ∩ j) ▸ nonneg_of_zero_le_restrict _ (zero_le_restrict_subset _ hi₁ (set.inter_subset_left _ _) ((@neg_zero (vector_measure α ℝ) _) ▸ neg_le_neg _ _ hi₁ hi))⟩ := begin erw [to_measure_of_zero_le_apply], { simp }, { assumption }, end /-- `signed_measure.to_measure_of_zero_le` is a finite measure. -/ instance to_measure_of_zero_le_finite (hi : 0 ≤[i] s) (hi₁ : measurable_set i) : is_finite_measure (s.to_measure_of_zero_le i hi₁ hi) := { measure_univ_lt_top := begin rw [to_measure_of_zero_le_apply s hi hi₁ measurable_set.univ], exact ennreal.coe_lt_top, end } /-- `signed_measure.to_measure_of_le_zero` is a finite measure. -/ instance to_measure_of_le_zero_finite (hi : s ≤[i] 0) (hi₁ : measurable_set i) : is_finite_measure (s.to_measure_of_le_zero i hi₁ hi) := { measure_univ_lt_top := begin rw [to_measure_of_le_zero_apply s hi hi₁ measurable_set.univ], exact ennreal.coe_lt_top, end } lemma to_measure_of_zero_le_to_signed_measure (hs : 0 ≤[univ] s) : (s.to_measure_of_zero_le univ measurable_set.univ hs).to_signed_measure = s := begin ext i hi, simp [measure.to_signed_measure_apply_measurable hi, to_measure_of_zero_le_apply _ _ _ hi], end lemma to_measure_of_le_zero_to_signed_measure (hs : s ≤[univ] 0) : (s.to_measure_of_le_zero univ measurable_set.univ hs).to_signed_measure = -s := begin ext i hi, simp [measure.to_signed_measure_apply_measurable hi, to_measure_of_le_zero_apply _ _ _ hi], end end signed_measure namespace measure open vector_measure variables (μ : measure α) [is_finite_measure μ] lemma zero_le_to_signed_measure : 0 ≤ μ.to_signed_measure := begin rw ← le_restrict_univ_iff_le, refine restrict_le_restrict_of_subset_le _ _ (λ j hj₁ _, _), simp only [measure.to_signed_measure_apply_measurable hj₁, coe_zero, pi.zero_apply, ennreal.to_real_nonneg, vector_measure.coe_zero] end lemma to_signed_measure_to_measure_of_zero_le : μ.to_signed_measure.to_measure_of_zero_le univ measurable_set.univ ((le_restrict_univ_iff_le _ _).2 (zero_le_to_signed_measure μ)) = μ := begin refine measure.ext (λ i hi, _), lift μ i to ℝ≥0 using (measure_lt_top _ _).ne with m hm, simp [signed_measure.to_measure_of_zero_le_apply _ _ _ hi, measure.to_signed_measure_apply_measurable hi, ← hm], end end measure end measure_theory
3e284be318f39a8838a1fac847865a960f10fbf4
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/homology/exact.lean
6fce3a5bcc95532f3bc634387cdb105714798aea
[ "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
3,555
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.homology.image_to_kernel_map /-! # Exact sequences In a category with zero morphisms, images, and equalizers we say that `f : A ⟶ B` and `g : B ⟶ C` are exact if `f ≫ g = 0` and the natural map `image f ⟶ kernel g` is an epimorphism. (We say epimorphism rather than isomorphism because, at least for preadditive categories, this is exactly equivalent to the homology at `i` vanishing. In an abelian category, this is the same as asking for it to be an isomorphism, because the inclusion map is always a monomorphism.) # Main results * Suppose that cokernels exist and that `f` and `g` are exact. If `s` is any kernel fork over `g` and `t` is any cokernel cofork over `f`, then `fork.ι s ≫ cofork.π t = 0`. See also `category_theory/abelian/exact.lean` for results that only hold in abelian categories. # Future work * Short exact sequences, split exact sequences, the splitting lemma (maybe only for abelian categories?) * Two adjacent maps in a chain complex are exact iff the homology vanishes * Composing with isomorphisms retains exactness, and similar constructions -/ universes v u open category_theory open category_theory.limits variables {V : Type u} [category.{v} V] [has_zero_morphisms V] variables [has_equalizers V] [has_images V] namespace category_theory /-- Two morphisms `f : A ⟶ B`, `g : B ⟶ C` are called exact if `f ≫ g = 0` and the natural map `image f ⟶ kernel g` is an epimorphism. -/ class exact {A B C : V} (f : A ⟶ B) (g : B ⟶ C) : Prop := (w : f ≫ g = 0) (epi : epi (image_to_kernel_map f g w)) attribute [instance] exact.epi lemma exact.w_assoc {A B C D : V} {f : A ⟶ B} {g : B ⟶ C} [exact f g] {h : C ⟶ D} : f ≫ g ≫ h = 0 := by rw [←category.assoc, @exact.w _ _ _ _ _ _ _ _ f g, zero_comp] instance exact_comp_iso {A B C C' : V} (f : A ⟶ B) (g : B ⟶ C) (h : C ≅ C') [exact f g] : exact f (g ≫ h.hom) := { w := exact.w_assoc, epi := by { simp only [image_to_kernel_map_comp_iso], apply epi_comp, } } instance exact_iso_comp {A A' B C : V} (h : A' ≅ A) (f : A ⟶ B) (g : B ⟶ C) [exact f g] : exact (h.hom ≫ f) g := { w := by rw [category.assoc, @exact.w _ _ _ _ _ _ _ _ f g, comp_zero], epi := by { simp only [image_to_kernel_map_iso_comp], apply epi_comp, } } section variables [has_cokernels V] {A B C : V} (f : A ⟶ B) (g : B ⟶ C) @[simp, reassoc] lemma kernel_comp_cokernel [exact f g] : kernel.ι g ≫ cokernel.π f = 0 := zero_of_epi_comp (image_to_kernel_map f g exact.w) $ zero_of_epi_comp (factor_thru_image f) $ by simp lemma comp_eq_zero_of_exact [exact f g] {X Y : V} {ι : X ⟶ B} (hι : ι ≫ g = 0) {π : B ⟶ Y} (hπ : f ≫ π = 0) : ι ≫ π = 0 := by rw [←kernel.lift_ι _ _ hι, ←cokernel.π_desc _ _ hπ, category.assoc, kernel_comp_cokernel_assoc, zero_comp, comp_zero] @[simp, reassoc] lemma fork_ι_comp_cofork_π [exact f g] (s : kernel_fork g) (t : cokernel_cofork f) : fork.ι s ≫ cofork.π t = 0 := comp_eq_zero_of_exact f g (kernel_fork.condition s) (cokernel_cofork.condition t) end section local attribute [instance] has_zero_object.has_zero lemma exact_of_zero [has_zero_object V] {A C : V} (f : A ⟶ 0) (g : 0 ⟶ C) : exact f g := begin obtain rfl : f = 0 := by ext, obtain rfl : g = 0 := by ext, fsplit, { simp, }, { exact image_to_kernel_map_epi_of_zero_of_mono 0, }, end end end category_theory
b117167a7ff0d40300d114079e28788bb3b1e8ca
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/polynomial/group_ring_action.lean
04ef2679a4fcbc4fb9d0f8036a31c019246491fe
[ "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,942
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.polynomial.monic import data.polynomial.algebra_map import algebra.group_ring_action import algebra.group_action_hom /-! # Group action on rings applied to polynomials This file contains instances and definitions relating `mul_semiring_action` to `polynomial`. -/ variables (M : Type*) [monoid M] namespace polynomial variables (R : Type*) [semiring R] variables {M} lemma smul_eq_map [mul_semiring_action M R] (m : M) : ((•) m) = map (mul_semiring_action.to_ring_hom M R m) := begin suffices : distrib_mul_action.to_add_monoid_hom (polynomial R) m = (map_ring_hom (mul_semiring_action.to_ring_hom M R m)).to_add_monoid_hom, { ext1 r, exact add_monoid_hom.congr_fun this r, }, ext n r : 2, change m • monomial n r = map (mul_semiring_action.to_ring_hom M R m) (monomial n r), simpa only [polynomial.map_monomial, polynomial.smul_monomial], end variables (M) noncomputable instance [mul_semiring_action M R] : mul_semiring_action M (polynomial R) := { smul := (•), smul_one := λ m, (smul_eq_map R m).symm ▸ map_one (mul_semiring_action.to_ring_hom M R m), smul_mul := λ m p q, (smul_eq_map R m).symm ▸ map_mul (mul_semiring_action.to_ring_hom M R m), ..polynomial.distrib_mul_action } variables {M R} variables [mul_semiring_action M R] @[simp] lemma smul_X (m : M) : (m • X : polynomial R) = X := (smul_eq_map R m).symm ▸ map_X _ variables (S : Type*) [comm_semiring S] [mul_semiring_action M S] theorem smul_eval_smul (m : M) (f : polynomial S) (x : S) : (m • f).eval (m • x) = m • f.eval x := polynomial.induction_on f (λ r, by rw [smul_C, eval_C, eval_C]) (λ f g ihf ihg, by rw [smul_add, eval_add, ihf, ihg, eval_add, smul_add]) (λ n r ih, by rw [smul_mul', smul_pow, smul_C, smul_X, eval_mul, eval_C, eval_pow, eval_X, eval_mul, eval_C, eval_pow, eval_X, smul_mul', smul_pow]) variables (G : Type*) [group G] theorem eval_smul' [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : f.eval (g • x) = g • (g⁻¹ • f).eval x := by rw [← smul_eval_smul, smul_inv_smul] theorem smul_eval [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : (g • f).eval x = g • f.eval (g⁻¹ • x) := by rw [← smul_eval_smul, smul_inv_smul] end polynomial section comm_ring variables (G : Type*) [group G] [fintype G] variables (R : Type*) [comm_ring R] [mul_semiring_action G R] open mul_action open_locale classical /-- the product of `(X - g • x)` over distinct `g • x`. -/ noncomputable def prod_X_sub_smul (x : R) : polynomial R := (finset.univ : finset (quotient_group.quotient $ mul_action.stabilizer G x)).prod $ λ g, polynomial.X - polynomial.C (of_quotient_stabilizer G x g) theorem prod_X_sub_smul.monic (x : R) : (prod_X_sub_smul G R x).monic := polynomial.monic_prod_of_monic _ _ $ λ g _, polynomial.monic_X_sub_C _ theorem prod_X_sub_smul.eval (x : R) : (prod_X_sub_smul G R x).eval x = 0 := (monoid_hom.map_prod ((polynomial.aeval x).to_ring_hom.to_monoid_hom : polynomial R →* R) _ _).trans $ finset.prod_eq_zero (finset.mem_univ $ quotient_group.mk 1) $ by simp theorem prod_X_sub_smul.smul (x : R) (g : G) : g • prod_X_sub_smul G R x = prod_X_sub_smul G R x := (smul_prod _ _ _ _ _).trans $ fintype.prod_bijective _ (mul_action.bijective g) _ _ (λ g', by rw [of_quotient_stabilizer_smul, smul_sub, polynomial.smul_X, polynomial.smul_C]) theorem prod_X_sub_smul.coeff (x : R) (g : G) (n : ℕ) : g • (prod_X_sub_smul G R x).coeff n = (prod_X_sub_smul G R x).coeff n := by rw [← polynomial.coeff_smul, prod_X_sub_smul.smul] end comm_ring namespace mul_semiring_action_hom variables {M} variables {P : Type*} [comm_semiring P] [mul_semiring_action M P] variables {Q : Type*} [comm_semiring Q] [mul_semiring_action M Q] open polynomial /-- An equivariant map induces an equivariant map on polynomials. -/ protected noncomputable def polynomial (g : P →+*[M] Q) : polynomial P →+*[M] polynomial Q := { to_fun := map g, map_smul' := λ m p, polynomial.induction_on p (λ b, by rw [smul_C, map_C, coe_fn_coe, g.map_smul, map_C, coe_fn_coe, smul_C]) (λ p q ihp ihq, by rw [smul_add, polynomial.map_add, ihp, ihq, polynomial.map_add, smul_add]) (λ n b ih, by rw [smul_mul', smul_C, smul_pow, smul_X, polynomial.map_mul, map_C, polynomial.map_pow, map_X, coe_fn_coe, g.map_smul, polynomial.map_mul, map_C, polynomial.map_pow, map_X, smul_mul', smul_C, smul_pow, smul_X, coe_fn_coe]), map_zero' := polynomial.map_zero g, map_add' := λ p q, polynomial.map_add g, map_one' := polynomial.map_one g, map_mul' := λ p q, polynomial.map_mul g } @[simp] theorem coe_polynomial (g : P →+*[M] Q) : (g.polynomial : polynomial P → polynomial Q) = map g := rfl end mul_semiring_action_hom
6669a3b3ac54f0c3076cb84948ddf414a40d545c
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/field.lean
6744a40f7a97f52d2f03582b9b07c898994b912c
[ "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
9,427
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring.basic import algebra.group_with_zero open set set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true universe u variables {α : Type u} /-- A `division_ring` is a `ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor ring has_inv] class division_ring (α : Type u) extends ring α, has_inv α, nontrivial α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) (inv_zero : (0 : α)⁻¹ = 0) section division_ring variables [division_ring α] {a b : α} instance division_ring_has_div : has_div α := ⟨λ a b, a * b⁻¹⟩ /-- Every division ring is a `group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero α := { .. ‹division_ring α›, .. (infer_instance : semiring α) } @[field_simps] lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel @[field_simps] lemma mul_div_assoc' (a b c : α) : a * (b / c) = (a * b) / c := by simp [mul_div_assoc] lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div (a b : α) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b * a⁻¹) : by rw inv_eq_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] @[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma div_neg (a : α) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] instance division_ring.to_domain : domain α := { ..‹division_ring α›, ..(by apply_instance : semiring α), ..(by apply_instance : no_zero_divisors α) } end division_ring /-- A `field` is a `comm_ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor division_ring comm_ring] class field (α : Type u) extends comm_ring α, has_inv α, nontrivial α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : α)⁻¹ = 0) section field variable [field α] instance field.to_division_ring : division_ring α := { inv_mul_cancel := λ _ h, by rw [mul_comm, field.mul_inv_cancel h] ..show field α, by apply_instance } /-- Every field is a `comm_group_with_zero`. -/ instance field.to_comm_group_with_zero : comm_group_with_zero α := { .. (_ : group_with_zero α), .. ‹field α› } lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [add_comm, ← div_mul_left ha, ← div_mul_right _ hb, division_def, division_def, division_def, ← right_distrib, mul_comm a] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] @[field_simps] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : α) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : α) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain : integral_domain α := { ..‹field α›, ..division_ring.to_domain } end field section is_field /-- A predicate to express that a ring is a field. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. Additionaly, this is useful when trying to prove that a particular ring structure extends to a field. -/ structure is_field (R : Type u) [ring R] : Prop := (exists_pair_ne : ∃ (x y : R), x ≠ y) (mul_comm : ∀ (x y : R), x * y = y * x) (mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1) /-- Transferring from field to is_field -/ lemma field.to_is_field (R : Type u) [field R] : is_field R := { mul_inv_cancel := λ a ha, ⟨a⁻¹, field.mul_inv_cancel ha⟩, ..‹field R› } open_locale classical /-- Transferring from is_field to field -/ noncomputable def is_field.to_field (R : Type u) [ring R] (h : is_field R) : field R := { inv := λ a, if ha : a = 0 then 0 else classical.some (is_field.mul_inv_cancel h ha), inv_zero := dif_pos rfl, mul_inv_cancel := λ a ha, begin convert classical.some_spec (is_field.mul_inv_cancel h ha), exact dif_neg ha end, .. ‹ring R›, ..h } /-- For each field, and for each nonzero element of said field, there is a unique inverse. Since `is_field` doesn't remember the data of an `inv` function and as such, a lemma that there is a unique inverse could be useful. -/ lemma uniq_inv_of_is_field (R : Type u) [ring R] (hf : is_field R) : ∀ (x : R), x ≠ 0 → ∃! (y : R), x * y = 1 := begin intros x hx, apply exists_unique_of_exists_of_unique, { exact hf.mul_inv_cancel hx }, { intros y z hxy hxz, calc y = y * (x * z) : by rw [hxz, mul_one] ... = (x * y) * z : by rw [← mul_assoc, hf.mul_comm y x] ... = z : by rw [hxy, one_mul] } end end is_field namespace ring_hom section variables {R K : Type*} [semiring R] [division_ring K] (f : R →+* K) @[simp] lemma map_units_inv (u : units R) : f ↑u⁻¹ = (f ↑u)⁻¹ := (f : R →* K).map_units_inv u end section variables {β γ : Type*} [division_ring α] [semiring β] [nontrivial β] [division_ring γ] (f : α →+* β) (g : α →+* γ) {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := (f : α →* β).map_ne_zero f.map_zero lemma map_eq_zero : f x = 0 ↔ x = 0 := (f : α →* β).map_eq_zero f.map_zero variables (x y) lemma map_inv : g x⁻¹ = (g x)⁻¹ := (g : α →* γ).map_inv' g.map_zero x lemma map_div : g (x / y) = g x / g y := (g : α →* γ).map_div g.map_zero x y protected lemma injective : function.injective f := f.injective_iff.2 $ λ x, f.map_eq_zero.1 end end ring_hom
f85ce504df5c6f0e168e698e61c476f5a8dbf5fe
306b89478da7f3c210fecd6f66472a644e896eff
/src/solutions/00_first_proofs.lean
b167be3a331b1c70bb4e555032cddf33814c4029
[ "Apache-2.0" ]
permissive
sinhp/tutorials
a671990270a3bcb3f2c7a8869bbd425e7085672f
2cd093d5901b848e708f07b8fe450f108eb928c6
refs/heads/master
1,684,060,380,201
1,623,025,767,000
1,623,025,767,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,051
lean
/- This file is intended for Lean beginners. The goal is to demonstrate what it feels like to prove things using Lean and mathlib. Complicated definitions and theory building are not covered. Everything is covered again more slowly and with exercises in the next files. -/ -- We want real numbers and their basic properties import data.real.basic -- We want to be able to use Lean's built-in "help" functionality import tactic.suggest -- We want to be able to define functions using the law of excluded middle noncomputable theory open_locale classical /- Our first goal is to define the set of upper bounds of a set of real numbers. This is already defined in mathlib (in a more general context), but we repeat it for the sake of exposition. Right-click "upper_bounds" below to get offered to jump to mathlib's version -/ #check upper_bounds /-- The set of upper bounds of a set of real numbers ℝ -/ def up_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, a ≤ x} /-- Predicate `is_max a A` means `a` is a maximum of `A` -/ def is_max (a : ℝ) (A : set ℝ) := a ∈ A ∧ a ∈ up_bounds A /- In the above definition, the symbol `∧` means "and". We also see the most visible difference between set theoretic foundations and type theoretic ones (used by almost all proof assistants). In set theory, everything is a set, and the only relation you get from foundations are `=` and `∈`. In type theory, there is a meta-theoretic relation of "typing": `a : ℝ` reads "`a` is a real number" or, more precisely, "the type of `a` is `ℝ`". Here "meta-theoretic" means this is not a statement you can prove or disprove inside the theory, it's a fact that is true or not. Here we impose this fact, in other circumstances, it would be checked by the Lean kernel. By contrast, `a ∈ A` is a statement inside the theory. Here it's part of the definition, in other circumstances it could be something proven inside Lean. -/ /- For illustrative purposes, we now define an infix version of the above predicate. It will allow us to write `a is_a_max_of A`, which is closer to a sentence. -/ infix ` is_a_max_of `:55 := is_max /- Let's prove something now! A set of real numbers has at most one maximum. Here everything left of the final `:` is introducing the objects and assumption. The equality `x = y` right of the colon is the conclusion. -/ lemma unique_max (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := begin -- We first break our assumptions in their two constituent pieces. -- We are free to choose the name following `with` cases hx with x_in x_up, cases hy with y_in y_up, -- Assumption `x_up` means x isn't less than elements of A, let's apply this to y specialize x_up y, -- Assumption `x_up` now needs the information that `y` is indeed in `A`. specialize x_up y_in, -- Let's do this quicker with roles swapped specialize y_up x x_in, -- We explained to Lean the idea of this proof. -- Now we know `x ≤ y` and `y ≤ x`, and Lean shouldn't need more help. -- `linarith` proves equalities and inequalities that follow linearly from -- the assumption we have. linarith, end /- The above proof is too long, even if you remove comments. We don't really need the unpacking steps at the beginning; we can access both parts of the assumption `hx : x is_a_max_of A` using shortcuts `h.1` and `h.2`. We can also improve readability without assistance from the tactic state display, clearly announcing intermediate goals using `have`. This way we get to the following version of the same proof. -/ example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := begin have : x ≤ y, from hy.2 x hx.1, have : y ≤ x, from hx.2 y hy.1, linarith, end /- Notice how mathematics based on type theory treats the assumption `∀ a ∈ A, a ≤ y` as a function turning an element `a` of `A` into the statement `a ≤ y`. More precisely, this assumption is the abbreviation of `∀ a : ℝ, a ∈ A → a ≤ y`. The expression `hy.2 x` appearing in the above proof is then the statement `x ∈ A → x ≤ y`, which itself is a function turning a statement `x ∈ A` into `x ≤ y` so that the full expression `hy.2 x hx.1` is indeed a proof of `x ≤ y`. One could argue a three-line-long proof of this lemma is still two lines too long. This is debatable, but mathlib's style is to write very short proofs for trivial lemmas. Those proofs are not easy to read but they are meant to indicate that the proof is probably not worth reading. In order to reach this stage, we need to know what `linarith` did for us. It invoked the lemma `le_antisymm` which says: `x ≤ y → y ≤ x → x = y`. This arrow, which is used both for function and implication, is right associative. So the statement is `x ≤ y → (y ≤ x → x = y)` which reads: I will send a proof `p` of `x ≤ y` to a function sending a proof `q'` of `y ≤ x` to a proof of `x = y`. Hence `le_antisymm p q'` is a proof of `x = y`. Using this we can get our one-line proof: -/ example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := le_antisymm (hy.2 x hx.1) (hx.2 y hy.1) /- Such a proof is called a proof term (or a "term mode" proof). Notice it has no `begin` and `end`. It is directly the kind of low level proof that the Lean kernel is consuming. Commands like `cases`, `specialize` or `linarith` are called tactics, they help users constructing proof terms that could be very tedious to write directly. The most efficient proof style combines tactics with proof terms like our previous `have : x ≤ y, from hy.2 x hx.1` where `hy.2 x hx.1` is a proof term embeded inside a tactic mode proof. In the remaining of this file, we'll be characterizing infima of sets of real numbers in term of sequences. -/ /-- The set of lower bounds of a set of real numbers ℝ -/ def low_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, x ≤ a} /- We now define `a` is an infimum of `A`. Again there is already a more general version in mathlib. -/ def is_inf (x : ℝ) (A : set ℝ) := x is_a_max_of (low_bounds A) infix ` is_an_inf_of `:55 := is_inf /- We need to prove that any number which is greater than the infimum of A is greater than some element of A. -/ lemma inf_lt {A : set ℝ} {x : ℝ} (hx : x is_an_inf_of A) : ∀ y, x < y → ∃ a ∈ A, a < y := begin -- Let `y` be any real number. intro y, -- Let's prove the contrapositive contrapose, -- The symbol `¬` means negation. Let's ask Lean to rewrite the goal without negation, -- pushing negation through quantifiers and inequalities push_neg, -- Let's assume the premise, calling the assumption `h` intro h, -- `h` is exactly saying `y` is a lower bound of `A` so the second part of -- the infimum assumption `hx` applied to `y` and `h` is exactly what we want. exact hx.2 y h end /- In the above proof, the sequence `contrapose, push_neg` is so common that it can be abbreviated to `contrapose!`. With these commands, we enter the gray zone between proof checking and proof finding. Practical computer proof checking crucially needs the computer to handle tedious proof steps. In the next proof, we'll start using `linarith` a bit more seriously, going one step further into automation. Our next real goal is to prove inequalities for limits of sequences. We extract the following lemma: if `y ≤ x + ε` for all positive `ε` then `y ≤ x`. -/ lemma le_of_le_add_eps {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin -- Let's prove the contrapositive, asking Lean to push negations right away. contrapose!, -- Assume `h : x < y`. intro h, -- We need to find `ε` such that `ε` is positive and `x + ε < y`. -- Let's use `(y-x)/2` use ((y-x)/2), -- we now have two properties to prove. Let's do both in turn, using `linarith` split, linarith, linarith, end /- Note how `linarith` was used for both sub-goals at the end of the above proof. We could have shortened that using the semi-colon combinator instead of comma, writing `split ; linarith`. Next we will study a compressed version of that proof: -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin contrapose!, exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩, end /- The angle brackets `⟨` and `⟩` introduce compound data or proofs. A proof of a `∃ z, P z` statemement is composed of a witness `z₀` and a proof `h` of `P z₀`. The compound is denoted by `⟨z₀, h⟩`. In the example above, the predicate is itself compound, it is a conjunction `P z ∧ Q z`. So the proof term should read `⟨z₀, ⟨h₁, h₂⟩⟩` where `h₁` (resp. `h₂`) is a proof of `P z₀` (resp. `Q z₀`). But these so-called "anonymous constructor" brackets are right-associative, so we can get rid of the nested brackets. The keyword `by` introduces tactic mode inside term mode, it is a shorter version of the `begin`/`end` pair, which is more convenient for single tactic blocks. In this example, `begin` enters tactic mode, `exact` leaves it, `by` re-enters it. Going all the way to a proof term would make the proof much longer, because we crucially use automation with `contrapose!` and `linarith`. We can still get a one-line proof using curly braces to gather several tactic invocations, and the `by` abbreviation instead of `begin`/`end`: -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := by { contrapose!, exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩ } /- One could argue that the above proof is a bit too terse, and we are relying too much on linarith. Let's have more `linarith` calls for smaller steps. For the sake of (tiny) variation, we will also assume the premise and argue by contradiction instead of contraposing. -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin intro h, -- Assume the conclusion is false, and call this assumption H. by_contradiction H, push_neg at H, -- Now let's compute. have key := calc -- Each line must end with a colon followed by a proof term -- We want to specialize our assumption `h` to `ε = (y-x)/2` but this is long to -- type, so let's put a hole `_` that Lean will fill in by comparing the -- statement we want to prove and our proof term with a hole. As usual, -- positivity of `(y-x)/2` is proved by `linarith` y ≤ x + (y-x)/2 : h _ (by linarith) ... = x/2 + y/2 : by ring ... < y : by linarith, -- our key now says `y < y` (notice how the sequence `≤`, `=`, `<` was correctly -- merged into a `<`). Let `linarith` find the desired contradiction now. linarith, -- alternatively, we could have provided the proof term -- `exact lt_irrefl y key` end /- Now we are ready for some analysis. Let's set up notation for absolute value -/ local notation `|`x`|` := abs x /- And let's define convergence of sequences of real numbers (of course there is a much more general definition in mathlib). -/ /-- The sequence `u` tends to `l` -/ def limit (u : ℕ → ℝ) (l : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε /- In the above definition, `u n` denotes the n-th term of the sequence. We can add parentheses to get `u(n)` but we try to avoid parentheses because they pile up very quickly -/ -- If y ≤ u n for all n and u n goes to x then y ≤ x lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : limit u x) (ineq : ∀ n, y ≤ u n) : y ≤ x := begin -- Let's apply our previous lemma apply le_of_le_add_eps, -- We need to prove y ≤ x + ε for all positive ε. -- Let ε be any positive real intros ε ε_pos, -- we now specialize our limit assumption to this `ε`, and immediately -- fix a `N` as promised by the definition. cases hu ε ε_pos with N HN, -- Now we only need to compute until reaching the conclusion calc y ≤ u N : ineq N ... = x + (u N - x) : by linarith -- We'll need `add_le_add` which says `a ≤ b` and `c ≤ d` implies `a + c ≤ b + d` -- We need a lemma saying `z ≤ |z|`. Because we don't know the name of this lemma, -- let's use `library_search`. Because searching thourgh the library is slow, -- Lean will write what it found in the Lean message window when cursor is on -- that line, so that we can replace it by the lemma. We see `le_abs_self`, which -- says `a ≤ |a|`, exactly what we're looking for. ... ≤ x + |u N - x| : add_le_add (by linarith) (by library_search) ... ≤ x + ε : add_le_add (by linarith) (HN N (by linarith)), end /- The next lemma has been extracted from the main proof in order to discuss numbers. In ordinary maths, we know that ℕ is *not* contained in `ℝ`, whatever the construction of real numbers that we use. For instance a natural number is not an equivalence class of Cauchy sequences. But it's very easy to pretend otherwise. Formal maths requires slightly more care. In the statement below, the "type ascription" `(n + 1 : ℝ)` forces Lean to convert the natural number `n+1` into a real number. The "inclusion" map will be displayed in tactic state as `↑`. There are various lemmas asserting this map is compatible with addition and monotone, but we don't want to bother writing their names. The `norm_cast` tactic is designed to wisely apply those lemmas for us. -/ lemma inv_succ_pos : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 := begin -- Let `n` be any integer intro n, -- Since we don't know the name of the relevant lemma, asserting that the inverse of -- a positive number is positive, let's state that is suffices -- to prove that `n+1`, seen as a real number, is positive, and ask `library_search` suffices : (n + 1 : ℝ) > 0, { library_search }, -- Now we want to reduce to a statement about natural numbers, not real numbers -- coming from natural numbers. norm_cast, -- and then get the usual help from `linarith` linarith, end /- That was a pretty long proof for an obvious fact. And stating it as a lemma feels stupid, so let's find a way to write it on one line in case we want to include it in some other proof without stating a lemma. First the `library_search` call above displays the name of the relevant lemma: `one_div_pos`. We can also replace the `linarith` call on the last line by `library_search` to learn the name of the lemma `nat.succ_pos` asserting that the successor of a natural number is positive. There is also a variant on `norm_cast` that combines it with `exact`. The term mode analogue of `intro` is `λ`. We get down to: -/ example : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 := λ n, one_div_pos.mpr (by exact_mod_cast nat.succ_pos n) /- The next proof uses mostly known things, so we will commment only new aspects. -/ lemma limit_inv_succ : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε := begin intros ε ε_pos, suffices : ∃ N : ℕ, 1/ε ≤ N, { -- Because we didn't provide a name for the above statement, Lean called it `this`. -- Let's fix an `N` that works. cases this with N HN, use N, intros n Hn, -- Now we want to rewrite the goal using lemmas -- `div_le_iff' : 0 < b → (a / b ≤ c ↔ a ≤ b * c)` -- `div_le_iff : 0 < b → (a / b ≤ c ↔ a ≤ c * b)` -- the second one will be rewritten from right to left, as indicated by `←`. -- Lean will create a side goal for the required positivity assumption that -- we don't provide for `div_le_iff'`. rw [div_le_iff', ← div_le_iff ε_pos], -- We want to replace assumption `Hn` by its real counter-part so that -- linarith can find what it needs. replace Hn : (N : ℝ) ≤ n, exact_mod_cast Hn, linarith, -- we are still left with the positivity assumption, but already discussed -- how to prove it in the preceding lemma exact_mod_cast nat.succ_pos n }, -- Now we need to prove that sufficient statement. -- We want to use that `ℝ` is archimedean. So we start typing -- `exact archimedean_` and hit Ctrl-space to see what completion Lean proposes -- the lemma `archimedean_iff_nat_le` sounds promising. We select the left to -- right implication using `.1`. This a generic lemma for fields equiped with -- a linear (ie total) order. We need to provide a proof that `ℝ` is indeed -- archimedean. This is done using the `apply_instance` tactic that will be -- covered elsewhere. exact archimedean_iff_nat_le.1 (by apply_instance) (1/ε), end /- We can now put all pieces together, with almost no new things to explain. -/ lemma inf_seq (A : set ℝ) (x : ℝ) : (x is_an_inf_of A) ↔ (x ∈ low_bounds A ∧ ∃ u : ℕ → ℝ, limit u x ∧ ∀ n, u n ∈ A ) := begin split, { intro h, split, { exact h.1 }, -- On the next line, we don't need to tell Lean to treat `n+1` as a real number because -- we add `x` to it, so Lean knows there is only one way to make sense of this expression. have key : ∀ n : ℕ, ∃ a ∈ A, a < x + 1/(n+1), { intro n, -- we can use the lemma we proved above apply inf_lt h, -- and another one we proved! have : 0 < 1/(n+1 : ℝ), from inv_succ_pos n, linarith }, -- Now we need to use axiom of (countable) choice choose u hu using key, use u, split, { intros ε ε_pos, -- again we use a lemma we proved, specializing it to our fixed `ε`, and fixing a `N` cases limit_inv_succ ε ε_pos with N H, use N, intros n hn, have : x ≤ u n, from h.1 _ (hu n).1, have := calc u n < x + 1/(n + 1) : (hu n).2 ... ≤ x + ε : add_le_add (le_refl x) (H n hn), rw abs_of_nonneg ; linarith }, { intro n, exact (hu n).1 } }, { intro h, -- Assumption `h` is made of nested compound statements. We can use the -- recursive version of `cases` to unpack it in one go. rcases h with ⟨x_min, u, lim, huA⟩, split, exact x_min, intros y y_mino, apply le_lim lim, intro n, exact y_mino (u n) (huA n) }, end
a70006ac25d95e8d8372dc8f355841b5b7e63be3
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/init/types.hlean
bac36fc19b040192a1cdae7d423e9fe87446fe1a
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
2,245
hlean
/- Copyright (c) 2014-2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn, Jakob von Raumer -/ prelude import init.num init.relation open iff -- Empty type -- ---------- protected definition empty.has_decidable_eq [instance] : decidable_eq empty := take (a b : empty), decidable.inl (!empty.elim a) -- Unit type -- --------- namespace unit notation `⋆` := star end unit -- Sigma type -- ---------- notation `Σ` binders `, ` r:(scoped P, sigma P) := r abbreviation dpair [constructor] := @sigma.mk namespace sigma notation `⟨`:max t:(foldr `, ` (e r, mk e r)) `⟩`:0 := t --input ⟨ ⟩ as \< \> namespace ops postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 abbreviation pr₁ := @pr1 abbreviation pr₂ := @pr2 end ops end sigma -- Sum type -- -------- namespace sum namespace low_precedence_plus reserve infixr ` + `:25 -- conflicts with notation for addition infixr ` + ` := sum end low_precedence_plus variables {a b c d : Type} definition sum_of_sum_of_imp_of_imp (H₁ : a ⊎ b) (H₂ : a → c) (H₃ : b → d) : c ⊎ d := sum.rec_on H₁ (assume Ha : a, sum.inl (H₂ Ha)) (assume Hb : b, sum.inr (H₃ Hb)) definition sum_of_sum_of_imp_left (H₁ : a ⊎ c) (H : a → b) : b ⊎ c := sum.rec_on H₁ (assume H₂ : a, sum.inl (H H₂)) (assume H₂ : c, sum.inr H₂) definition sum_of_sum_of_imp_right (H₁ : c ⊎ a) (H : a → b) : c ⊎ b := sum.rec_on H₁ (assume H₂ : c, sum.inl H₂) (assume H₂ : a, sum.inr (H H₂)) end sum -- Product type -- ------------ namespace prod -- notation for n-ary tuples notation `(` h `, ` t:(foldl `,` (e r, prod.mk r e) h) `)` := t namespace ops postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 abbreviation pr₁ := @pr1 abbreviation pr₂ := @pr2 end ops namespace low_precedence_times reserve infixr ` * `:30 -- conflicts with notation for multiplication infixr ` * ` := prod end low_precedence_times open prod.ops definition flip [unfold 3] {A B : Type} (a : A × B) : B × A := pair (pr2 a) (pr1 a) end prod
cc8364761dbb8ffa1e53ffd99be608f26d07e805
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/set/intervals/disjoint.lean
f1109974c97636e5133ddf4bdfdd935460b581c3
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,881
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yury Kudryashov -/ import data.set.lattice /-! # Extra lemmas about intervals This file contains lemmas about intervals that cannot be included into `data.set.intervals.basic` because this would create an `import` cycle. Namely, lemmas in this file can use definitions from `data.set.lattice`, including `disjoint`. -/ universes u v w variables {ι : Sort u} {α : Type v} {β : Type w} open set order_dual (to_dual) namespace set section preorder variables [preorder α] {a b c : α} @[simp] lemma Iic_disjoint_Ioi (h : a ≤ b) : disjoint (Iic a) (Ioi b) := disjoint_left.mpr $ λ x ha hb, (h.trans_lt hb).not_le ha @[simp] lemma Iic_disjoint_Ioc (h : a ≤ b) : disjoint (Iic a) (Ioc b c) := (Iic_disjoint_Ioi h).mono le_rfl (λ _, and.left) @[simp] lemma Ioc_disjoint_Ioc_same {a b c : α} : disjoint (Ioc a b) (Ioc b c) := (Iic_disjoint_Ioc (le_refl b)).mono (λ _, and.right) le_rfl @[simp] lemma Ico_disjoint_Ico_same {a b c : α} : disjoint (Ico a b) (Ico b c) := disjoint_left.mpr $ λ x hab hbc, hab.2.not_le hbc.1 @[simp] lemma Ici_disjoint_Iic : disjoint (Ici a) (Iic b) ↔ ¬(a ≤ b) := by rw [set.disjoint_iff_inter_eq_empty, Ici_inter_Iic, Icc_eq_empty_iff] @[simp] lemma Iic_disjoint_Ici : disjoint (Iic a) (Ici b) ↔ ¬(b ≤ a) := disjoint.comm.trans Ici_disjoint_Iic @[simp] lemma Union_Iic : (⋃ a : α, Iic a) = univ := Union_eq_univ_iff.2 $ λ x, ⟨x, right_mem_Iic⟩ @[simp] lemma Union_Ici : (⋃ a : α, Ici a) = univ := Union_eq_univ_iff.2 $ λ x, ⟨x, left_mem_Ici⟩ @[simp] lemma Union_Icc_right (a : α) : (⋃ b, Icc a b) = Ici a := by simp only [← Ici_inter_Iic, ← inter_Union, Union_Iic, inter_univ] @[simp] lemma Union_Ioc_right (a : α) : (⋃ b, Ioc a b) = Ioi a := by simp only [← Ioi_inter_Iic, ← inter_Union, Union_Iic, inter_univ] @[simp] lemma Union_Icc_left (b : α) : (⋃ a, Icc a b) = Iic b := by simp only [← Ici_inter_Iic, ← Union_inter, Union_Ici, univ_inter] @[simp] lemma Union_Ico_left (b : α) : (⋃ a, Ico a b) = Iio b := by simp only [← Ici_inter_Iio, ← Union_inter, Union_Ici, univ_inter] @[simp] lemma Union_Iio [no_max_order α] : (⋃ a : α, Iio a) = univ := Union_eq_univ_iff.2 exists_gt @[simp] lemma Union_Ioi [no_min_order α] : (⋃ a : α, Ioi a) = univ := Union_eq_univ_iff.2 exists_lt @[simp] lemma Union_Ico_right [no_max_order α] (a : α) : (⋃ b, Ico a b) = Ici a := by simp only [← Ici_inter_Iio, ← inter_Union, Union_Iio, inter_univ] @[simp] lemma Union_Ioo_right [no_max_order α] (a : α) : (⋃ b, Ioo a b) = Ioi a := by simp only [← Ioi_inter_Iio, ← inter_Union, Union_Iio, inter_univ] @[simp] lemma Union_Ioc_left [no_min_order α] (b : α) : (⋃ a, Ioc a b) = Iic b := by simp only [← Ioi_inter_Iic, ← Union_inter, Union_Ioi, univ_inter] @[simp] lemma Union_Ioo_left [no_min_order α] (b : α) : (⋃ a, Ioo a b) = Iio b := by simp only [← Ioi_inter_Iio, ← Union_inter, Union_Ioi, univ_inter] end preorder section linear_order variables [linear_order α] {a₁ a₂ b₁ b₂ : α} @[simp] lemma Ico_disjoint_Ico : disjoint (Ico a₁ a₂) (Ico b₁ b₂) ↔ min a₂ b₂ ≤ max a₁ b₁ := by simp_rw [set.disjoint_iff_inter_eq_empty, Ico_inter_Ico, Ico_eq_empty_iff, inf_eq_min, sup_eq_max, not_lt] @[simp] lemma Ioc_disjoint_Ioc : disjoint (Ioc a₁ a₂) (Ioc b₁ b₂) ↔ min a₂ b₂ ≤ max a₁ b₁ := have h : _ ↔ min (to_dual a₁) (to_dual b₁) ≤ max (to_dual a₂) (to_dual b₂) := Ico_disjoint_Ico, by simpa only [dual_Ico] using h /-- If two half-open intervals are disjoint and the endpoint of one lies in the other, then it must be equal to the endpoint of the other. -/ lemma eq_of_Ico_disjoint {x₁ x₂ y₁ y₂ : α} (h : disjoint (Ico x₁ x₂) (Ico y₁ y₂)) (hx : x₁ < x₂) (h2 : x₂ ∈ Ico y₁ y₂) : y₁ = x₂ := begin rw [Ico_disjoint_Ico, min_eq_left (le_of_lt h2.2), le_max_iff] at h, apply le_antisymm h2.1, exact h.elim (λ h, absurd hx (not_lt_of_le h)) id end @[simp] lemma Union_Ico_eq_Iio_self_iff {f : ι → α} {a : α} : (⋃ i, Ico (f i) a) = Iio a ↔ ∀ x < a, ∃ i, f i ≤ x := by simp [← Ici_inter_Iio, ← Union_inter, subset_def] @[simp] lemma Union_Ioc_eq_Ioi_self_iff {f : ι → α} {a : α} : (⋃ i, Ioc a (f i)) = Ioi a ↔ ∀ x, a < x → ∃ i, x ≤ f i := by simp [← Ioi_inter_Iic, ← inter_Union, subset_def] @[simp] lemma bUnion_Ico_eq_Iio_self_iff {p : ι → Prop} {f : Π i, p i → α} {a : α} : (⋃ i (hi : p i), Ico (f i hi) a) = Iio a ↔ ∀ x < a, ∃ i hi, f i hi ≤ x := by simp [← Ici_inter_Iio, ← Union_inter, subset_def] @[simp] lemma bUnion_Ioc_eq_Ioi_self_iff {p : ι → Prop} {f : Π i, p i → α} {a : α} : (⋃ i (hi : p i), Ioc a (f i hi)) = Ioi a ↔ ∀ x, a < x → ∃ i hi, x ≤ f i hi := by simp [← Ioi_inter_Iic, ← inter_Union, subset_def] end linear_order end set section Union_Ixx variables [linear_order α] {s : set α} {a : α} {f : ι → α} lemma is_glb.bUnion_Ioi_eq (h : is_glb s a) : (⋃ x ∈ s, Ioi x) = Ioi a := begin refine (Union₂_subset $ λ x hx, _).antisymm (λ x hx, _), { exact Ioi_subset_Ioi (h.1 hx) }, { rcases h.exists_between hx with ⟨y, hys, hay, hyx⟩, exact mem_bUnion hys hyx } end lemma is_glb.Union_Ioi_eq (h : is_glb (range f) a) : (⋃ x, Ioi (f x)) = Ioi a := bUnion_range.symm.trans h.bUnion_Ioi_eq lemma is_lub.bUnion_Iio_eq (h : is_lub s a) : (⋃ x ∈ s, Iio x) = Iio a := h.dual.bUnion_Ioi_eq lemma is_lub.Union_Iio_eq (h : is_lub (range f) a) : (⋃ x, Iio (f x)) = Iio a := h.dual.Union_Ioi_eq lemma is_glb.bUnion_Ici_eq_Ioi (a_glb : is_glb s a) (a_not_mem : a ∉ s) : (⋃ x ∈ s, Ici x) = Ioi a := begin refine (Union₂_subset $ λ x hx, _).antisymm (λ x hx, _), { exact Ici_subset_Ioi.mpr (lt_of_le_of_ne (a_glb.1 hx) (λ h, (h ▸ a_not_mem) hx)), }, { rcases a_glb.exists_between hx with ⟨y, hys, hay, hyx⟩, apply mem_Union₂.mpr , refine ⟨y, hys, hyx.le⟩, }, end lemma is_glb.bUnion_Ici_eq_Ici (a_glb : is_glb s a) (a_mem : a ∈ s) : (⋃ x ∈ s, Ici x) = Ici a := begin refine (Union₂_subset $ λ x hx, _).antisymm (λ x hx, _), { exact Ici_subset_Ici.mpr (mem_lower_bounds.mp a_glb.1 x hx), }, { apply mem_Union₂.mpr, refine ⟨a, a_mem, hx⟩, }, end lemma is_lub.bUnion_Iic_eq_Iio (a_lub : is_lub s a) (a_not_mem : a ∉ s) : (⋃ x ∈ s, Iic x) = Iio a := a_lub.dual.bUnion_Ici_eq_Ioi a_not_mem lemma is_lub.bUnion_Iic_eq_Iic (a_lub : is_lub s a) (a_mem : a ∈ s) : (⋃ x ∈ s, Iic x) = Iic a := a_lub.dual.bUnion_Ici_eq_Ici a_mem lemma Union_Ici_eq_Ioi_infi {R : Type*} [complete_linear_order R] {f : ι → R} (no_least_elem : (⨅ i, f i) ∉ range f) : (⋃ (i : ι), Ici (f i)) = Ioi (⨅ i, f i) := by simp only [← is_glb.bUnion_Ici_eq_Ioi (@is_glb_infi _ _ _ f) no_least_elem, mem_range, Union_exists, Union_Union_eq'] lemma Union_Iic_eq_Iio_supr {R : Type*} [complete_linear_order R] {f : ι → R} (no_greatest_elem : (⨆ i, f i) ∉ range f) : (⋃ (i : ι), Iic (f i)) = Iio (⨆ i, f i) := @Union_Ici_eq_Ioi_infi ι (order_dual R) _ f no_greatest_elem lemma Union_Ici_eq_Ici_infi {R : Type*} [complete_linear_order R] {f : ι → R} (has_least_elem : (⨅ i, f i) ∈ range f) : (⋃ (i : ι), Ici (f i)) = Ici (⨅ i, f i) := by simp only [← is_glb.bUnion_Ici_eq_Ici (@is_glb_infi _ _ _ f) has_least_elem, mem_range, Union_exists, Union_Union_eq'] lemma Union_Iic_eq_Iic_supr {R : Type*} [complete_linear_order R] {f : ι → R} (has_greatest_elem : (⨆ i, f i) ∈ range f) : (⋃ (i : ι), Iic (f i)) = Iic (⨆ i, f i) := @Union_Ici_eq_Ici_infi ι (order_dual R) _ f has_greatest_elem end Union_Ixx
e36469a637a2657c34b6d842354361a960f4937f
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Meta/Message.lean
5f64115aa75ef4559cb12494deacda6bfc8a4fbb
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,706
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.Basic namespace Lean namespace Meta namespace Exception private def run? {α} (ctx : ExceptionContext) (x : MetaM α) : Option α := match x { lctx := ctx.lctx, currRecDepth := 0, maxRecDepth := getMaxRecDepth ctx.opts } { env := ctx.env, mctx := ctx.mctx, ngen := { namePrefix := `_meta_exception } } with | EStateM.Result.ok a _ => some a | EStateM.Result.error _ _ => none private def inferType? (ctx : ExceptionContext) (e : Expr) : Option Expr := run? ctx (inferType e) private def inferDomain? (ctx : ExceptionContext) (f : Expr) : Option Expr := run? ctx $ do fType ← inferType f; fType ← whnf fType; match fType with | Expr.forallE _ d _ _ => pure d | _ => throw $ Exception.other "unexpected" private def whnf? (ctx : ExceptionContext) (e : Expr) : Option Expr := run? ctx (whnf e) def mkAppTypeMismatchMessage (f a : Expr) (ctx : ExceptionContext) : MessageData := mkCtx ctx $ let e := mkApp f a; match inferType? ctx a, inferDomain? ctx f with | some aType, some expectedType => "application type mismatch" ++ indentExpr e ++ Format.line ++ "argument" ++ indentExpr a ++ Format.line ++ "has type" ++ indentExpr aType ++ Format.line ++ "but is expected to have type" ++ indentExpr expectedType | _, _ => "application type mismatch" ++ indentExpr e def mkLetTypeMismatchMessage (fvarId : FVarId) (ctx : ExceptionContext) : MessageData := mkCtx ctx $ match ctx.lctx.find? fvarId with | some (LocalDecl.ldecl _ n t v b) => match inferType? ctx v with | some vType => "invalid let declaration, term" ++ indentExpr v ++ Format.line ++ "has type " ++ indentExpr vType ++ Format.line ++ "but is expected to have type" ++ indentExpr t | none => "type mismatch at let declaration for " ++ n | _ => unreachable! /-- Convert to `MessageData` that is supposed to be displayed in user-friendly error messages. -/ def toMessageData : Exception → MessageData | unknownConst c ctx => mkCtx ctx $ "unknown constant " ++ c | unknownFVar fvarId ctx => mkCtx ctx $ "unknown free variable " ++ fvarId | unknownExprMVar mvarId ctx => mkCtx ctx $ "unknown metavariable " ++ mvarId | unknownLevelMVar mvarId ctx => mkCtx ctx $ "unknown universe level metavariable " ++ mvarId | unexpectedBVar bvarIdx => "unexpected bound variable " ++ mkBVar bvarIdx | functionExpected f a ctx => mkCtx ctx $ "function expected " ++ mkApp f a | typeExpected t ctx => mkCtx ctx $ "type expected " ++ t | incorrectNumOfLevels c lvls ctx => mkCtx ctx $ "incorrect number of universe levels " ++ mkConst c lvls | invalidProjection s i e ctx => mkCtx ctx $ "invalid projection" ++ indentExpr (mkProj s i e) | revertFailure xs decl ctx => mkCtx ctx $ "revert failure" | readOnlyMVar mvarId ctx => mkCtx ctx $ "tried to update read only metavariable " ++ mkMVar mvarId | isLevelDefEqStuck u v ctx => mkCtx ctx $ "stuck at universe level constraint " ++ u ++ " =?= " ++ v | isExprDefEqStuck t s ctx => mkCtx ctx $ "stuck at constraint " ++ t ++ " =?= " ++ s | letTypeMismatch fvarId ctx => mkLetTypeMismatchMessage fvarId ctx | appTypeMismatch f a ctx => mkAppTypeMismatchMessage f a ctx | notInstance i ctx => mkCtx ctx $ "not a type class instance " ++ i | appBuilder op msg args ctx => mkCtx ctx $ "application builder failure " ++ op ++ " " ++ args ++ " " ++ msg | synthInstance inst ctx => mkCtx ctx $ "failed to synthesize" ++ indentExpr inst | tactic tacName mvarId msg ctx => mkCtx ctx $ "tactic '" ++ tacName ++ "' failed, " ++ msg ++ Format.line ++ MessageData.ofGoal mvarId | generalizeTelescope es ctx => mkCtx ctx $ "failed to create telescope generalizing " ++ es | kernel ex opts => ex.toMessageData opts | bug _ _ => "internal bug" -- TODO improve | other s => s end Exception instance MetaHasEval {α} [MetaHasEval α] : MetaHasEval (MetaM α) := ⟨fun env opts x _ => do match x { config := { opts := opts }, currRecDepth := 0, maxRecDepth := getMaxRecDepth opts } { env := env } with | EStateM.Result.ok a s => do s.traceState.traces.forM $ fun m => IO.println $ format m; MetaHasEval.eval s.env opts a | EStateM.Result.error err s => do s.traceState.traces.forM $ fun m => IO.println $ format m; throw (IO.userError (toString (format err.toMessageData)))⟩ end Meta end Lean
09a5afff0575dcbb41d4922378033120044110e5
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/bernoulli.lean
9688587f8e26fb9b12c3a74472dde1775b1dd1e6
[ "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
16,851
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kevin Buzzard -/ import algebra.big_operators.nat_antidiagonal import algebra.geom_sum import data.fintype.card import ring_theory.power_series.well_known import tactic.field_simp /-! # Bernoulli numbers The Bernoulli numbers are a sequence of rational numbers that frequently show up in number theory. ## Mathematical overview The Bernoulli numbers $(B_0, B_1, B_2, \ldots)=(1, -1/2, 1/6, 0, -1/30, \ldots)$ are a sequence of rational numbers. They show up in the formula for the sums of $k$th powers. They are related to the Taylor series expansions of $x/\tan(x)$ and of $\coth(x)$, and also show up in the values that the Riemann Zeta function takes both at both negative and positive integers (and hence in the theory of modular forms). For example, if $1 \leq n$ is even then $$\zeta(2n)=\sum_{t\geq1}t^{-2n}=(-1)^{n+1}\frac{(2\pi)^{2n}B_{2n}}{2(2n)!}.$$ Note however that this result is not yet formalised in Lean. The Bernoulli numbers can be formally defined using the power series $$\sum B_n\frac{t^n}{n!}=\frac{t}{1-e^{-t}}$$ although that happens to not be the definition in mathlib (this is an *implementation detail* and need not concern the mathematician). Note that $B_1=-1/2$, meaning that we are using the $B_n^-$ of [from Wikipedia](https://en.wikipedia.org/wiki/Bernoulli_number). ## Implementation detail The Bernoulli numbers are defined using well-founded induction, by the formula $$B_n=1-\sum_{k\lt n}\frac{\binom{n}{k}}{n-k+1}B_k.$$ This formula is true for all $n$ and in particular $B_0=1$. Note that this is the definition for positive Bernoulli numbers, which we call `bernoulli'`. The negative Bernoulli numbers are then defined as `bernoulli := (-1)^n * bernoulli'`. ## Main theorems `sum_bernoulli : ∑ k in finset.range n, (n.choose k : ℚ) * bernoulli k = 0` -/ open_locale nat big_operators open finset nat finset.nat power_series variables (A : Type*) [comm_ring A] [algebra ℚ A] /-! ### Definitions -/ /-- The Bernoulli numbers: the $n$-th Bernoulli number $B_n$ is defined recursively via $$B_n = 1 - \sum_{k < n} \binom{n}{k}\frac{B_k}{n+1-k}$$ -/ def bernoulli' : ℕ → ℚ := well_founded.fix lt_wf $ λ n bernoulli', 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k k.2 lemma bernoulli'_def' (n : ℕ) : bernoulli' n = 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k := well_founded.fix_eq _ _ _ lemma bernoulli'_def (n : ℕ) : bernoulli' n = 1 - ∑ k in range n, n.choose k / (n - k + 1) * bernoulli' k := by { rw [bernoulli'_def', ← fin.sum_univ_eq_sum_range], refl } lemma bernoulli'_spec (n : ℕ) : ∑ k in range n.succ, (n.choose (n - k) : ℚ) / (n - k + 1) * bernoulli' k = 1 := begin rw [sum_range_succ_comm, bernoulli'_def n, tsub_self], conv in (n.choose (_ - _)) { rw choose_symm (mem_range.1 H).le }, simp only [one_mul, cast_one, sub_self, sub_add_cancel, choose_zero_right, zero_add, div_one], end lemma bernoulli'_spec' (n : ℕ) : ∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli' k.1 = 1 := begin refine ((sum_antidiagonal_eq_sum_range_succ_mk _ n).trans _).trans (bernoulli'_spec n), refine sum_congr rfl (λ x hx, _), simp only [add_tsub_cancel_of_le, mem_range_succ_iff.mp hx, cast_sub], end /-! ### Examples -/ section examples @[simp] lemma bernoulli'_zero : bernoulli' 0 = 1 := by { rw bernoulli'_def, norm_num } @[simp] lemma bernoulli'_one : bernoulli' 1 = 1/2 := by { rw bernoulli'_def, norm_num } @[simp] lemma bernoulli'_two : bernoulli' 2 = 1/6 := by { rw bernoulli'_def, norm_num [sum_range_succ] } @[simp] lemma bernoulli'_three : bernoulli' 3 = 0 := by { rw bernoulli'_def, norm_num [sum_range_succ] } @[simp] lemma bernoulli'_four : bernoulli' 4 = -1/30 := have nat.choose 4 2 = 6 := dec_trivial, -- shrug by { rw bernoulli'_def, norm_num [sum_range_succ, this] } end examples @[simp] lemma sum_bernoulli' (n : ℕ) : ∑ k in range n, (n.choose k : ℚ) * bernoulli' k = n := begin cases n, { simp }, suffices : (n + 1 : ℚ) * ∑ k in range n, ↑(n.choose k) / (n - k + 1) * bernoulli' k = ∑ x in range n, ↑(n.succ.choose x) * bernoulli' x, { rw_mod_cast [sum_range_succ, bernoulli'_def, ← this, choose_succ_self_right], ring }, simp_rw [mul_sum, ← mul_assoc], refine sum_congr rfl (λ k hk, _), congr', have : ((n - k : ℕ) : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero, field_simp [← cast_sub (mem_range.1 hk).le, mul_comm], rw_mod_cast [tsub_add_eq_add_tsub (mem_range.1 hk).le, choose_mul_succ_eq], end /-- The exponential generating function for the Bernoulli numbers `bernoulli' n`. -/ def bernoulli'_power_series := mk $ λ n, algebra_map ℚ A (bernoulli' n / n!) theorem bernoulli'_power_series_mul_exp_sub_one : bernoulli'_power_series A * (exp A - 1) = X * exp A := begin ext n, -- constant coefficient is a special case cases n, { simp }, rw [bernoulli'_power_series, coeff_mul, mul_comm X, sum_antidiagonal_succ'], suffices : ∑ p in antidiagonal n, (bernoulli' p.1 / p.1!) * ((p.2 + 1) * p.2!)⁻¹ = n!⁻¹, { simpa [ring_hom.map_sum] using congr_arg (algebra_map ℚ A) this }, apply eq_inv_of_mul_eq_one_left, rw sum_mul, convert bernoulli'_spec' n using 1, apply sum_congr rfl, simp_rw [mem_antidiagonal], rintro ⟨i, j⟩ rfl, have : (j + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero j, have : (j + 1 : ℚ) * j! * i! ≠ 0 := by simpa [factorial_ne_zero], have := factorial_mul_factorial_dvd_factorial_add i j, field_simp [mul_comm _ (bernoulli' i), mul_assoc, add_choose], rw_mod_cast [mul_comm (j + 1), mul_div_assoc, ← mul_assoc], rw [cast_mul, cast_mul, mul_div_mul_right, cast_div_char_zero, cast_mul], assumption, rwa nat.cast_succ, end /-- Odd Bernoulli numbers (greater than 1) are zero. -/ theorem bernoulli'_odd_eq_zero {n : ℕ} (h_odd : odd n) (hlt : 1 < n) : bernoulli' n = 0 := begin let B := mk (λ n, bernoulli' n / n!), suffices : (B - eval_neg_hom B) * (exp ℚ - 1) = X * (exp ℚ - 1), { cases mul_eq_mul_right_iff.mp this; simp only [power_series.ext_iff, eval_neg_hom, coeff_X] at h, { apply eq_zero_of_neg_eq, specialize h n, split_ifs at h; simp [h_odd.neg_one_pow, factorial_ne_zero, *] at * }, { simpa using h 1 } }, have h : B * (exp ℚ - 1) = X * exp ℚ, { simpa [bernoulli'_power_series] using bernoulli'_power_series_mul_exp_sub_one ℚ }, rw [sub_mul, h, mul_sub X, sub_right_inj, ← neg_sub, mul_neg, neg_eq_iff_neg_eq], suffices : eval_neg_hom (B * (exp ℚ - 1)) * exp ℚ = eval_neg_hom (X * exp ℚ) * exp ℚ, { simpa [mul_assoc, sub_mul, mul_comm (eval_neg_hom (exp ℚ)), exp_mul_exp_neg_eq_one, eq_comm] }, congr', end /-- The Bernoulli numbers are defined to be `bernoulli'` with a parity sign. -/ def bernoulli (n : ℕ) : ℚ := (-1)^n * bernoulli' n lemma bernoulli'_eq_bernoulli (n : ℕ) : bernoulli' n = (-1)^n * bernoulli n := by simp [bernoulli, ← mul_assoc, ← sq, ← pow_mul, mul_comm n 2, pow_mul] @[simp] lemma bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli] @[simp] lemma bernoulli_one : bernoulli 1 = -1/2 := by norm_num [bernoulli] theorem bernoulli_eq_bernoulli'_of_ne_one {n : ℕ} (hn : n ≠ 1) : bernoulli n = bernoulli' n := begin by_cases h0 : n = 0, { simp [h0] }, rw [bernoulli, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one n, { simp [h] }, simp [bernoulli'_odd_eq_zero (odd_iff.mpr h) (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, hn⟩)], end @[simp] theorem sum_bernoulli (n : ℕ): ∑ k in range n, (n.choose k : ℚ) * bernoulli k = if n = 1 then 1 else 0 := begin cases n, { simp }, cases n, { simp }, suffices : ∑ i in range n, ↑((n + 2).choose (i + 2)) * bernoulli (i + 2) = n / 2, { simp only [this, sum_range_succ', cast_succ, bernoulli_one, bernoulli_zero, choose_one_right, mul_one, choose_zero_right, cast_zero, if_false, zero_add, succ_succ_ne_one], ring }, have f := sum_bernoulli' n.succ.succ, simp_rw [sum_range_succ', bernoulli'_one, choose_one_right, cast_succ, ← eq_sub_iff_add_eq] at f, convert f, { funext x, rw bernoulli_eq_bernoulli'_of_ne_one (succ_ne_zero x ∘ succ.inj) }, { simp only [one_div, mul_one, bernoulli'_zero, cast_one, choose_zero_right, add_sub_cancel], ring }, end lemma bernoulli_spec' (n : ℕ) : ∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli k.1 = if n = 0 then 1 else 0 := begin cases n, { simp }, rw if_neg (succ_ne_zero _), -- algebra facts have h₁ : (1, n) ∈ antidiagonal n.succ := by simp [mem_antidiagonal, add_comm], have h₂ : (n : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero, have h₃ : (1 + n).choose n = n + 1 := by simp [add_comm], -- key equation: the corresponding fact for `bernoulli'` have H := bernoulli'_spec' n.succ, -- massage it to match the structure of the goal, then convert piece by piece rw sum_eq_add_sum_diff_singleton h₁ at H ⊢, apply add_eq_of_eq_sub', convert eq_sub_of_add_eq' H using 1, { refine sum_congr rfl (λ p h, _), obtain ⟨h', h''⟩ : p ∈ _ ∧ p ≠ _ := by rwa [mem_sdiff, mem_singleton] at h, simp [bernoulli_eq_bernoulli'_of_ne_one ((not_congr (antidiagonal_congr h' h₁)).mp h'')] }, { field_simp [h₃], norm_num }, end /-- The exponential generating function for the Bernoulli numbers `bernoulli n`. -/ def bernoulli_power_series := mk $ λ n, algebra_map ℚ A (bernoulli n / n!) theorem bernoulli_power_series_mul_exp_sub_one : bernoulli_power_series A * (exp A - 1) = X := begin ext n, -- constant coefficient is a special case cases n, { simp }, simp only [bernoulli_power_series, coeff_mul, coeff_X, sum_antidiagonal_succ', one_div, coeff_mk, coeff_one, coeff_exp, linear_map.map_sub, factorial, if_pos, cast_succ, cast_one, cast_mul, sub_zero, ring_hom.map_one, add_eq_zero_iff, if_false, _root_.inv_one, zero_add, one_ne_zero, mul_zero, and_false, sub_self, ← ring_hom.map_mul, ← ring_hom.map_sum], cases n, { simp }, rw if_neg n.succ_succ_ne_one, have hfact : ∀ m, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m, have hite2 : ite (n.succ = 0) 1 0 = (0 : ℚ) := if_neg n.succ_ne_zero, rw [←map_zero (algebra_map ℚ A), ←zero_div (n.succ! : ℚ), ←hite2, ← bernoulli_spec', sum_div], refine congr_arg (algebra_map ℚ A) (sum_congr rfl $ λ x h, eq_div_of_mul_eq (hfact n.succ) _), rw mem_antidiagonal at h, have hj : (x.2 + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero _, field_simp [← h, mul_ne_zero hj (hfact x.2), hfact x.1, mul_comm _ (bernoulli x.1), mul_assoc, add_choose, cast_div_char_zero (factorial_mul_factorial_dvd_factorial_add _ _), nat.factorial_ne_zero, hj], cc, end section faulhaber /-- **Faulhaber's theorem** relating the **sum of of p-th powers** to the Bernoulli numbers: $$\sum_{k=0}^{n-1} k^p = \sum_{i=0}^p B_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$ See https://proofwiki.org/wiki/Faulhaber%27s_Formula and [orosi2018faulhaber] for the proof provided here. -/ theorem sum_range_pow (n p : ℕ) : ∑ k in range n, (k : ℚ) ^ p = ∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) := begin have hne : ∀ m : ℕ, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m, -- compute the Cauchy product of two power series have h_cauchy : mk (λ p, bernoulli p / p!) * mk (λ q, coeff ℚ (q + 1) (exp ℚ ^ n)) = mk (λ p, ∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!), { ext q : 1, let f := λ a b, bernoulli a / a! * coeff ℚ (b + 1) (exp ℚ ^ n), -- key step: use `power_series.coeff_mul` and then rewrite sums simp only [coeff_mul, coeff_mk, cast_mul, sum_antidiagonal_eq_sum_range_succ f], apply sum_congr rfl, simp_intros m h only [finset.mem_range], simp only [f, exp_pow_eq_rescale_exp, rescale, one_div, coeff_mk, ring_hom.coe_mk, coeff_exp, ring_hom.id_apply, cast_mul, algebra_map_rat_rat], -- manipulate factorials and binomial coefficients rw [choose_eq_factorial_div_factorial h.le, eq_comm, div_eq_iff (hne q.succ), succ_eq_add_one, mul_assoc _ _ ↑q.succ!, mul_comm _ ↑q.succ!, ← mul_assoc, div_mul_eq_mul_div, mul_comm (↑n ^ (q - m + 1)), ← mul_assoc _ _ (↑n ^ (q - m + 1)), ← one_div, mul_one_div, div_div, tsub_add_eq_add_tsub (le_of_lt_succ h), cast_div, cast_mul], { ring }, { exact factorial_mul_factorial_dvd_factorial h.le }, { simp [hne] } }, -- same as our goal except we pull out `p!` for convenience have hps : ∑ k in range n, ↑k ^ p = (∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!) * p!, { suffices : mk (λ p, ∑ k in range n, ↑k ^ p * algebra_map ℚ ℚ p!⁻¹) = mk (λ p, ∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!), { rw [← div_eq_iff (hne p), div_eq_mul_inv, sum_mul], rw power_series.ext_iff at this, simpa using this p }, -- the power series `exp ℚ - 1` is non-zero, a fact we need in order to use `mul_right_inj'` have hexp : exp ℚ - 1 ≠ 0, { simp only [exp, power_series.ext_iff, ne, not_forall], use 1, simp }, have h_r : exp ℚ ^ n - 1 = X * mk (λ p, coeff ℚ (p + 1) (exp ℚ ^ n)), { have h_const : C ℚ (constant_coeff ℚ (exp ℚ ^ n)) = 1 := by simp, rw [← h_const, sub_const_eq_X_mul_shift] }, -- key step: a chain of equalities of power series rw [← mul_right_inj' hexp, mul_comm, ← exp_pow_sum, geom_sum_mul, h_r, ← bernoulli_power_series_mul_exp_sub_one, bernoulli_power_series, mul_right_comm], simp [h_cauchy, mul_comm] }, -- massage `hps` into our goal rw [hps, sum_mul], refine sum_congr rfl (λ x hx, _), field_simp [mul_right_comm _ ↑p!, ← mul_assoc _ _ ↑p!, cast_add_one_ne_zero, hne], end /-- Alternate form of **Faulhaber's theorem**, relating the sum of p-th powers to the Bernoulli numbers: $$\sum_{k=1}^{n} k^p = \sum_{i=0}^p (-1)^iB_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$ Deduced from `sum_range_pow`. -/ theorem sum_Ico_pow (n p : ℕ) : ∑ k in Ico 1 (n + 1), (k : ℚ) ^ p = ∑ i in range (p + 1), bernoulli' i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) := begin rw ← nat.cast_succ, -- dispose of the trivial case cases p, { simp }, let f := λ i, bernoulli i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ, let f' := λ i, bernoulli' i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ, suffices : ∑ k in Ico 1 n.succ, ↑k ^ p.succ = ∑ i in range p.succ.succ, f' i, { convert this }, -- prove some algebraic facts that will make things easier for us later on have hle := nat.le_add_left 1 n, have hne : (p + 1 + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero p.succ, have h1 : ∀ r : ℚ, r * (p + 1 + 1) * n ^ p.succ / (p + 1 + 1 : ℚ) = r * n ^ p.succ := λ r, by rw [mul_div_right_comm, mul_div_cancel _ hne], have h2 : f 1 + n ^ p.succ = 1 / 2 * n ^ p.succ, { simp_rw [f, bernoulli_one, choose_one_right, succ_sub_succ_eq_sub, cast_succ, tsub_zero, h1], ring }, have : ∑ i in range p, bernoulli (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2) = ∑ i in range p, bernoulli' (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2) := sum_congr rfl (λ i h, by rw bernoulli_eq_bernoulli'_of_ne_one (succ_succ_ne_one i)), calc ∑ k in Ico 1 n.succ, ↑k ^ p.succ -- replace sum over `Ico` with sum over `range` and simplify = ∑ k in range n.succ, ↑k ^ p.succ : by simp [sum_Ico_eq_sub _ hle, succ_ne_zero] -- extract the last term of the sum ... = ∑ k in range n, (k : ℚ) ^ p.succ + n ^ p.succ : by rw sum_range_succ -- apply the key lemma, `sum_range_pow` ... = ∑ i in range p.succ.succ, f i + n ^ p.succ : by simp [f, sum_range_pow] -- extract the first two terms of the sum ... = ∑ i in range p, f i.succ.succ + f 1 + f 0 + n ^ p.succ : by simp_rw [sum_range_succ'] ... = ∑ i in range p, f i.succ.succ + (f 1 + n ^ p.succ) + f 0 : by ring ... = ∑ i in range p, f i.succ.succ + 1 / 2 * n ^ p.succ + f 0 : by rw h2 -- convert from `bernoulli` to `bernoulli'` ... = ∑ i in range p, f' i.succ.succ + f' 1 + f' 0 : by { simp only [f, f'], simpa [h1, λ i, show i + 2 = i + 1 + 1, from rfl] } -- rejoin the first two terms of the sum ... = ∑ i in range p.succ.succ, f' i : by simp_rw [sum_range_succ'], end end faulhaber
e4795b952c1105e6271a1552d2e21e98caaeeac6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/fintype/small.lean
6c24ac71f1cbb09dc789ec6b713f6d2db0d30ccd
[ "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
606
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 data.fintype.card import logic.small.basic /-! # All finite types are small. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. That is, any `α` with `[fintype α]` is equivalent to a type in any universe. -/ universes w v @[priority 100] instance small_of_fintype (α : Type v) [fintype α] : small.{w} α := begin rw small_congr (fintype.equiv_fin α), apply_instance, end
f0fb0787af6ee6ff109ef63db2139b142a57bccf
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/error_full_names.lean
bdf79301677b1347889d1a22c1c77f9e5769da75
[ "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
164
lean
namespace foo open nat inductive nat : Type | zero, foosucc : nat → nat check 0 + nat.zero --error end foo namespace foo check nat.succ nat.zero --error end foo
d20cfbbabeb56f338b9c213666e8c288239421a9
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/logic/basic.lean
5c17920f406b3af335ab8462561dde6db9c1dd4f
[ "Apache-2.0" ]
permissive
kristychoi/mathlib
c504b5e8f84e272ea1d8966693c42de7523bf0ec
257fd84fe98927ff4a5ffe044f68c4e9d235cc75
refs/heads/master
1,586,520,722,896
1,544,030,145,000
1,544,031,933,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,344
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 Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". Note: in the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ import data.prod tactic.cache /- miscellany TODO: move elsewhere -/ section miscellany variables {α : Type*} {β : Type*} def empty.elim {C : Sort*} : empty → C. instance : subsingleton empty := ⟨λa, a.elim⟩ instance : decidable_eq empty := λa, a.elim @[priority 0] instance decidable_eq_of_subsingleton {α} [subsingleton α] : decidable_eq α | a b := is_true (subsingleton.elim a b) /- Add an instance to "undo" coercion transitivity into a chain of coercions, because most simp lemmas are stated with respect to simple coercions and will not match when part of a chain. -/ @[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ] (a : α) : (a : γ) = (a : β) := rfl @[simp] theorem coe_fn_coe_trans {α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ] (x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl @[simp] theorem coe_fn_coe_base {α β} [has_coe α β] [has_coe_to_fun β] (x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl @[simp] theorem coe_sort_coe_trans {α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ] (x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl @[simp] theorem coe_sort_coe_base {α β} [has_coe α β] [has_coe_to_sort β] (x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl /-- `pempty` is the universe-polymorphic analogue of `empty`. -/ @[derive decidable_eq] inductive {u} pempty : Sort u def pempty.elim {C : Sort*} : pempty → C. instance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩ lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂ | a _ rfl := heq.rfl end miscellany /- propositional connectives -/ @[simp] theorem false_ne_true : false ≠ true | h := h.symm ▸ trivial section propositional variables {a b c d : Prop} /- implies -/ theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩ @[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id theorem imp_intro {α β} (h : α) (h₂ : β) : α := h theorem imp_false : (a → false) ↔ ¬ a := iff.rfl theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) := ⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩, λ h ha, ⟨h.left ha, h.right ha⟩⟩ @[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb) theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies _ _ theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) := iff_def.trans and.comm @[simp] theorem imp_true_iff {α : Sort*} : (α → true) ↔ true := iff_true_intro $ λ_, trivial @[simp] theorem imp_iff_right (ha : a) : (a → b) ↔ b := ⟨λf, f ha, imp_intro⟩ /- not -/ theorem not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1 @[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2 theorem not_not_of_not_imp : ¬(a → b) → ¬¬a := mt not.elim theorem not_of_not_imp {α} : ¬(α → b) → ¬b := mt imp_intro theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p theorem by_contradiction {p} [decidable p] : (¬p → false) → p := decidable.by_contradiction @[simp] theorem not_not [decidable a] : ¬¬a ↔ a := iff.intro by_contradiction not_not_intro theorem of_not_not [decidable a] : ¬¬a → a := by_contradiction theorem of_not_imp [decidable a] (h : ¬ (a → b)) : a := by_contradiction (not_not_of_not_imp h) theorem not.imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a := by_contradiction $ hb ∘ h theorem not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) := ⟨not.imp_symm, not.imp_symm⟩ theorem imp.swap : (a → b → c) ↔ (b → a → c) := ⟨function.swap, function.swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap /- and -/ theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and.imp_left (h : a → b) : a ∧ c → b ∧ c := and.imp h id theorem and.imp_right (h : a → b) : c ∧ a → c ∧ b := and.imp id h lemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := by simp [and.left_comm, and.comm] lemma and.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a := by simp [and.left_comm, and.comm] theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false := iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false := iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, h ha⟩) theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b := iff.intro and.right (λ hb, ⟨h hb, hb⟩) lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) := ⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩ /- or -/ theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha (assume h₂, or.elim h₂ hb hc) theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) := ⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩, assume ⟨ha, hb⟩, or.rec ha hb⟩ theorem or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) := ⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩ theorem or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) := or.comm.trans or_iff_not_imp_left theorem not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, by_contradiction $ assume na, h na hb, mt⟩ /- distributivity -/ theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := ⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha), or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩ theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := (and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm) theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := ⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr), and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩ theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := (or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm) /- iff -/ theorem iff_of_true (ha : a) (hb : b) : a ↔ b := ⟨λ_, hb, λ _, ha⟩ theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b := ⟨ha.elim, hb.elim⟩ theorem iff_true_left (ha : a) : (a ↔ b) ↔ b := ⟨λ h, h.1 ha, iff_of_true ha⟩ theorem iff_true_right (ha : a) : (b ↔ a) ↔ b := iff.comm.trans (iff_true_left ha) theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b := ⟨λ h, mt h.2 ha, iff_of_false ha⟩ theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b := iff.comm.trans (iff_false_left ha) theorem not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b := if ha : a then or.inr (h ha) else or.inl ha theorem imp_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) := ⟨not_or_of_imp, or.neg_resolve_left⟩ theorem imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by simp [imp_iff_not_or, or.comm, or.left_comm] theorem imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)] theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b) | ⟨ha, hb⟩ h := hb $ h ha @[simp] theorem not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨λ h, ⟨of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩ -- for monotonicity lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) := assume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀ theorem peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h ha.elim theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id theorem not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) := by rw [@iff_def (¬ a), @iff_def' a]; exact and_congr not_imp_not not_imp_not theorem not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) := by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr not_imp_comm imp_not_comm theorem not_iff [decidable a] [decidable b] : ¬ (a ↔ b) ↔ (¬ a ↔ b) := by split; intro h; [split, skip]; intro h'; [by_contradiction,intro,skip]; try { refine h _; simp [*] }; rw [h',not_iff_self] at h; exact h theorem iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := by rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm not_imp_comm theorem iff_iff_and_or_not_and_not [decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := by { split; intro h, { rw h; by_cases b; [left,right]; split; assumption }, { cases h with h h; cases h; split; intro; { contradiction <|> assumption } } } @[simp] theorem not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) := ⟨λ h ha, h.imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩ @[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b := decidable_of_decidable_of_iff D h @[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a := decidable_of_decidable_of_iff D h.symm def decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a | tt h := is_true (h.1 rfl) | ff h := is_false (mt h.2 bool.ff_ne_tt) /- de morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) | ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb) theorem not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩ theorem not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩ @[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a := not_and.trans imp_not_comm theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := ⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩, λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩ theorem or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rw [← not_or_distrib, not_not] theorem and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rw [← not_and_distrib, not_not] end propositional /- equality -/ section equality variables {α : Sort*} {a b : α} @[simp] theorem heq_iff_eq : a == b ↔ a = b := ⟨eq_of_heq, heq_of_eq⟩ theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq := have p = q, from propext ⟨λ _, hq, λ _, hp⟩, by subst q; refl theorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α} (h : a ∈ s) : b ∉ s → a ≠ b := mt $ λ e, e ▸ h theorem eq_equivalence : equivalence (@eq α) := ⟨eq.refl, @eq.symm _, @eq.trans _⟩ lemma heq_of_eq_mp : ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : (eq.mp e a) = a'), a == a' | α ._ a a' rfl h := eq.rec_on h (heq.refl _) lemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) : @eq.rec α a C x b eq == y := by subst eq; exact h end equality /- quantifiers -/ section quantifiers variables {α : Sort*} {p q : α → Prop} {b : Prop} def Exists.imp := @exists_imp_exists theorem forall_swap {α β} {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y := ⟨function.swap, function.swap⟩ theorem exists_swap {α β} {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y := ⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩ @[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩ --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_imp_of_exists_imp h theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_imp_distrib.2 h @[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x := exists_imp_distrib theorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x | ⟨x, hn⟩ h := hn (h x) theorem not_forall {p : α → Prop} [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := ⟨not.imp_symm $ λ nx x, nx.imp_symm $ λ h, ⟨x, h⟩, not_forall_of_exists_not⟩ @[simp] theorem not_forall_not [decidable (∃ x, p x)] : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := by haveI := decidable_of_iff (¬ ∃ x, p x) not_exists; exact not_iff_comm.1 not_exists @[simp] theorem not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := by simp @[simp] theorem forall_true_iff : (α → true) ↔ true := iff_true_intro (λ _, trivial) -- Unfortunately this causes simp to loop sometimes, so we -- add the 2 and 3 cases as simp lemmas instead theorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true := iff_true_intro (λ _, of_iff_true (h _)) @[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true := forall_true_iff' $ λ _, forall_true_iff @[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} : (∀ a (b : β a), γ a b → true) ↔ true := forall_true_iff' $ λ _, forall_2_true_iff @[simp] theorem forall_const (α : Sort*) [inhabited α] : (α → b) ↔ b := ⟨λ h, h (arbitrary α), λ hb x, hb⟩ @[simp] theorem exists_const (α : Sort*) [inhabited α] : (∃ x : α, b) ↔ b := ⟨λ ⟨x, h⟩, h, λ h, ⟨arbitrary α, h⟩⟩ theorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := ⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩ theorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := ⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩), λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩ @[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩ @[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} : (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q := by simp [and_comm] @[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩ @[simp] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩ @[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' := ⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩ @[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' := (exists_congr $ by exact λ a, and.comm).trans exists_eq_left @[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' := by simp [@eq_comm _ a'] theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x := h.imp_right $ λ h₂, h₂ x theorem forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := ⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq, forall_or_of_or_forall⟩ @[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩ @[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h theorem Exists.fst {p : b → Prop} : Exists p → b | ⟨h, _⟩ := h theorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst | ⟨_, h⟩ := h @[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h := @forall_const (q h) p ⟨h⟩ @[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h := @exists_const (q h) p ⟨h⟩ @[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true := iff_true_intro $ λ h, hn.elim h @[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') := mt Exists.fst end quantifiers /- classical versions -/ namespace classical variables {α : Sort*} {p : α → Prop} local attribute [instance] prop_decidable protected theorem not_forall : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := not_forall protected theorem forall_or_distrib_left {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := forall_or_distrib_left theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a := assume a, cases_on a h1 h2 theorem or_not {p : Prop} : p ∨ ¬ p := by_cases or.inl or.inr protected theorem or_iff_not_imp_left {p q : Prop} : p ∨ q ↔ (¬ p → q) := or_iff_not_imp_left protected theorem or_iff_not_imp_right {p q : Prop} : q ∨ p ↔ (¬ p → q) := or_iff_not_imp_right protected lemma not_not {p : Prop} : ¬¬p ↔ p := not_not /- use shortened names to avoid conflict when classical namespace is open -/ noncomputable theorem dec (p : Prop) : decidable p := by apply_instance noncomputable theorem dec_pred (p : α → Prop) : decidable_pred p := by apply_instance noncomputable theorem dec_rel (p : α → α → Prop) : decidable_rel p := by apply_instance noncomputable theorem dec_eq (α : Sort*) : decidable_eq α := by apply_instance @[elab_as_eliminator] noncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C := if h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0 lemma some_spec2 {α : Type*} {p : α → Prop} {h : ∃a, p a} (q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) := hpq _ $ some_spec _ end classical @[elab_as_eliminator] noncomputable def {u} exists.classical_rec_on {α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C := H (classical.some h) (classical.some_spec h) /- bounded quantifiers -/ section bounded_quantifiers variables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop} theorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩ theorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b | ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂ theorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h := ⟨a, h₁, h₂⟩ theorem ball_congr (H : ∀ x h, P x h ↔ Q x h) : (∀ x h, P x h) ↔ (∀ x h, Q x h) := forall_congr $ λ x, forall_congr (H x) theorem bex_congr (H : ∀ x h, P x h ↔ Q x h) : (∃ x h, P x h) ↔ (∃ x h, Q x h) := exists_congr $ λ x, exists_congr (H x) theorem ball.imp_right (H : ∀ x h, (P x h → Q x h)) (h₁ : ∀ x h, P x h) (x h) : Q x h := H _ _ $ h₁ _ _ theorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) : (∃ x h, P x h) → ∃ x h, Q x h | ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩ theorem ball.imp_left (H : ∀ x, p x → q x) (h₁ : ∀ x, q x → r x) (x) (h : p x) : r x := h₁ _ $ H _ h theorem bex.imp_left (H : ∀ x, p x → q x) : (∃ x (_ : p x), r x) → ∃ x (_ : q x), r x | ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩ theorem ball_of_forall (h : ∀ x, p x) (x) (_ : q x) : p x := h x theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x := h x $ H x theorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x | ⟨x, hq⟩ := ⟨x, H x, hq⟩ theorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x | ⟨x, _, hq⟩ := ⟨x, hq⟩ @[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) := by simp theorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h := bex_imp_distrib theorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h | ⟨x, h, hp⟩ al := hp $ al x h theorem not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := ⟨not.imp_symm $ λ nx x h, nx.imp_symm $ λ h', ⟨x, h, h'⟩, not_ball_of_bex_not⟩ theorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true := iff_true_intro (λ h hrx, trivial) theorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) := iff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib theorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) := iff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib end bounded_quantifiers namespace classical local attribute [instance] prop_decidable theorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball end classical section nonempty universes u v w variables {α : Type u} {β : Type v} {γ : α → Type w} attribute [simp] nonempty_of_inhabited lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α := iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩) @[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p := iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩) lemma not_nonempty_iff_imp_false {p : Prop} : ¬ nonempty α ↔ α → false := ⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩ @[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_subtype {α : Sort u} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) := iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩) @[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_pprod {α : Sort u} {β : Sort v} : nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end) @[simp] lemma nonempty_psum {α : Sort u} {β : Sort v} : nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end) @[simp] lemma nonempty_psigma {α : Sort u} {β : α → Sort v} : nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_empty : ¬ nonempty empty := assume ⟨h⟩, h.elim @[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty_plift {α : Sort u} : nonempty (plift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty.forall {α : Sort u} {p : nonempty α → Prop} : (∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) := iff.intro (assume h a, h _) (assume h ⟨a⟩, h _) @[simp] lemma nonempty.exists {α : Sort u} {p : nonempty α → Prop} : (∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) := iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩) lemma classical.nonempty_pi {α : Sort u} {β : α → Sort v} : nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) := iff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩) end nonempty
745f03a6dca1988d740422056ebd009fca9b93cb
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/adjunction/reflective.lean
c97294ca23cc652865e5a1b9b7748bb37741e4e4
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,912
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.preserves.shapes.terminal import category_theory.adjunction.fully_faithful /-! # Reflective functors Basic properties of reflective functors, especially those relating to their essential image. Note properties of reflective functors relating to limits and colimits are included in `category_theory.monad.limits`. -/ universes v₁ v₂ v₃ u₁ u₂ u₃ noncomputable theory namespace category_theory open category adjunction limits variables {C : Type u₁} {D : Type u₂} {E : Type u₃} variables [category.{v₁} C] [category.{v₂} D] [category.{v₃} E] /-- A functor is *reflective*, or *a reflective inclusion*, if it is fully faithful and right adjoint. -/ class reflective (R : D ⥤ C) extends is_right_adjoint R, full R, faithful R. variables {i : D ⥤ C} /-- For a reflective functor `i` (with left adjoint `L`), with unit `η`, we have `η_iL = iL η`. -/ -- TODO: This holds more generally for idempotent adjunctions, not just reflective adjunctions. lemma unit_obj_eq_map_unit [reflective i] (X : C) : (of_right_adjoint i).unit.app (i.obj ((left_adjoint i).obj X)) = i.map ((left_adjoint i).map ((of_right_adjoint i).unit.app X)) := begin rw [←cancel_mono (i.map ((of_right_adjoint i).counit.app ((left_adjoint i).obj X))), ←i.map_comp], simp, end /-- When restricted to objects in `D` given by `i : D ⥤ C`, the unit is an isomorphism. In other words, `η_iX` is an isomorphism for any `X` in `D`. More generally this applies to objects essentially in the reflective subcategory, see `functor.ess_image.unit_iso`. -/ instance is_iso_unit_obj [reflective i] {B : D} : is_iso ((of_right_adjoint i).unit.app (i.obj B)) := begin have : (of_right_adjoint i).unit.app (i.obj B) = inv (i.map ((of_right_adjoint i).counit.app B)), { rw ← comp_hom_eq_id, apply (of_right_adjoint i).right_triangle_components }, rw this, exact is_iso.inv_is_iso, end /-- If `A` is essentially in the image of a reflective functor `i`, then `η_A` is an isomorphism. This gives that the "witness" for `A` being in the essential image can instead be given as the reflection of `A`, with the isomorphism as `η_A`. (For any `B` in the reflective subcategory, we automatically have that `ε_B` is an iso.) -/ lemma functor.ess_image.unit_is_iso [reflective i] {A : C} (h : A ∈ i.ess_image) : is_iso ((of_right_adjoint i).unit.app A) := begin suffices : (of_right_adjoint i).unit.app A = h.get_iso.inv ≫ (of_right_adjoint i).unit.app (i.obj h.witness) ≫ (left_adjoint i ⋙ i).map h.get_iso.hom, { rw this, apply_instance }, rw ← nat_trans.naturality, simp, end /-- If `η_A` is an isomorphism, then `A` is in the essential image of `i`. -/ lemma mem_ess_image_of_unit_is_iso [is_right_adjoint i] (A : C) [is_iso ((of_right_adjoint i).unit.app A)] : A ∈ i.ess_image := ⟨(left_adjoint i).obj A, ⟨(as_iso ((of_right_adjoint i).unit.app A)).symm⟩⟩ /-- If `η_A` is a split monomorphism, then `A` is in the reflective subcategory. -/ lemma mem_ess_image_of_unit_split_mono [reflective i] {A : C} [split_mono ((of_right_adjoint i).unit.app A)] : A ∈ i.ess_image := begin let η : 𝟭 C ⟶ left_adjoint i ⋙ i := (of_right_adjoint i).unit, haveI : is_iso (η.app (i.obj ((left_adjoint i).obj A))) := (i.obj_mem_ess_image _).unit_is_iso, have : epi (η.app A), { apply epi_of_epi (retraction (η.app A)) _, rw (show retraction _ ≫ η.app A = _, from η.naturality (retraction (η.app A))), apply epi_comp (η.app (i.obj ((left_adjoint i).obj A))) }, resetI, haveI := is_iso_of_epi_of_split_mono (η.app A), exact mem_ess_image_of_unit_is_iso A, end /-- Composition of reflective functors. -/ instance reflective.comp (F : C ⥤ D) (G : D ⥤ E) [Fr : reflective F] [Gr : reflective G] : reflective (F ⋙ G) := { to_faithful := faithful.comp F G, } /-- (Implementation) Auxiliary definition for `unit_comp_partial_bijective`. -/ def unit_comp_partial_bijective_aux [reflective i] (A : C) (B : D) : (A ⟶ i.obj B) ≃ (i.obj ((left_adjoint i).obj A) ⟶ i.obj B) := ((adjunction.of_right_adjoint i).hom_equiv _ _).symm.trans (equiv_of_fully_faithful i) /-- The description of the inverse of the bijection `unit_comp_partial_bijective_aux`. -/ lemma unit_comp_partial_bijective_aux_symm_apply [reflective i] {A : C} {B : D} (f : i.obj ((left_adjoint i).obj A) ⟶ i.obj B) : (unit_comp_partial_bijective_aux _ _).symm f = (of_right_adjoint i).unit.app A ≫ f := by simp [unit_comp_partial_bijective_aux] /-- If `i` has a reflector `L`, then the function `(i.obj (L.obj A) ⟶ B) → (A ⟶ B)` given by precomposing with `η.app A` is a bijection provided `B` is in the essential image of `i`. That is, the function `λ (f : i.obj (L.obj A) ⟶ B), η.app A ≫ f` is bijective, as long as `B` is in the essential image of `i`. This definition gives an equivalence: the key property that the inverse can be described nicely is shown in `unit_comp_partial_bijective_symm_apply`. This establishes there is a natural bijection `(A ⟶ B) ≃ (i.obj (L.obj A) ⟶ B)`. In other words, from the point of view of objects in `D`, `A` and `i.obj (L.obj A)` look the same: specifically that `η.app A` is an isomorphism. -/ def unit_comp_partial_bijective [reflective i] (A : C) {B : C} (hB : B ∈ i.ess_image) : (A ⟶ B) ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) := calc (A ⟶ B) ≃ (A ⟶ i.obj hB.witness) : iso.hom_congr (iso.refl _) hB.get_iso.symm ... ≃ (i.obj _ ⟶ i.obj hB.witness) : unit_comp_partial_bijective_aux _ _ ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) : iso.hom_congr (iso.refl _) hB.get_iso @[simp] lemma unit_comp_partial_bijective_symm_apply [reflective i] (A : C) {B : C} (hB : B ∈ i.ess_image) (f) : (unit_comp_partial_bijective A hB).symm f = (of_right_adjoint i).unit.app A ≫ f := by simp [unit_comp_partial_bijective, unit_comp_partial_bijective_aux_symm_apply] lemma unit_comp_partial_bijective_symm_natural [reflective i] (A : C) {B B' : C} (h : B ⟶ B') (hB : B ∈ i.ess_image) (hB' : B' ∈ i.ess_image) (f : i.obj ((left_adjoint i).obj A) ⟶ B) : (unit_comp_partial_bijective A hB').symm (f ≫ h) = (unit_comp_partial_bijective A hB).symm f ≫ h := by simp lemma unit_comp_partial_bijective_natural [reflective i] (A : C) {B B' : C} (h : B ⟶ B') (hB : B ∈ i.ess_image) (hB' : B' ∈ i.ess_image) (f : A ⟶ B) : (unit_comp_partial_bijective A hB') (f ≫ h) = unit_comp_partial_bijective A hB f ≫ h := by rw [←equiv.eq_symm_apply, unit_comp_partial_bijective_symm_natural A h, equiv.symm_apply_apply] end category_theory
360fe4879a10232d7754a198a4fa8c02b73baede
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/interp2.lean
79ea761857c04ec53b23075df982ef6ff773dfd1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,024
lean
inductive Vector (α : Type u) : Nat → Type u | nil : Vector α 0 | cons : α → Vector α n → Vector α (n+1) infix:67 " :: " => Vector.cons inductive Ty where | int | bool | fn (a r : Ty) abbrev Ty.interp : Ty → Type | int => Int | bool => Bool | fn a r => a.interp → r.interp inductive HasType : Fin n → Vector Ty n → Ty → Type where | stop : HasType 0 (ty :: ctx) ty | pop : HasType k ctx ty → HasType k.succ (u :: ctx) ty inductive Expr : Vector Ty n → Ty → Type where | var : HasType i ctx ty → Expr ctx ty | val : Int → Expr ctx Ty.int | lam : Expr (a :: ctx) ty → Expr ctx (Ty.fn a ty) | app : Expr ctx (Ty.fn a ty) → Expr ctx a → Expr ctx ty | op : (a.interp → b.interp → c.interp) → Expr ctx a → Expr ctx b → Expr ctx c | ife : Expr ctx Ty.bool → Expr ctx a → Expr ctx a → Expr ctx a | delay : (Unit → Expr ctx a) → Expr ctx a inductive Env : Vector Ty n → Type where | nil : Env Vector.nil | cons : Ty.interp a → Env ctx → Env (a :: ctx) infix:67 " :: " => Env.cons def lookup : HasType i ctx ty → Env ctx → ty.interp | .stop, x :: xs => x | .pop k, x :: xs => lookup k xs def interp (env : Env ctx) : Expr ctx ty → ty.interp := fun e => match e with | .var i => lookup i env | .val x => x | .lam b => fun x => interp (x :: env) b | .app f a => interp env f (interp env a) | .op o x y => o (interp env x) (interp env y) | .ife c t e => if interp env c then interp env t else interp env e | .delay a => interp env (a ()) open Expr /- Examples -/ def add : Expr ctx (Ty.fn Ty.int (Ty.fn Ty.int Ty.int)) := lam (lam (op (.+.) (var .stop) (var (.pop .stop)))) #eval interp Env.nil add 10 20 def fact : Expr ctx (Ty.fn Ty.int Ty.int) := lam (ife (op (.==.) (var .stop) (val 0)) (val 1) (op (.*.) (delay fun _ => app fact (op (.-.) (var .stop) (val 1))) (var .stop))) decreasing_by sorry #eval interp Env.nil fact 10
c8ab881424a69a5fd98cf0fc9386dbf7c65833c4
9dc8cecdf3c4634764a18254e94d43da07142918
/archive/100-theorems-list/82_cubing_a_cube.lean
f1e94be0ad83cdc793a7b6463f9f9bbac5bf21f3
[ "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
23,621
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import data.fin.tuple import data.real.basic import data.set.intervals import data.set.pairwise import set_theory.cardinal.basic /-! Proof that a cube (in dimension n ≥ 3) cannot be cubed: There does not exist a partition of a cube into finitely many smaller cubes (at least two) of different sizes. We follow the proof described here: http://www.alaricstephen.com/main-featured/2017/9/28/cubing-a-cube-proof -/ open real set function fin open_locale cardinal noncomputable theory variable {n : ℕ} /-- Given three intervals `I, J, K` such that `J ⊂ I`, neither endpoint of `J` coincides with an endpoint of `I`, `¬ (K ⊆ J)` and `K` does not lie completely to the left nor completely to the right of `J`. Then `I ∩ K \ J` is nonempty. -/ lemma Ico_lemma {α} [linear_order α] {x₁ x₂ y₁ y₂ z₁ z₂ w : α} (h₁ : x₁ < y₁) (hy : y₁ < y₂) (h₂ : y₂ < x₂) (hz₁ : z₁ ≤ y₂) (hz₂ : y₁ ≤ z₂) (hw : w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂) : ∃w, w ∈ Ico x₁ x₂ ∧ w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂ := begin simp only [not_and, not_lt, mem_Ico] at hw, refine ⟨max x₁ (min w y₂), _, _, _⟩, { simp [le_refl, lt_trans h₁ (lt_trans hy h₂), h₂] }, { simp [hw, lt_irrefl, not_le_of_lt h₁] {contextual := tt} }, { simp [hw.2.1, hw.2.2, hz₁, lt_of_lt_of_le h₁ hz₂] at ⊢ } end /-- A (hyper)-cube (in standard orientation) is a vector `b` consisting of the bottom-left point of the cube, a width `w` and a proof that `w > 0`. We use functions from `fin n` to denote vectors. -/ structure cube (n : ℕ) : Type := (b : fin n → ℝ) -- bottom-left coordinate (w : ℝ) -- width (hw : 0 < w) namespace cube lemma hw' (c : cube n) : 0 ≤ c.w := le_of_lt c.hw /-- The j-th side of a cube is the half-open interval `[b j, b j + w)` -/ def side (c : cube n) (j : fin n) : set ℝ := Ico (c.b j) (c.b j + c.w) @[simp] lemma b_mem_side (c : cube n) (j : fin n) : c.b j ∈ c.side j := by simp [side, cube.hw, le_refl] def to_set (c : cube n) : set (fin n → ℝ) := { x | ∀j, x j ∈ side c j } def to_set_subset {c c' : cube n} : c.to_set ⊆ c'.to_set ↔ ∀j, c.side j ⊆ c'.side j := begin split, intros h j x hx, let f : fin n → ℝ := λ j', if j' = j then x else c.b j', have : f ∈ c.to_set, { intro j', by_cases hj' : j' = j; simp [f, hj', if_pos, if_neg, hx] }, convert h this j, { simp [f, if_pos] }, intros h f hf j, exact h j (hf j) end def to_set_disjoint {c c' : cube n} : disjoint c.to_set c'.to_set ↔ ∃j, disjoint (c.side j) (c'.side j) := begin split, intros h, classical, by_contra h', simp only [not_disjoint_iff, classical.skolem, not_exists] at h', cases h' with f hf, apply not_disjoint_iff.mpr ⟨f, _, _⟩ h; intro j, exact (hf j).1, exact (hf j).2, rintro ⟨j, hj⟩, rw [set.disjoint_iff], rintros f ⟨h1f, h2f⟩, apply not_disjoint_iff.mpr ⟨f j, h1f j, h2f j⟩ hj end lemma b_mem_to_set (c : cube n) : c.b ∈ c.to_set := by simp [to_set] protected def tail (c : cube (n+1)) : cube n := ⟨tail c.b, c.w, c.hw⟩ lemma side_tail (c : cube (n+1)) (j : fin n) : c.tail.side j = c.side j.succ := rfl def bottom (c : cube (n+1)) : set (fin (n+1) → ℝ) := { x | x 0 = c.b 0 ∧ tail x ∈ c.tail.to_set } lemma b_mem_bottom (c : cube (n+1)) : c.b ∈ c.bottom := by simp [bottom, to_set, side, cube.hw, le_refl, cube.tail] def xm (c : cube (n+1)) : ℝ := c.b 0 + c.w lemma b_lt_xm (c : cube (n+1)) : c.b 0 < c.xm := by simp [xm, hw] lemma b_ne_xm (c : cube (n+1)) : c.b 0 ≠ c.xm := ne_of_lt c.b_lt_xm def shift_up (c : cube (n+1)) : cube (n+1) := ⟨cons c.xm $ tail c.b, c.w, c.hw⟩ @[simp] lemma tail_shift_up (c : cube (n+1)) : c.shift_up.tail = c.tail := by simp [shift_up, cube.tail] @[simp] lemma head_shift_up (c : cube (n+1)) : c.shift_up.b 0 = c.xm := rfl def unit_cube : cube n := ⟨λ _, 0, 1, by norm_num⟩ @[simp] lemma side_unit_cube {j : fin n} : unit_cube.side j = Ico 0 1 := by norm_num [unit_cube, side] end cube open cube variables {ι : Type} [fintype ι] {cs : ι → cube (n+1)} {i i' : ι} /-- A finite family of (at least 2) cubes partitioning the unit cube with different sizes -/ def correct (cs : ι → cube n) : Prop := pairwise (disjoint on (cube.to_set ∘ cs)) ∧ (⋃(i : ι), (cs i).to_set) = unit_cube.to_set ∧ injective (cube.w ∘ cs) ∧ 2 ≤ #ι ∧ 3 ≤ n variable (h : correct cs) include h lemma to_set_subset_unit_cube {i} : (cs i).to_set ⊆ unit_cube.to_set := by { rw [←h.2.1], exact subset_Union _ i } lemma side_subset {i j} : (cs i).side j ⊆ Ico 0 1 := by { have := to_set_subset_unit_cube h, rw [to_set_subset] at this, convert this j, norm_num [unit_cube] } lemma zero_le_of_mem_side {i j x} (hx : x ∈ (cs i).side j) : 0 ≤ x := (side_subset h hx).1 lemma zero_le_of_mem {i p} (hp : p ∈ (cs i).to_set) (j) : 0 ≤ p j := zero_le_of_mem_side h (hp j) lemma zero_le_b {i j} : 0 ≤ (cs i).b j := zero_le_of_mem h (cs i).b_mem_to_set j lemma b_add_w_le_one {j} : (cs i).b j + (cs i).w ≤ 1 := by { have := side_subset h, rw [side, Ico_subset_Ico_iff] at this, convert this.2, simp [hw] } /-- The width of any cube in the partition cannot be 1. -/ lemma w_ne_one (i : ι) : (cs i).w ≠ 1 := begin intro hi, have := h.2.2.2.1, rw [cardinal.two_le_iff' i] at this, cases this with i' hi', let p := (cs i').b, have hp : p ∈ (cs i').to_set := (cs i').b_mem_to_set, have h2p : p ∈ (cs i).to_set, { intro j, split, transitivity (0 : ℝ), { rw [←add_le_add_iff_right (1 : ℝ)], convert b_add_w_le_one h, rw hi, rw zero_add }, apply zero_le_b h, apply lt_of_lt_of_le (side_subset h $ (cs i').b_mem_side j).2, simp [hi, zero_le_b h] }, apply not_disjoint_iff.mpr ⟨p, hp, h2p⟩, apply h.1, exact hi'.symm end /-- The top of a cube (which is the bottom of the cube shifted up by its width) must be covered by bottoms of (other) cubes in the family. -/ lemma shift_up_bottom_subset_bottoms (hc : (cs i).xm ≠ 1) : (cs i).shift_up.bottom ⊆ ⋃(i : ι), (cs i).bottom := begin intros p hp, cases hp with hp0 hps, rw [tail_shift_up] at hps, have : p ∈ (unit_cube : cube (n+1)).to_set, { simp only [to_set, forall_fin_succ, hp0, side_unit_cube, mem_set_of_eq, mem_Ico, head_shift_up], refine ⟨⟨_, _⟩, _⟩, { rw [←zero_add (0 : ℝ)], apply add_le_add, apply zero_le_b h, apply (cs i).hw' }, { exact lt_of_le_of_ne (b_add_w_le_one h) hc }, intro j, exact side_subset h (hps j) }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i', rfl⟩, hi'⟩, rw [mem_Union], use i', refine ⟨_, λ j, hi' j.succ⟩, have : i ≠ i', { rintro rfl, apply not_le_of_lt (hi' 0).2, rw [hp0], refl }, have := h.1 i i' this, rw [on_fun, to_set_disjoint, exists_fin_succ] at this, rcases this with h0|⟨j, hj⟩, rw [hp0], symmetry, apply eq_of_Ico_disjoint h0 (by simp [hw]) _, convert hi' 0, rw [hp0], refl, exfalso, apply not_disjoint_iff.mpr ⟨tail p j, hps j, hi' j.succ⟩ hj end omit h /-- A valley is a square on which cubes in the family of cubes are placed, so that the cubes completely cover the valley and none of those cubes is partially outside the square. We also require that no cube on it has the same size as the valley (so that there are at least two cubes on the valley). This is the main concept in the formalization. We prove that the smallest cube on a valley has another valley on the top of it, which gives an infinite sequence of cubes in the partition, which contradicts the finiteness. A valley is characterized by a cube `c` (which is not a cube in the family cs) by considering the bottom face of `c`. -/ def valley (cs : ι → cube (n+1)) (c : cube (n+1)) : Prop := c.bottom ⊆ (⋃(i : ι), (cs i).bottom) ∧ (∀i, (cs i).b 0 = c.b 0 → (∃x, x ∈ (cs i).tail.to_set ∩ c.tail.to_set) → (cs i).tail.to_set ⊆ c.tail.to_set) ∧ ∀(i : ι), (cs i).b 0 = c.b 0 → (cs i).w ≠ c.w variables {c : cube (n+1)} (v : valley cs c) /-- The bottom of the unit cube is a valley -/ lemma valley_unit_cube (h : correct cs) : valley cs unit_cube := begin refine ⟨_, _, _⟩, { intro v, simp only [bottom, and_imp, mem_Union, mem_set_of_eq], intros h0 hv, have : v ∈ (unit_cube : cube (n+1)).to_set, { dsimp only [to_set, unit_cube, mem_set_of_eq], rw [forall_fin_succ, h0], split, norm_num [side, unit_cube], exact hv }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i, rfl⟩, hi⟩, use i, split, { apply le_antisymm, rw h0, exact zero_le_b h, exact (hi 0).1 }, intro j, exact hi _ }, { intros i hi h', rw to_set_subset, intro j, convert side_subset h using 1, simp [side_tail] }, { intros i hi, exact w_ne_one h i } end /-- the cubes which lie in the valley `c` -/ def bcubes (cs : ι → cube (n+1)) (c : cube (n+1)) : set ι := { i : ι | (cs i).b 0 = c.b 0 ∧ (cs i).tail.to_set ⊆ c.tail.to_set } /-- A cube which lies on the boundary of a valley in dimension `j` -/ def on_boundary (hi : i ∈ bcubes cs c) (j : fin n) : Prop := c.b j.succ = (cs i).b j.succ ∨ (cs i).b j.succ + (cs i).w = c.b j.succ + c.w lemma tail_sub (hi : i ∈ bcubes cs c) : ∀j, (cs i).tail.side j ⊆ c.tail.side j := by { rw [←to_set_subset], exact hi.2 } lemma bottom_mem_side (hi : i ∈ bcubes cs c) : c.b 0 ∈ (cs i).side 0 := by { convert b_mem_side (cs i) _ using 1, rw hi.1 } lemma b_le_b (hi : i ∈ bcubes cs c) (j : fin n) : c.b j.succ ≤ (cs i).b j.succ := (tail_sub hi j $ b_mem_side _ _).1 lemma t_le_t (hi : i ∈ bcubes cs c) (j : fin n) : (cs i).b j.succ + (cs i).w ≤ c.b j.succ + c.w := begin have h' := tail_sub hi j, dsimp only [side] at h', rw [Ico_subset_Ico_iff] at h', exact h'.2, simp [hw] end include h v /-- Every cube in the valley must be smaller than it -/ lemma w_lt_w (hi : i ∈ bcubes cs c) : (cs i).w < c.w := begin apply lt_of_le_of_ne _ (v.2.2 i hi.1), have j : fin n := ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩, rw [←add_le_add_iff_left ((cs i).b j.succ)], apply le_trans (t_le_t hi j), rw [add_le_add_iff_right], apply b_le_b hi, end open cardinal /-- There are at least two cubes in a valley -/ lemma two_le_mk_bcubes : 2 ≤ #(bcubes cs c) := begin rw [two_le_iff], rcases v.1 c.b_mem_bottom with ⟨_, ⟨i, rfl⟩, hi⟩, have h2i : i ∈ bcubes cs c := ⟨hi.1.symm, v.2.1 i hi.1.symm ⟨tail c.b, hi.2, λ j, c.b_mem_side j.succ⟩⟩, let j : fin (n+1) := ⟨2, h.2.2.2.2⟩, have hj : 0 ≠ j := by { simp only [fin.ext_iff, ne.def], contradiction }, let p : fin (n+1) → ℝ := λ j', if j' = j then c.b j + (cs i).w else c.b j', have hp : p ∈ c.bottom, { split, { simp only [bottom, p, if_neg hj] }, intro j', simp only [tail, side_tail], by_cases hj' : j'.succ = j, { simp [p, -add_comm, if_pos, side, hj', hw', w_lt_w h v h2i] }, { simp [p, -add_comm, if_neg hj'] }}, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, refine ⟨⟨i, h2i⟩, ⟨i', h2i'⟩, _⟩, intro hii', cases congr_arg subtype.val hii', apply not_le_of_lt (hi'.2 ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩).2, simp only [-add_comm, tail, cube.tail, p], rw [if_pos, add_le_add_iff_right], { exact (hi.2 _).1 }, refl end /-- There is a cube in the valley -/ lemma nonempty_bcubes : (bcubes cs c).nonempty := begin rw [←set.ne_empty_iff_nonempty], intro h', have := two_le_mk_bcubes h v, rw h' at this, apply not_lt_of_le this, rw mk_emptyc, norm_cast, norm_num end /-- There is a smallest cube in the valley -/ lemma exists_mi : ∃(i : ι), i ∈ bcubes cs c ∧ ∀(i' ∈ bcubes cs c), (cs i).w ≤ (cs i').w := by simpa using (bcubes cs c).exists_min_image (λ i, (cs i).w) (set.to_finite _) (nonempty_bcubes h v) /-- We let `mi` be the (index for the) smallest cube in the valley `c` -/ def mi : ι := classical.some $ exists_mi h v variables {h v} lemma mi_mem_bcubes : mi h v ∈ bcubes cs c := (classical.some_spec $ exists_mi h v).1 lemma mi_minimal (hi : i ∈ bcubes cs c) : (cs $ mi h v).w ≤ (cs i).w := (classical.some_spec $ exists_mi h v).2 i hi lemma mi_strict_minimal (hii' : mi h v ≠ i) (hi : i ∈ bcubes cs c) : (cs $ mi h v).w < (cs i).w := by { apply lt_of_le_of_ne (mi_minimal hi), apply h.2.2.1.ne, apply hii' } /-- The top of `mi` cannot be 1, since there is a larger cube in the valley -/ lemma mi_xm_ne_one : (cs $ mi h v).xm ≠ 1 := begin apply ne_of_lt, rcases (two_le_iff' _).mp (two_le_mk_bcubes h v) with ⟨⟨i, hi⟩, h2i⟩, swap, exact ⟨mi h v, mi_mem_bcubes⟩, apply lt_of_lt_of_le _ (b_add_w_le_one h), exact i, exact 0, rw [xm, mi_mem_bcubes.1, hi.1, _root_.add_lt_add_iff_left], apply mi_strict_minimal _ hi, intro h', apply h2i, rw subtype.ext_iff_val, exact h' end /-- If `mi` lies on the boundary of the valley in dimension j, then this lemma expresses that all other cubes on the same boundary extend further from the boundary. More precisely, there is a j-th coordinate `x : ℝ` in the valley, but not in `mi`, such that every cube that shares a (particular) j-th coordinate with `mi` also contains j-th coordinate `x` -/ lemma smallest_on_boundary {j} (bi : on_boundary (mi_mem_bcubes : mi h v ∈ _) j) : ∃(x : ℝ), x ∈ c.side j.succ \ (cs $ mi h v).side j.succ ∧ ∀{{i'}} (hi' : i' ∈ bcubes cs c), i' ≠ mi h v → (cs $ mi h v).b j.succ ∈ (cs i').side j.succ → x ∈ (cs i').side j.succ := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, cases bi, { refine ⟨(cs i).b j.succ + (cs i).w, ⟨_, _⟩, _⟩, { simp [side, bi, hw', w_lt_w h v hi] }, { intro h', simpa [i, lt_irrefl] using h'.2 }, intros i' hi' i'_i h2i', split, apply le_trans h2i'.1, { simp [hw'] }, apply lt_of_lt_of_le (add_lt_add_left (mi_strict_minimal i'_i.symm hi') _), simp [bi.symm, b_le_b hi'] }, let s := bcubes cs c \ { i }, have hs : s.nonempty, { rcases (two_le_iff' (⟨i, hi⟩ : bcubes cs c)).mp (two_le_mk_bcubes h v) with ⟨⟨i', hi'⟩, h2i'⟩, refine ⟨i', hi', _⟩, simp only [mem_singleton_iff], intro h, apply h2i', simp [h] }, rcases set.exists_min_image s (w ∘ cs) (set.to_finite _) hs with ⟨i', ⟨hi', h2i'⟩, h3i'⟩, rw [mem_singleton_iff] at h2i', let x := c.b j.succ + c.w - (cs i').w, have hx : x < (cs i).b j.succ, { dsimp only [x], rw [←bi, add_sub_assoc, add_lt_iff_neg_left, sub_lt_zero], apply mi_strict_minimal (ne.symm h2i') hi' }, refine ⟨x, ⟨_, _⟩, _⟩, { simp only [side, x, -add_comm, -add_assoc, neg_lt_zero, hw, add_lt_iff_neg_left, and_true, mem_Ico, sub_eq_add_neg], rw [add_assoc, le_add_iff_nonneg_right, ←sub_eq_add_neg, sub_nonneg], apply le_of_lt (w_lt_w h v hi') }, { simp only [side, not_and_distrib, not_lt, add_comm, not_le, mem_Ico], left, exact hx }, intros i'' hi'' h2i'' h3i'', split, swap, apply lt_trans hx h3i''.2, simp only [x], rw [le_sub_iff_add_le], refine le_trans _ (t_le_t hi'' j), rw [add_le_add_iff_left], apply h3i' i'' ⟨hi'', _⟩, simp [mem_singleton, h2i''] end variables (h v) /-- `mi` cannot lie on the boundary of the valley. Otherwise, the cube adjacent to it in the `j`-th direction will intersect one of the neighbouring cubes on the same boundary as `mi`. -/ lemma mi_not_on_boundary (j : fin n) : ¬on_boundary (mi_mem_bcubes : mi h v ∈ _) j := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, rcases (two_le_iff' j).mp _ with ⟨j', hj'⟩, swap, { rw [mk_fin, ←nat.cast_two, nat_cast_le], apply nat.le_of_succ_le_succ h.2.2.2.2 }, intro hj, rcases smallest_on_boundary hj with ⟨x, ⟨hx, h2x⟩, h3x⟩, let p : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j then x else (cs i).b j₂.succ), have hp : p ∈ c.bottom, { suffices : ∀ (j' : fin n), ite (j' = j) x ((cs i).b j'.succ) ∈ c.side j'.succ, { simpa [bottom, p, to_set, tail, side_tail] }, intro j₂, by_cases hj₂ : j₂ = j, { simp [hj₂, hx] }, simp only [hj₂, if_false], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, have i_i' : i ≠ i', { rintro rfl, simpa [p, side_tail, i, h2x] using hi'.2 j }, have : nonempty ↥((cs i').tail.side j' \ (cs i).tail.side j'), { apply nonempty_Ico_sdiff, apply mi_strict_minimal i_i' h2i', apply hw }, rcases this with ⟨⟨x', hx'⟩⟩, let p' : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j' then x' else (cs i).b j₂.succ), have hp' : p' ∈ c.bottom, { suffices : ∀ (j : fin n), ite (j = j') x' ((cs i).b j.succ) ∈ c.side j.succ, { simpa [bottom, p', to_set, tail, side_tail] }, intro j₂, by_cases hj₂ : j₂ = j', simp [hj₂], apply tail_sub h2i', apply hx'.1, simp only [if_congr, if_false, hj₂], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp' with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c := ⟨hi''.1.symm, v.2.1 i'' hi''.1.symm ⟨tail p', hi''.2, hp'.2⟩⟩, have i'_i'' : i' ≠ i'', { rintro ⟨⟩, have : (cs i).b ∈ (cs i').to_set, { simp only [to_set, forall_fin_succ, hi.1, bottom_mem_side h2i', true_and, mem_set_of_eq], intro j₂, by_cases hj₂ : j₂ = j, { simpa [side_tail, p', hj', hj₂] using hi''.2 j }, { simpa [hj₂] using hi'.2 j₂ } }, apply not_disjoint_iff.mpr ⟨(cs i).b, (cs i).b_mem_to_set, this⟩ (h.1 i i' i_i') }, have i_i'' : i ≠ i'', { intro h, induction h, simpa [hx'.2] using hi''.2 j' }, apply not.elim _ (h.1 i' i'' i'_i''), simp only [on_fun, to_set_disjoint, not_disjoint_iff, forall_fin_succ, not_exists, comp_app], refine ⟨⟨c.b 0, bottom_mem_side h2i', bottom_mem_side h2i''⟩, _⟩, intro j₂, by_cases hj₂ : j₂ = j, { cases hj₂, refine ⟨x, _, _⟩, { convert hi'.2 j, simp [p] }, apply h3x h2i'' i_i''.symm, convert hi''.2 j, simp [p', hj'] }, by_cases h2j₂ : j₂ = j', { cases h2j₂, refine ⟨x', hx'.1, _⟩, convert hi''.2 j', simp }, refine ⟨(cs i).b j₂.succ, _, _⟩, { convert hi'.2 j₂, simp [hj₂] }, { convert hi''.2 j₂, simp [h2j₂] } end variables {h v} /-- The same result that `mi` cannot lie on the boundary of the valley written as inequalities. -/ lemma mi_not_on_boundary' (j : fin n) : c.tail.b j < (cs (mi h v)).tail.b j ∧ (cs (mi h v)).tail.b j + (cs (mi h v)).w < c.tail.b j + c.w := begin have := mi_not_on_boundary h v j, simp only [on_boundary, not_or_distrib] at this, cases this with h1 h2, split, apply lt_of_le_of_ne (b_le_b mi_mem_bcubes _) h1, apply lt_of_le_of_ne _ h2, apply ((Ico_subset_Ico_iff _).mp (tail_sub mi_mem_bcubes j)).2, simp [hw] end /-- The top of `mi` gives rise to a new valley, since the neighbouring cubes extend further upward than `mi`. -/ def valley_mi : valley cs ((cs (mi h v)).shift_up) := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, refine ⟨_, _, _⟩, { intro p, apply shift_up_bottom_subset_bottoms h mi_xm_ne_one }, { rintros i' hi' ⟨p2, hp2, h2p2⟩, simp only [head_shift_up] at hi', classical, by_contra h2i', rw [tail_shift_up] at h2p2, simp only [not_subset, tail_shift_up] at h2i', rcases h2i' with ⟨p1, hp1, h2p1⟩, have : ∃p3, p3 ∈ (cs i').tail.to_set ∧ p3 ∉ (cs i).tail.to_set ∧ p3 ∈ c.tail.to_set, { simp only [to_set, not_forall, mem_set_of_eq] at h2p1, cases h2p1 with j hj, rcases Ico_lemma (mi_not_on_boundary' j).1 (by simp [hw]) (mi_not_on_boundary' j).2 (le_trans (hp2 j).1 $ le_of_lt (h2p2 j).2) (le_trans (h2p2 j).1 $ le_of_lt (hp2 j).2) ⟨hj, hp1 j⟩ with ⟨w, hw, h2w, h3w⟩, refine ⟨λ j', if j' = j then w else p2 j', _, _, _⟩, { intro j', by_cases h : j' = j, { simp only [if_pos h], convert h3w }, { simp only [if_neg h], exact hp2 j' } }, { simp only [to_set, not_forall, mem_set_of_eq], use j, rw [if_pos rfl], convert h2w }, { intro j', by_cases h : j' = j, { simp only [if_pos h, side_tail], convert hw }, { simp only [if_neg h], apply hi.2, apply h2p2 } } }, rcases this with ⟨p3, h1p3, h2p3, h3p3⟩, let p := @cons n (λ_, ℝ) (c.b 0) p3, have hp : p ∈ c.bottom, { refine ⟨rfl, _⟩, rwa [tail_cons] }, rcases v.1 hp with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c, { use hi''.1.symm, apply v.2.1 i'' hi''.1.symm, use tail p, split, exact hi''.2, rw [tail_cons], exact h3p3 }, have h3i'' : (cs i).w < (cs i'').w, { apply mi_strict_minimal _ h2i'', rintro rfl, apply h2p3, convert hi''.2, rw [tail_cons] }, let p' := @cons n (λ_, ℝ) (cs i).xm p3, have hp' : p' ∈ (cs i').to_set, { simpa [to_set, forall_fin_succ, p', hi'.symm] using h1p3 }, have h2p' : p' ∈ (cs i'').to_set, { simp only [to_set, forall_fin_succ, p', cons_succ, cons_zero, mem_set_of_eq], refine ⟨_, by simpa [to_set, p] using hi''.2⟩, have : (cs i).b 0 = (cs i'').b 0, { rw [hi.1, h2i''.1] }, simp [side, hw', xm, this, h3i''] }, apply not_disjoint_iff.mpr ⟨p', hp', h2p'⟩, apply h.1, rintro rfl, apply (cs i).b_ne_xm, rw [←hi', ←hi''.1, hi.1], refl }, { intros i' hi' h2i', dsimp only [shift_up] at h2i', replace h2i' := h.2.2.1 h2i'.symm, induction h2i', exact b_ne_xm (cs i) hi' } end variables (h) omit v /-- We get a sequence of cubes whose size is decreasing -/ noncomputable def sequence_of_cubes : ℕ → { i : ι // valley cs ((cs i).shift_up) } | 0 := let v := valley_unit_cube h in ⟨mi h v, valley_mi⟩ | (k+1) := let v := (sequence_of_cubes k).2 in ⟨mi h v, valley_mi⟩ def decreasing_sequence (k : ℕ) : ℝ := (cs (sequence_of_cubes h k).1).w lemma strict_anti_sequence_of_cubes : strict_anti $ decreasing_sequence h := strict_anti_nat_of_succ_lt $ λ k, begin let v := (sequence_of_cubes h k).2, dsimp only [decreasing_sequence, sequence_of_cubes], apply w_lt_w h v (mi_mem_bcubes : mi h v ∈ _), end omit h /-- The infinite sequence of cubes contradicts the finiteness of the family. -/ theorem not_correct : ¬correct cs := begin intro h, apply (lt_aleph_0_of_finite ι).not_le, rw [aleph_0, lift_id], fapply mk_le_of_injective, exact λ n, (sequence_of_cubes h n).1, intros n m hnm, apply (strict_anti_sequence_of_cubes h).injective, dsimp only [decreasing_sequence], rw hnm end /-- **Dissection of Cubes**: A cube cannot be cubed. -/ theorem cannot_cube_a_cube : ∀{n : ℕ}, n ≥ 3 → -- In ℝ^n for n ≥ 3 ∀{ι : Type} [fintype ι] {cs : ι → cube n}, -- given a finite collection of (hyper)cubes 2 ≤ #ι → -- containing at least two elements pairwise (disjoint on (cube.to_set ∘ cs)) → -- which is pairwise disjoint (⋃(i : ι), (cs i).to_set) = unit_cube.to_set → -- whose union is the unit cube injective (cube.w ∘ cs) → -- such that the widths of all cubes are different false := -- then we can derive a contradiction begin intros n hn ι hι cs h1 h2 h3 h4, resetI, rcases n, cases hn, exact not_correct ⟨h2, h3, h4, h1, hn⟩ end
58b260337c2335a2f565aafebbf3c99d9b457703
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/set_theory/pgame.lean
e199e3b9077bea3299bcb4912e532cedfc978074
[ "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
42,378
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import logic.embedding import data.nat.cast import data.fin /-! # Combinatorial (pre-)games. The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We construct "pregames", define an ordering and arithmetic operations on them, then show that the operations descend to "games", defined via the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`. The surreal numbers will be built as a quotient of a subtype of pregames. A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two types (thought of as indexing the the possible moves for the players Left and Right), and a pair of functions out of these types to `pgame` (thought of as describing the resulting game after making a move). Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`. ## Conway induction By construction, the induction principle for pregames is exactly "Conway induction". That is, to prove some predicate `pgame → Prop` holds for all pregames, it suffices to prove that for every pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds for `g`. While it is often convenient to work "by induction" on pregames, in some situations this becomes awkward, so we also define accessor functions `left_moves`, `right_moves`, `move_left` and `move_right`. There is a relation `subsequent p q`, saying that `p` can be reached by playing some non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying on this relation. ## Order properties Pregames have both a `≤` and a `<` relation, which are related in quite a subtle way. In particular, it is worth noting that in Lean's (perhaps unfortunate?) definition of a `preorder`, we have `lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)`, but this is _not_ satisfied by the usual `≤` and `<` relations on pregames. (It is satisfied once we restrict to the surreal numbers.) In particular, `<` is not transitive; there is an example below showing `0 < star ∧ star < 0`. We do have ``` theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := ... theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := ... ``` The statement `0 ≤ x` means that Left has a good response to any move by Right; in particular, the theorem `zero_le` below states ``` 0 ≤ x ↔ ∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i ``` On the other hand the statement `0 < x` means that Left has a good move right now; in particular the theorem `zero_lt` below states ``` 0 < x ↔ ∃ i : left_moves x, ∀ j : right_moves (x.move_left i), 0 < (x.move_left i).move_right j ``` The theorems `le_def`, `lt_def`, give a recursive characterisation of each relation, in terms of themselves two moves later. The theorems `le_def_lt` and `lt_def_lt` give recursive characterisations of each relation in terms of the other relation one move later. We define an equivalence relation `equiv p q ↔ p ≤ q ∧ q ≤ p`. Later, games will be defined as the quotient by this relation. ## Algebraic structures We next turn to defining the operations necessary to make games into a commutative additive group. Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR + y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$. The order structures interact in the expected way with addition, so we have ``` theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry ``` We show that these operations respect the equivalence relation, and hence descend to games. At the level of games, these operations satisfy all the laws of a commutative group. To prove the necessary equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`. ## Future work * The theory of dominated and reversible positions, and unique normal form for short games. * Analysis of basic domineering positions. * Hex. * Temperature. * The development of surreal numbers, based on this development of combinatorial games, is still quite incomplete. ## References The material here is all drawn from * [Conway, *On numbers and games*][conway2001] An interested reader may like to formalise some of the material from * [Andreas Blass, *A game semantics for linear logic*][MR1167694] * [André Joyal, *Remarques sur la théorie des jeux à deux personnes*][joyal1997] -/ universes u /-- The type of pre-games, before we have quotiented by extensionality. In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a pre-game is built inductively from two families of pre-games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. -/ inductive pgame : Type (u+1) | mk : ∀ α β : Type u, (α → pgame) → (β → pgame) → pgame namespace pgame /-- Construct a pre-game from list of pre-games describing the available moves for Left and Right. -/ -- TODO provide some API describing the interaction with -- `left_moves`, `right_moves`, `move_left` and `move_right` below. -- TODO define this at the level of games, as well, and perhaps also for finsets of games. def of_lists (L R : list pgame.{0}) : pgame.{0} := pgame.mk (fin L.length) (fin R.length) (λ i, L.nth_le i i.is_lt) (λ j, R.nth_le j.val j.is_lt) /-- The indexing type for allowable moves by Left. -/ def left_moves : pgame → Type u | (mk l _ _ _) := l /-- The indexing type for allowable moves by Right. -/ def right_moves : pgame → Type u | (mk _ r _ _) := r /-- The new game after Left makes an allowed move. -/ def move_left : Π (g : pgame), left_moves g → pgame | (mk l _ L _) i := L i /-- The new game after Right makes an allowed move. -/ def move_right : Π (g : pgame), right_moves g → pgame | (mk _ r _ R) j := R j @[simp] lemma left_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).left_moves = xl := rfl @[simp] lemma move_left_mk {xl xr xL xR i} : (⟨xl, xr, xL, xR⟩ : pgame).move_left i = xL i := rfl @[simp] lemma right_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).right_moves = xr := rfl @[simp] lemma move_right_mk {xl xr xL xR j} : (⟨xl, xr, xL, xR⟩ : pgame).move_right j = xR j := rfl /-- `subsequent p q` says that `p` can be obtained by playing some nonempty sequence of moves from `q`. -/ inductive subsequent : pgame → pgame → Prop | left : Π (x : pgame) (i : x.left_moves), subsequent (x.move_left i) x | right : Π (x : pgame) (j : x.right_moves), subsequent (x.move_right j) x | trans : Π (x y z : pgame), subsequent x y → subsequent y z → subsequent x z theorem wf_subsequent : well_founded subsequent := ⟨λ x, begin induction x with l r L R IHl IHr, refine ⟨_, λ y h, _⟩, generalize_hyp e : mk l r L R = x at h, induction h with _ i _ j a b _ h1 h2 IH1 IH2; subst e, { apply IHl }, { apply IHr }, { exact acc.inv (IH2 rfl) h1 } end⟩ instance : has_well_founded pgame := { r := subsequent, wf := wf_subsequent } /-- A move by Left produces a subsequent game. (For use in pgame_wf_tac.) -/ lemma subsequent.left_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {i : xl} : subsequent (xL i) (mk xl xr xL xR) := subsequent.left (mk xl xr xL xR) i /-- A move by Right produces a subsequent game. (For use in pgame_wf_tac.) -/ lemma subsequent.right_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {j : xr} : subsequent (xR j) (mk xl xr xL xR) := subsequent.right (mk xl xr xL xR) j /-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/ meta def pgame_wf_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right, subsequent.left_move, subsequent.right_move, subsequent.left, subsequent.right, subsequent.trans] { max_depth := 6 }] /-- The pre-game `zero` is defined by `0 = { | }`. -/ instance : has_zero pgame := ⟨⟨pempty, pempty, pempty.elim, pempty.elim⟩⟩ @[simp] lemma zero_left_moves : (0 : pgame).left_moves = pempty := rfl @[simp] lemma zero_right_moves : (0 : pgame).right_moves = pempty := rfl instance : inhabited pgame := ⟨0⟩ /-- The pre-game `one` is defined by `1 = { 0 | }`. -/ instance : has_one pgame := ⟨⟨punit, pempty, λ _, 0, pempty.elim⟩⟩ @[simp] lemma one_left_moves : (1 : pgame).left_moves = punit := rfl @[simp] lemma one_move_left : (1 : pgame).move_left punit.star = 0 := rfl @[simp] lemma one_right_moves : (1 : pgame).right_moves = pempty := rfl /-- Define simultaneously by mutual induction the `<=` and `<` relation on pre-games. The ZFC definition says that `x = {xL | xR}` is less or equal to `y = {yL | yR}` if `∀ x₁ ∈ xL, x₁ < y` and `∀ y₂ ∈ yR, x < y₂`, where `x < y` is the same as `¬ y <= x`. This is a tricky induction because it only decreases one side at a time, and it also swaps the arguments in the definition of `<`. The solution is to define `x < y` and `x <= y` simultaneously. -/ def le_lt : Π (x y : pgame), Prop × Prop | (mk xl xr xL xR) (mk yl yr yL yR) := -- the orderings of the clauses here are carefully chosen so that -- and.left/or.inl refer to moves by Left, and -- and.right/or.inr refer to moves by Right. ((∀ i : xl, (le_lt (xL i) ⟨yl, yr, yL, yR⟩).2) ∧ (∀ j : yr, (le_lt ⟨xl, xr, xL, xR⟩ (yR j)).2), (∃ i : yl, (le_lt ⟨xl, xr, xL, xR⟩ (yL i)).1) ∨ (∃ j : xr, (le_lt (xR j) ⟨yl, yr, yL, yR⟩).1)) using_well_founded { dec_tac := pgame_wf_tac } instance : has_le pgame := ⟨λ x y, (le_lt x y).1⟩ instance : has_lt pgame := ⟨λ x y, (le_lt x y).2⟩ /-- Definition of `x ≤ y` on pre-games built using the constructor. -/ @[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} : (⟨xl, xr, xL, xR⟩ : pgame) ≤ ⟨yl, yr, yL, yR⟩ ↔ (∀ i, xL i < ⟨yl, yr, yL, yR⟩) ∧ (∀ j, (⟨xl, xr, xL, xR⟩ : pgame) < yR j) := show (le_lt _ _).1 ↔ _, by { rw le_lt, refl } /-- Definition of `x ≤ y` on pre-games, in terms of `<` -/ theorem le_def_lt {x y : pgame} : x ≤ y ↔ (∀ i : x.left_moves, x.move_left i < y) ∧ (∀ j : y.right_moves, x < y.move_right j) := by { cases x, cases y, rw mk_le_mk, refl } /-- Definition of `x < y` on pre-games built using the constructor. -/ @[simp] theorem mk_lt_mk {xl xr xL xR yl yr yL yR} : (⟨xl, xr, xL, xR⟩ : pgame) < ⟨yl, yr, yL, yR⟩ ↔ (∃ i, (⟨xl, xr, xL, xR⟩ : pgame) ≤ yL i) ∨ (∃ j, xR j ≤ ⟨yl, yr, yL, yR⟩) := show (le_lt _ _).2 ↔ _, by { rw le_lt, refl } /-- Definition of `x < y` on pre-games, in terms of `≤` -/ theorem lt_def_le {x y : pgame} : x < y ↔ (∃ i : y.left_moves, x ≤ y.move_left i) ∨ (∃ j : x.right_moves, x.move_right j ≤ y) := by { cases x, cases y, rw mk_lt_mk, refl } /-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. -/ theorem le_def {x y : pgame} : x ≤ y ↔ (∀ i : x.left_moves, (∃ i' : y.left_moves, x.move_left i ≤ y.move_left i') ∨ (∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ y)) ∧ (∀ j : y.right_moves, (∃ i : (y.move_right j).left_moves, x ≤ (y.move_right j).move_left i) ∨ (∃ j' : x.right_moves, x.move_right j' ≤ y.move_right j)) := begin rw [le_def_lt], conv { to_lhs, simp only [lt_def_le] }, end /-- The definition of `x < y` on pre-games, in terms of `<` two moves later. -/ theorem lt_def {x y : pgame} : x < y ↔ (∃ i : y.left_moves, (∀ i' : x.left_moves, x.move_left i' < y.move_left i) ∧ (∀ j : (y.move_left i).right_moves, x < (y.move_left i).move_right j)) ∨ (∃ j : x.right_moves, (∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < y) ∧ (∀ j' : y.right_moves, x.move_right j < y.move_right j')) := begin rw [lt_def_le], conv { to_lhs, simp only [le_def_lt] }, end /-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/ theorem le_zero {x : pgame} : x ≤ 0 ↔ ∀ i : x.left_moves, ∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ 0 := begin rw le_def, dsimp, simp [forall_pempty, exists_pempty] end /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/ theorem zero_le {x : pgame} : 0 ≤ x ↔ ∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i := begin rw le_def, dsimp, simp [forall_pempty, exists_pempty] end /-- The definition of `x < 0` on pre-games, in terms of `< 0` two moves later. -/ theorem lt_zero {x : pgame} : x < 0 ↔ ∃ j : x.right_moves, ∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < 0 := begin rw lt_def, dsimp, simp [forall_pempty, exists_pempty] end /-- The definition of `0 < x` on pre-games, in terms of `< x` two moves later. -/ theorem zero_lt {x : pgame} : 0 < x ↔ ∃ i : x.left_moves, ∀ j : (x.move_left i).right_moves, 0 < (x.move_left i).move_right j := begin rw lt_def, dsimp, simp [forall_pempty, exists_pempty] end /-- Given a right-player-wins game, provide a response to any move by left. -/ noncomputable def right_response {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).right_moves := classical.some $ (le_zero.1 h) i /-- Show that the response for right provided by `right_response` preserves the right-player-wins condition. -/ lemma right_response_spec {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).move_right (right_response h i) ≤ 0 := classical.some_spec $ (le_zero.1 h) i /-- Given a left-player-wins game, provide a response to any move by right. -/ noncomputable def left_response {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : (x.move_right j).left_moves := classical.some $ (zero_le.1 h) j /-- Show that the response for left provided by `left_response` preserves the left-player-wins condition. -/ lemma left_response_spec {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : 0 ≤ (x.move_right j).move_left (left_response h j) := classical.some_spec $ (zero_le.1 h) j theorem lt_of_le_mk {xl xr xL xR y i} : (⟨xl, xr, xL, xR⟩ : pgame) ≤ y → xL i < y := by { cases y, rw mk_le_mk, tauto } theorem lt_of_mk_le {x : pgame} {yl yr yL yR i} : x ≤ ⟨yl, yr, yL, yR⟩ → x < yR i := by { cases x, rw mk_le_mk, tauto } theorem mk_lt_of_le {xl xr xL xR y i} : (by exact xR i ≤ y) → (⟨xl, xr, xL, xR⟩ : pgame) < y := by { cases y, rw mk_lt_mk, tauto } theorem lt_mk_of_le {x : pgame} {yl yr yL yR i} : (by exact x ≤ yL i) → x < ⟨yl, yr, yL, yR⟩ := by { cases x, rw mk_lt_mk, exact λ h, or.inl ⟨_, h⟩ } theorem not_le_lt {x y : pgame} : (¬ x ≤ y ↔ y < x) ∧ (¬ x < y ↔ y ≤ x) := begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, classical, simp only [mk_le_mk, mk_lt_mk, not_and_distrib, not_or_distrib, not_forall, not_exists, and_comm, or_comm, IHxl, IHxr, IHyl, IHyr, iff_self, and_self] end theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := not_le_lt.1 theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := not_le_lt.2 @[refl] theorem le_refl : ∀ x : pgame, x ≤ x | ⟨l, r, L, R⟩ := by rw mk_le_mk; exact ⟨λ i, lt_mk_of_le (le_refl _), λ i, mk_lt_of_le (le_refl _)⟩ theorem lt_irrefl (x : pgame) : ¬ x < x := not_lt.2 (le_refl _) theorem ne_of_lt : ∀ {x y : pgame}, x < y → x ≠ y | x _ h rfl := lt_irrefl x h theorem le_trans_aux {xl xr} {xL : xl → pgame} {xR : xr → pgame} {yl yr} {yL : yl → pgame} {yR : yr → pgame} {zl zr} {zL : zl → pgame} {zR : zr → pgame} (h₁ : ∀ i, mk yl yr yL yR ≤ mk zl zr zL zR → mk zl zr zL zR ≤ xL i → mk yl yr yL yR ≤ xL i) (h₂ : ∀ i, zR i ≤ mk xl xr xL xR → mk xl xr xL xR ≤ mk yl yr yL yR → zR i ≤ mk yl yr yL yR) : mk xl xr xL xR ≤ mk yl yr yL yR → mk yl yr yL yR ≤ mk zl zr zL zR → mk xl xr xL xR ≤ mk zl zr zL zR := by simp only [mk_le_mk] at *; exact λ ⟨xLy, xyR⟩ ⟨yLz, yzR⟩, ⟨ λ i, not_le.1 (λ h, not_lt.2 (h₁ _ ⟨yLz, yzR⟩ h) (xLy _)), λ i, not_le.1 (λ h, not_lt.2 (h₂ _ h ⟨xLy, xyR⟩) (yzR _))⟩ @[trans] theorem le_trans {x y z : pgame} : x ≤ y → y ≤ z → x ≤ z := suffices ∀ {x y z : pgame}, (x ≤ y → y ≤ z → x ≤ z) ∧ (y ≤ z → z ≤ x → y ≤ x) ∧ (z ≤ x → x ≤ y → z ≤ y), from this.1, begin clear x y z, intros, induction x with xl xr xL xR IHxl IHxr generalizing y z, induction y with yl yr yL yR IHyl IHyr generalizing z, induction z with zl zr zL zR IHzl IHzr, exact ⟨ le_trans_aux (λ i, (IHxl _).2.1) (λ i, (IHzr _).2.2), le_trans_aux (λ i, (IHyl _).2.2) (λ i, (IHxr _).1), le_trans_aux (λ i, (IHzl _).1) (λ i, (IHyr _).2.1)⟩, end @[trans] theorem lt_of_le_of_lt {x y z : pgame} (hxy : x ≤ y) (hyz : y < z) : x < z := begin rw ←not_le at ⊢ hyz, exact mt (λ H, le_trans H hxy) hyz end @[trans] theorem lt_of_lt_of_le {x y z : pgame} (hxy : x < y) (hyz : y ≤ z) : x < z := begin rw ←not_le at ⊢ hxy, exact mt (λ H, le_trans hyz H) hxy end /-- Define the equivalence relation on pre-games. Two pre-games `x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. -/ def equiv (x y : pgame) : Prop := x ≤ y ∧ y ≤ x local infix ` ≈ ` := pgame.equiv @[refl, simp] theorem equiv_refl (x) : x ≈ x := ⟨le_refl _, le_refl _⟩ @[symm] theorem equiv_symm {x y} : x ≈ y → y ≈ x | ⟨xy, yx⟩ := ⟨yx, xy⟩ @[trans] theorem equiv_trans {x y z} : x ≈ y → y ≈ z → x ≈ z | ⟨xy, yx⟩ ⟨yz, zy⟩ := ⟨le_trans xy yz, le_trans zy yx⟩ theorem lt_of_lt_of_equiv {x y z} (h₁ : x < y) (h₂ : y ≈ z) : x < z := lt_of_lt_of_le h₁ h₂.1 theorem le_of_le_of_equiv {x y z} (h₁ : x ≤ y) (h₂ : y ≈ z) : x ≤ z := le_trans h₁ h₂.1 theorem lt_of_equiv_of_lt {x y z} (h₁ : x ≈ y) (h₂ : y < z) : x < z := lt_of_le_of_lt h₁.1 h₂ theorem le_of_equiv_of_le {x y z} (h₁ : x ≈ y) (h₂ : y ≤ z) : x ≤ z := le_trans h₁.1 h₂ theorem le_congr {x₁ y₁ x₂ y₂} : x₁ ≈ x₂ → y₁ ≈ y₂ → (x₁ ≤ y₁ ↔ x₂ ≤ y₂) | ⟨x12, x21⟩ ⟨y12, y21⟩ := ⟨λ h, le_trans x21 (le_trans h y12), λ h, le_trans x12 (le_trans h y21)⟩ theorem lt_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ < y₁ ↔ x₂ < y₂ := not_le.symm.trans $ (not_congr (le_congr hy hx)).trans not_le theorem equiv_congr_left {y₁ y₂} : y₁ ≈ y₂ ↔ ∀ x₁, x₁ ≈ y₁ ↔ x₁ ≈ y₂ := ⟨λ h x₁, ⟨λ h', equiv_trans h' h, λ h', equiv_trans h' (equiv_symm h)⟩, λ h, (h y₁).1 $ equiv_refl _⟩ theorem equiv_congr_right {x₁ x₂} : x₁ ≈ x₂ ↔ ∀ y₁, x₁ ≈ y₁ ↔ x₂ ≈ y₁ := ⟨λ h y₁, ⟨λ h', equiv_trans (equiv_symm h) h', λ h', equiv_trans h h'⟩, λ h, (h x₂).2 $ equiv_refl _⟩ theorem equiv_of_mk_equiv {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves) (hl : ∀ (i : x.left_moves), x.move_left i ≈ y.move_left (L i)) (hr : ∀ (j : y.right_moves), x.move_right (R.symm j) ≈ y.move_right j) : x ≈ y := begin fsplit; rw le_def, { exact ⟨λ i, or.inl ⟨L i, (hl i).1⟩, λ j, or.inr ⟨R.symm j, (hr j).1⟩⟩ }, { fsplit, { intro i, left, specialize hl (L.symm i), simp only [move_left_mk, equiv.apply_symm_apply] at hl, use ⟨L.symm i, hl.2⟩ }, { intro j, right, specialize hr (R j), simp only [move_right_mk, equiv.symm_apply_apply] at hr, use ⟨R j, hr.2⟩ } } end /-- `restricted x y` says that Left always has no more moves in `x` than in `y`, and Right always has no more moves in `y` than in `x` -/ inductive restricted : pgame.{u} → pgame.{u} → Type (u+1) | mk : Π {x y : pgame} (L : x.left_moves → y.left_moves) (R : y.right_moves → x.right_moves), (∀ (i : x.left_moves), restricted (x.move_left i) (y.move_left (L i))) → (∀ (j : y.right_moves), restricted (x.move_right (R j)) (y.move_right j)) → restricted x y /-- The identity restriction. -/ @[refl] def restricted.refl : Π (x : pgame), restricted x x | (mk xl xr xL xR) := restricted.mk id id (λ i, restricted.refl _) (λ j, restricted.refl _) using_well_founded { dec_tac := pgame_wf_tac } -- TODO trans for restricted theorem restricted.le : Π {x y : pgame} (r : restricted x y), x ≤ y | (mk xl xr xL xR) (mk yl yr yL yR) (restricted.mk L_embedding R_embedding L_restriction R_restriction) := begin rw le_def, exact ⟨λ i, or.inl ⟨L_embedding i, (L_restriction i).le⟩, λ i, or.inr ⟨R_embedding i, (R_restriction i).le⟩⟩ end /-- `relabelling x y` says that `x` and `y` are really the same game, just dressed up differently. Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly for Right, and under these bijections we inductively have `relabelling`s for the consequent games. -/ inductive relabelling : pgame.{u} → pgame.{u} → Type (u+1) | mk : Π {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves), (∀ (i : x.left_moves), relabelling (x.move_left i) (y.move_left (L i))) → (∀ (j : y.right_moves), relabelling (x.move_right (R.symm j)) (y.move_right j)) → relabelling x y /-- If `x` is a relabelling of `y`, then Left and Right have the same moves in either game, so `x` is a restriction of `y`. -/ def relabelling.restricted: Π {x y : pgame} (r : relabelling x y), restricted x y | (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) := restricted.mk L_equiv.to_embedding R_equiv.symm.to_embedding (λ i, (L_relabelling i).restricted) (λ j, (R_relabelling j).restricted) -- It's not the case that `restricted x y → restricted y x → relabelling x y`, -- but if we insisted that the maps in a restriction were injective, then one -- could use Schröder-Bernstein for do this. /-- The identity relabelling. -/ @[refl] def relabelling.refl : Π (x : pgame), relabelling x x | (mk xl xr xL xR) := relabelling.mk (equiv.refl _) (equiv.refl _) (λ i, relabelling.refl _) (λ j, relabelling.refl _) using_well_founded { dec_tac := pgame_wf_tac } /-- Reverse a relabelling. -/ @[symm] def relabelling.symm : Π {x y : pgame}, relabelling x y → relabelling y x | (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) := begin refine relabelling.mk L_equiv.symm R_equiv.symm _ _, { intro i, simpa using (L_relabelling (L_equiv.symm i)).symm }, { intro j, simpa using (R_relabelling (R_equiv j)).symm } end /-- Transitivity of relabelling -/ @[trans] def relabelling.trans : Π {x y z : pgame}, relabelling x y → relabelling y z → relabelling x z | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) (relabelling.mk L_equiv₁ R_equiv₁ L_relabelling₁ R_relabelling₁) (relabelling.mk L_equiv₂ R_equiv₂ L_relabelling₂ R_relabelling₂) := begin refine relabelling.mk (L_equiv₁.trans L_equiv₂) (R_equiv₁.trans R_equiv₂) _ _, { intro i, simpa using (L_relabelling₁ _).trans (L_relabelling₂ _) }, { intro j, simpa using (R_relabelling₁ _).trans (R_relabelling₂ _) }, end theorem relabelling.le {x y : pgame} (r : relabelling x y) : x ≤ y := r.restricted.le /-- A relabelling lets us prove equivalence of games. -/ theorem relabelling.equiv {x y : pgame} (r : relabelling x y) : x ≈ y := ⟨r.le, r.symm.le⟩ instance {x y : pgame} : has_coe (relabelling x y) (x ≈ y) := ⟨relabelling.equiv⟩ /-- Replace the types indexing the next moves for Left and Right by equivalent types. -/ def relabel {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') := pgame.mk xl' xr' (λ i, x.move_left (el.symm i)) (λ j, x.move_right (er.symm j)) @[simp] lemma relabel_move_left' {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : xl') : move_left (relabel el er) i = x.move_left (el.symm i) := rfl @[simp] lemma relabel_move_left {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : x.left_moves) : move_left (relabel el er) (el i) = x.move_left i := by simp @[simp] lemma relabel_move_right' {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : xr') : move_right (relabel el er) j = x.move_right (er.symm j) := rfl @[simp] lemma relabel_move_right {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : x.right_moves) : move_right (relabel el er) (er j) = x.move_right j := by simp /-- The game obtained by relabelling the next moves is a relabelling of the original game. -/ def relabel_relabelling {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') : relabelling x (relabel el er) := relabelling.mk el er (λ i, by simp) (λ j, by simp) /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : pgame → pgame | ⟨l, r, L, R⟩ := ⟨r, l, λ i, neg (R i), λ i, neg (L i)⟩ instance : has_neg pgame := ⟨neg⟩ @[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (λ j, -(xR j)) (λ i, -(xL i)) := rfl @[simp] theorem neg_neg : Π {x : pgame}, -(-x) = x | (mk xl xr xL xR) := begin dsimp [has_neg.neg, neg], congr; funext i; apply neg_neg end @[simp] theorem neg_zero : -(0 : pgame) = 0 := begin dsimp [has_zero.zero, has_neg.neg, neg], congr; funext i; cases i end /-- An explicit equivalence between the moves for Left in `-x` and the moves for Right in `x`. -/ -- This equivalence is useful to avoid having to use `cases` unnecessarily. def left_moves_neg (x : pgame) : (-x).left_moves ≃ x.right_moves := by { cases x, refl } /-- An explicit equivalence between the moves for Right in `-x` and the moves for Left in `x`. -/ def right_moves_neg (x : pgame) : (-x).right_moves ≃ x.left_moves := by { cases x, refl } @[simp] lemma move_right_left_moves_neg {x : pgame} (i : left_moves (-x)) : move_right x ((left_moves_neg x) i) = -(move_left (-x) i) := begin induction x, exact neg_neg.symm end @[simp] lemma move_left_left_moves_neg_symm {x : pgame} (i : right_moves x) : move_left (-x) ((left_moves_neg x).symm i) = -(move_right x i) := by { cases x, refl } @[simp] lemma move_left_right_moves_neg {x : pgame} (i : right_moves (-x)) : move_left x ((right_moves_neg x) i) = -(move_right (-x) i) := begin induction x, exact neg_neg.symm end @[simp] lemma move_right_right_moves_neg_symm {x : pgame} (i : left_moves x) : move_right (-x) ((right_moves_neg x).symm i) = -(move_left x i) := by { cases x, refl } /-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/ def relabelling.neg_congr : ∀ {x y : pgame}, x.relabelling y → (-x).relabelling (-y) | (mk xl xr xL xR) (mk yl yr yL yR) ⟨L_equiv, R_equiv, L_relabelling, R_relabelling⟩ := ⟨R_equiv, L_equiv, λ i, relabelling.neg_congr (by simpa using R_relabelling (R_equiv i)), λ i, relabelling.neg_congr (by simpa using L_relabelling (L_equiv.symm i))⟩ theorem le_iff_neg_ge : Π {x y : pgame}, x ≤ y ↔ -y ≤ -x | (mk xl xr xL xR) (mk yl yr yL yR) := begin rw [le_def], rw [le_def], dsimp [neg], split, { intro h, split, { intro i, have t := h.right i, cases t, { right, cases t, use (@right_moves_neg (yR i)).symm t_w, convert le_iff_neg_ge.1 t_h, simp }, { left, cases t, use t_w, exact le_iff_neg_ge.1 t_h, } }, { intro j, have t := h.left j, cases t, { right, cases t, use t_w, exact le_iff_neg_ge.1 t_h, }, { left, cases t, use (@left_moves_neg (xL j)).symm t_w, convert le_iff_neg_ge.1 t_h, simp, } } }, { intro h, split, { intro i, have t := h.right i, cases t, { right, cases t, use (@left_moves_neg (xL i)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp, }, { left, cases t, use t_w, exact le_iff_neg_ge.2 t_h, } }, { intro j, have t := h.left j, cases t, { right, cases t, use t_w, exact le_iff_neg_ge.2 t_h, }, { left, cases t, use (@right_moves_neg (yR j)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp } } }, end using_well_founded { dec_tac := pgame_wf_tac } theorem neg_congr {x y : pgame} (h : x ≈ y) : -x ≈ -y := ⟨le_iff_neg_ge.1 h.2, le_iff_neg_ge.1 h.1⟩ theorem lt_iff_neg_gt : Π {x y : pgame}, x < y ↔ -y < -x := begin classical, intros, rw [←not_le, ←not_le, not_iff_not], apply le_iff_neg_ge end theorem zero_le_iff_neg_le_zero {x : pgame} : 0 ≤ x ↔ -x ≤ 0 := begin convert le_iff_neg_ge, rw neg_zero end theorem le_zero_iff_zero_le_neg {x : pgame} : x ≤ 0 ↔ 0 ≤ -x := begin convert le_iff_neg_ge, rw neg_zero end /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add (x y : pgame) : pgame := begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, have y := mk yl yr yL yR, refine ⟨xl ⊕ yl, xr ⊕ yr, sum.rec _ _, sum.rec _ _⟩, { exact λ i, IHxl i y }, { exact λ i, IHyl i }, { exact λ i, IHxr i y }, { exact λ i, IHyr i } end instance : has_add pgame := ⟨add⟩ /-- `x + 0` has exactly the same moves as `x`. -/ def add_zero_relabelling : Π (x : pgame.{u}), relabelling (x + 0) x | (mk xl xr xL xR) := begin refine ⟨equiv.sum_empty xl pempty, equiv.sum_empty xr pempty, _, _⟩, { rintro (⟨i⟩|⟨⟨⟩⟩), apply add_zero_relabelling, }, { rintro j, apply add_zero_relabelling, } end /-- `x + 0` is equivalent to `x`. -/ lemma add_zero_equiv (x : pgame.{u}) : x + 0 ≈ x := (add_zero_relabelling x).equiv /-- `0 + x` has exactly the same moves as `x`. -/ def zero_add_relabelling : Π (x : pgame.{u}), relabelling (0 + x) x | (mk xl xr xL xR) := begin refine ⟨equiv.empty_sum pempty xl, equiv.empty_sum pempty xr, _, _⟩, { rintro (⟨⟨⟩⟩|⟨i⟩), apply zero_add_relabelling, }, { rintro j, apply zero_add_relabelling, } end /-- `0 + x` is equivalent to `x`. -/ lemma zero_add_equiv (x : pgame.{u}) : 0 + x ≈ x := (zero_add_relabelling x).equiv /-- An explicit equivalence between the moves for Left in `x + y` and the type-theory sum of the moves for Left in `x` and in `y`. -/ def left_moves_add (x y : pgame) : (x + y).left_moves ≃ x.left_moves ⊕ y.left_moves := by { cases x, cases y, refl, } /-- An explicit equivalence between the moves for Right in `x + y` and the type-theory sum of the moves for Right in `x` and in `y`. -/ def right_moves_add (x y : pgame) : (x + y).right_moves ≃ x.right_moves ⊕ y.right_moves := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) = (mk xl xr xL xR).move_left i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_left_inl {x y : pgame} {i} : (x + y).move_left ((@left_moves_add x y).symm (sum.inl i)) = x.move_left i + y := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) = (mk xl xr xL xR).move_right i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_right_inl {x y : pgame} {i} : (x + y).move_right ((@right_moves_add x y).symm (sum.inl i)) = x.move_right i + y := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_left i := rfl @[simp] lemma add_move_left_inr {x y : pgame} {i : y.left_moves} : (x + y).move_left ((@left_moves_add x y).symm (sum.inr i)) = x + y.move_left i := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_right i := rfl @[simp] lemma add_move_right_inr {x y : pgame} {i} : (x + y).move_right ((@right_moves_add x y).symm (sum.inr i)) = x + y.move_right i := by { cases x, cases y, refl, } /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w + y` has the same moves as `x + z`. -/ def relabelling.add_congr : ∀ {w x y z : pgame.{u}}, w.relabelling x → y.relabelling z → (w + y).relabelling (x + z) | (mk wl wr wL wR) (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) ⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩ ⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩ := begin refine ⟨equiv.sum_congr L_equiv₁ L_equiv₂, equiv.sum_congr R_equiv₁ R_equiv₂, _, _⟩, { rintro (i|j), { exact relabelling.add_congr (L_relabelling₁ i) (⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) }, { exact relabelling.add_congr (⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩) (L_relabelling₂ j) }}, { rintro (i|j), { exact relabelling.add_congr (R_relabelling₁ i) (⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) }, { exact relabelling.add_congr (⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩) (R_relabelling₂ j) }} end using_well_founded { dec_tac := pgame_wf_tac } instance : has_sub pgame := ⟨λ x y, x + -y⟩ /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w - y` has the same moves as `x - z`. -/ def relabelling.sub_congr {w x y z : pgame} (h₁ : w.relabelling x) (h₂ : y.relabelling z) : (w - y).relabelling (x - z) := h₁.add_congr h₂.neg_congr /-- `-(x+y)` has exactly the same moves as `-x + -y`. -/ def neg_add_relabelling : Π (x y : pgame), relabelling (-(x + y)) (-x + -y) | (mk xl xr xL xR) (mk yl yr yL yR) := ⟨equiv.refl _, equiv.refl _, λ j, sum.cases_on j (λ j, neg_add_relabelling (xR j) (mk yl yr yL yR)) (λ j, neg_add_relabelling (mk xl xr xL xR) (yR j)), λ i, sum.cases_on i (λ i, neg_add_relabelling (xL i) (mk yl yr yL yR)) (λ i, neg_add_relabelling (mk xl xr xL xR) (yL i))⟩ using_well_founded { dec_tac := pgame_wf_tac } theorem neg_add_le {x y : pgame} : -(x + y) ≤ -x + -y := (neg_add_relabelling x y).le /-- `x+y` has exactly the same moves as `y+x`. -/ def add_comm_relabelling : Π (x y : pgame.{u}), relabelling (x + y) (y + x) | (mk xl xr xL xR) (mk yl yr yL yR) := begin refine ⟨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _⟩; rintros (_|_); { simp [left_moves_add, right_moves_add], apply add_comm_relabelling } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_comm_le {x y : pgame} : x + y ≤ y + x := (add_comm_relabelling x y).le theorem add_comm_equiv {x y : pgame} : x + y ≈ y + x := (add_comm_relabelling x y).equiv /-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/ def add_assoc_relabelling : Π (x y z : pgame.{u}), relabelling ((x + y) + z) (x + (y + z)) | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) := begin refine ⟨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _⟩, { rintro (⟨i|i⟩|i), { apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + yL i + mk zl zr zL zR) (mk xl xr xL xR + (yL i + mk zl zr zL zR)), apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + mk yl yr yL yR + zL i) (mk xl xr xL xR + (mk yl yr yL yR + zL i)), apply add_assoc_relabelling, } }, { rintro (j|⟨j|j⟩), { apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + yR j + mk zl zr zL zR) (mk xl xr xL xR + (yR j + mk zl zr zL zR)), apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + mk yl yr yL yR + zR j) (mk xl xr xL xR + (mk yl yr yL yR + zR j)), apply add_assoc_relabelling, } }, end using_well_founded { dec_tac := pgame_wf_tac } theorem add_assoc_equiv {x y z : pgame} : (x + y) + z ≈ x + (y + z) := (add_assoc_relabelling x y z).equiv theorem add_le_add_right : Π {x y z : pgame} (h : x ≤ y), x + z ≤ y + z | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) := begin intros h, rw le_def, split, { -- if Left plays first intros i, change xl ⊕ zl at i, cases i, { -- either they play in x rw le_def at h, cases h, have t := h_left i, rcases t with ⟨i', ih⟩ | ⟨j, jh⟩, { left, refine ⟨(left_moves_add _ _).inv_fun (sum.inl i'), _⟩, exact add_le_add_right ih, }, { right, refine ⟨(right_moves_add _ _).inv_fun (sum.inl j), _⟩, convert add_le_add_right jh, apply add_move_right_inl }, }, { -- or play in z left, refine ⟨(left_moves_add _ _).inv_fun (sum.inr i), _⟩, exact add_le_add_right h, }, }, { -- if Right plays first intros j, change yr ⊕ zr at j, cases j, { -- either they play in y rw le_def at h, cases h, have t := h_right j, rcases t with ⟨i, ih⟩ | ⟨j', jh⟩, { left, refine ⟨(left_moves_add _ _).inv_fun (sum.inl i), _⟩, convert add_le_add_right ih, apply add_move_left_inl }, { right, refine ⟨(right_moves_add _ _).inv_fun (sum.inl j'), _⟩, exact add_le_add_right jh } }, { -- or play in z right, refine ⟨(right_moves_add _ _).inv_fun (sum.inr j), _⟩, exact add_le_add_right h } } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_le_add_left {x y z : pgame} (h : y ≤ z) : x + y ≤ x + z := calc x + y ≤ y + x : add_comm_le ... ≤ z + x : add_le_add_right h ... ≤ x + z : add_comm_le theorem add_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w + y ≈ x + z := ⟨calc w + y ≤ w + z : add_le_add_left h₂.1 ... ≤ x + z : add_le_add_right h₁.1, calc x + z ≤ x + y : add_le_add_left h₂.2 ... ≤ w + y : add_le_add_right h₁.2⟩ theorem sub_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w - y ≈ x - z := add_congr h₁ (neg_congr h₂) theorem add_left_neg_le_zero : Π {x : pgame}, (-x) + x ≤ 0 | ⟨xl, xr, xL, xR⟩ := begin rw [le_def], split, { intro i, change xr ⊕ xl at i, cases i, { -- If Left played in -x, Right responds with the same move in x. right, refine ⟨(right_moves_add _ _).inv_fun (sum.inr i), _⟩, convert @add_left_neg_le_zero (xR i), exact add_move_right_inr }, { -- If Left in x, Right responds with the same move in -x. right, dsimp, refine ⟨(right_moves_add _ _).inv_fun (sum.inl i), _⟩, convert @add_left_neg_le_zero (xL i), exact add_move_right_inl }, }, { rintro ⟨⟩, } end using_well_founded { dec_tac := pgame_wf_tac } theorem zero_le_add_left_neg : Π {x : pgame}, 0 ≤ (-x) + x := begin intro x, rw [le_iff_neg_ge, neg_zero], exact le_trans neg_add_le add_left_neg_le_zero end theorem add_left_neg_equiv {x : pgame} : (-x) + x ≈ 0 := ⟨add_left_neg_le_zero, zero_le_add_left_neg⟩ theorem add_right_neg_le_zero {x : pgame} : x + (-x) ≤ 0 := calc x + (-x) ≤ (-x) + x : add_comm_le ... ≤ 0 : add_left_neg_le_zero theorem zero_le_add_right_neg {x : pgame} : 0 ≤ x + (-x) := calc 0 ≤ (-x) + x : zero_le_add_left_neg ... ≤ x + (-x) : add_comm_le theorem add_right_neg_equiv {x : pgame} : x + (-x) ≈ 0 := ⟨add_right_neg_le_zero, zero_le_add_right_neg⟩ theorem add_lt_add_right {x y z : pgame} (h : x < y) : x + z < y + z := suffices y + z ≤ x + z → y ≤ x, by { rw ←not_le at ⊢ h, exact mt this h }, assume w, calc y ≤ y + 0 : (add_zero_relabelling _).symm.le ... ≤ y + (z + -z) : add_le_add_left zero_le_add_right_neg ... ≤ (y + z) + (-z) : (add_assoc_relabelling _ _ _).symm.le ... ≤ (x + z) + (-z) : add_le_add_right w ... ≤ x + (z + -z) : (add_assoc_relabelling _ _ _).le ... ≤ x + 0 : add_le_add_left add_right_neg_le_zero ... ≤ x : (add_zero_relabelling _).le theorem add_lt_add_left {x y z : pgame} (h : y < z) : x + y < x + z := calc x + y ≤ y + x : add_comm_le ... < z + x : add_lt_add_right h ... ≤ x + z : add_comm_le theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := ⟨λ h, le_trans zero_le_add_right_neg (add_le_add_right h), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... ≤ (y - x) + x : add_le_add_right h ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero) ... ≤ y : (add_zero_relabelling y).le⟩ theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := ⟨λ h, lt_of_le_of_lt zero_le_add_right_neg (add_lt_add_right h), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... < (y - x) + x : add_lt_add_right h ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero) ... ≤ y : (add_zero_relabelling y).le⟩ /-- The pre-game `star`, which is fuzzy/confused with zero. -/ def star : pgame := pgame.of_lists [0] [0] theorem star_lt_zero : star < 0 := by rw lt_def; exact or.inr ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩ theorem zero_lt_star : 0 < star := by rw lt_def; exact or.inl ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩ /-- The pre-game `ω`. (In fact all ordinals have game and surreal representatives.) -/ def omega : pgame := ⟨ulift ℕ, pempty, λ n, ↑n.1, pempty.elim⟩ end pgame
75bc3e231761c2329987ad8a405feac2643e3ea3
367134ba5a65885e863bdc4507601606690974c1
/src/order/boolean_algebra.lean
4850bea2a06a69fde10c1e384c49c70c821ac167
[ "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
4,551
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 Type class hierarchy for Boolean algebras. -/ import order.bounded_lattice set_option old_structure_cmd true universes u v variables {α : Type u} {w x y z : α} /-- Set / lattice complement -/ class has_compl (α : Type*) := (compl : α → α) export has_compl (compl) postfix `ᶜ`:(max+1) := compl /-- A boolean algebra is a bounded distributive lattice with a complementation operation `-` such that `x ⊓ - x = ⊥` and `x ⊔ - x = ⊤`. This is a generalization of (classical) logic of propositions, or the powerset lattice. -/ class boolean_algebra α extends bounded_distrib_lattice α, has_compl α, has_sdiff α := (inf_compl_le_bot : ∀x:α, x ⊓ xᶜ ≤ ⊥) (top_le_sup_compl : ∀x:α, ⊤ ≤ x ⊔ xᶜ) (sdiff_eq : ∀x y:α, x \ y = x ⊓ yᶜ) section boolean_algebra variables [boolean_algebra α] @[simp] theorem inf_compl_eq_bot : x ⊓ xᶜ = ⊥ := bot_unique $ boolean_algebra.inf_compl_le_bot x @[simp] theorem compl_inf_eq_bot : xᶜ ⊓ x = ⊥ := eq.trans inf_comm inf_compl_eq_bot @[simp] theorem sup_compl_eq_top : x ⊔ xᶜ = ⊤ := top_unique $ boolean_algebra.top_le_sup_compl x @[simp] theorem compl_sup_eq_top : xᶜ ⊔ x = ⊤ := eq.trans sup_comm sup_compl_eq_top theorem is_compl_compl : is_compl x xᶜ := is_compl.of_eq inf_compl_eq_bot sup_compl_eq_top theorem is_compl.compl_eq (h : is_compl x y) : xᶜ = y := (h.right_unique is_compl_compl).symm theorem disjoint_compl_right : disjoint x xᶜ := is_compl_compl.disjoint theorem disjoint_compl_left : disjoint xᶜ x := disjoint_compl_right.symm theorem sdiff_eq : x \ y = x ⊓ yᶜ := boolean_algebra.sdiff_eq x y theorem compl_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : xᶜ = y := (is_compl.of_eq i s).compl_eq @[simp] theorem compl_top : ⊤ᶜ = (⊥:α) := is_compl_top_bot.compl_eq @[simp] theorem compl_bot : ⊥ᶜ = (⊤:α) := is_compl_bot_top.compl_eq @[simp] theorem compl_compl (x : α) : xᶜᶜ = x := is_compl_compl.symm.compl_eq theorem compl_injective : function.injective (compl : α → α) := function.involutive.injective compl_compl @[simp] theorem compl_inj_iff : xᶜ = yᶜ ↔ x = y := compl_injective.eq_iff theorem is_compl.compl_eq_iff (h : is_compl x y) : zᶜ = y ↔ z = x := h.compl_eq ▸ compl_inj_iff @[simp] theorem compl_eq_top : xᶜ = ⊤ ↔ x = ⊥ := is_compl_bot_top.compl_eq_iff @[simp] theorem compl_eq_bot : xᶜ = ⊥ ↔ x = ⊤ := is_compl_top_bot.compl_eq_iff @[simp] theorem compl_inf : (x ⊓ y)ᶜ = xᶜ ⊔ yᶜ := (is_compl_compl.inf_sup is_compl_compl).compl_eq @[simp] theorem compl_sup : (x ⊔ y)ᶜ = xᶜ ⊓ yᶜ := (is_compl_compl.sup_inf is_compl_compl).compl_eq theorem compl_le_compl (h : y ≤ x) : xᶜ ≤ yᶜ := is_compl_compl.antimono is_compl_compl h @[simp] theorem compl_le_compl_iff_le : yᶜ ≤ xᶜ ↔ x ≤ y := ⟨assume h, by have h := compl_le_compl h; simp at h; assumption, compl_le_compl⟩ theorem le_compl_of_le_compl (h : y ≤ xᶜ) : x ≤ yᶜ := by simpa only [compl_compl] using compl_le_compl h theorem compl_le_of_compl_le (h : yᶜ ≤ x) : xᶜ ≤ y := by simpa only [compl_compl] using compl_le_compl h theorem le_compl_iff_le_compl : y ≤ xᶜ ↔ x ≤ yᶜ := ⟨le_compl_of_le_compl, le_compl_of_le_compl⟩ theorem compl_le_iff_compl_le : xᶜ ≤ y ↔ yᶜ ≤ x := ⟨compl_le_of_compl_le, compl_le_of_compl_le⟩ theorem sup_sdiff_same : x ⊔ (y \ x) = x ⊔ y := by simp [sdiff_eq, sup_inf_left] theorem sdiff_eq_left (h : x ⊓ y = ⊥) : x \ y = x := by rwa [sdiff_eq, inf_eq_left, is_compl_compl.le_right_iff, disjoint_iff] theorem sdiff_le_sdiff (h₁ : w ≤ y) (h₂ : z ≤ x) : w \ x ≤ y \ z := by rw [sdiff_eq, sdiff_eq]; from inf_le_inf h₁ (compl_le_compl h₂) @[simp] lemma sdiff_idem_right : x \ y \ y = x \ y := by rw [sdiff_eq, sdiff_eq, inf_assoc, inf_idem] namespace boolean_algebra @[priority 100] instance : is_complemented α := ⟨λ x, ⟨xᶜ, is_compl_compl⟩⟩ end boolean_algebra end boolean_algebra instance boolean_algebra_Prop : boolean_algebra Prop := { compl := not, sdiff := λ p q, p ∧ ¬ q, sdiff_eq := λ _ _, rfl, inf_compl_le_bot := λ p ⟨Hp, Hpc⟩, Hpc Hp, top_le_sup_compl := λ p H, classical.em p, .. bounded_distrib_lattice_Prop } instance pi.boolean_algebra {α : Type u} {β : Type v} [boolean_algebra β] : boolean_algebra (α → β) := by pi_instance
f411a9b1b783a8cc845f3c9cc242af239a19b670
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Util/Sorry.lean
57232f3b93aef60d47986cda6c7bce52cff307d1
[ "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
2,697
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.Message import Lean.Exception namespace Lean def Expr.isSorry : Expr → Bool | Expr.app (Expr.app (Expr.const `sorryAx _ _) _ _) _ _ => true | _ => false def Expr.isSyntheticSorry : Expr → Bool | Expr.app (Expr.app (Expr.const `sorryAx _ _) _ _) (Expr.const `Bool.true _ _) _ => true | _ => false def Expr.hasSorry : Expr → Bool | Expr.const c _ _ => c == `sorryAx | Expr.app f a _ => f.hasSorry || a.hasSorry | Expr.letE _ t v b _ => t.hasSorry || v.hasSorry || b.hasSorry | Expr.forallE _ d b _ => d.hasSorry || b.hasSorry | Expr.lam _ d b _ => d.hasSorry || b.hasSorry | Expr.mdata _ e _ => e.hasSorry | Expr.proj _ _ e _ => e.hasSorry | _ => false def Expr.hasSyntheticSorry : Expr → Bool | e@(Expr.app f a _) => e.isSyntheticSorry || f.hasSyntheticSorry || a.hasSyntheticSorry | Expr.letE _ t v b _ => t.hasSyntheticSorry || v.hasSyntheticSorry || b.hasSyntheticSorry | Expr.forallE _ d b _ => d.hasSyntheticSorry || b.hasSyntheticSorry | Expr.lam _ d b _ => d.hasSyntheticSorry || b.hasSyntheticSorry | Expr.mdata _ e _ => e.hasSyntheticSorry | Expr.proj _ _ e _ => e.hasSyntheticSorry | _ => false partial def MessageData.hasSorry : MessageData → Bool | MessageData.ofExpr e => e.hasSorry | MessageData.withContext _ msg => msg.hasSorry | MessageData.nest _ msg => msg.hasSorry | MessageData.group msg => msg.hasSorry | MessageData.compose msg₁ msg₂ => msg₁.hasSorry || msg₂.hasSorry | MessageData.tagged _ msg => msg.hasSorry | MessageData.node msgs => msgs.any hasSorry | _ => false partial def MessageData.hasSyntheticSorry (msg : MessageData) : Bool := visit msg.instantiateMVars where visit : MessageData → Bool | MessageData.ofExpr e => e.hasSyntheticSorry | MessageData.withContext _ msg => visit msg | MessageData.withNamingContext _ msg => visit msg | MessageData.nest _ msg => visit msg | MessageData.group msg => visit msg | MessageData.compose msg₁ msg₂ => visit msg₁ || visit msg₂ | MessageData.tagged _ msg => visit msg | MessageData.node msgs => msgs.any hasSyntheticSorry | _ => false def Exception.hasSyntheticSorry : Exception → Bool | Exception.error _ msg => msg.hasSyntheticSorry | _ => false end Lean
a6b4c27b5216749ec6c4e7e9820a3b3117c9ff6b
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-algebra-55.lean
074c7667221c9abd1d8c755a5d179faa055e92ed
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
329
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic example (q p : ℝ) (h₀ : q = 2 - 4 + 6 - 8 + 10 - 12 + 14) (h₁ : p = 3 - 6 + 9 - 12 + 15 - 18 + 21) : q / p = 2 / 3 := begin rw [h₀, h₁], ring, end
370638502f6026fdd10a02efbf8fe7a6c7f23c28
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Compiler/ClosedTermCache.lean
5325a57b13399c8e4366d4f318521f2359cc1d77
[ "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
959
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Environment namespace Lean abbrev ClosedTermCache := SMap Expr Name builtin_initialize closedTermCacheExt : SimplePersistentEnvExtension (Expr × Name) ClosedTermCache ← registerSimplePersistentEnvExtension { name := `closedTermCache, addImportedFn := fun as => let cache : ClosedTermCache := mkStateFromImportedEntries (fun s (p : Expr × Name) => s.insert p.1 p.2) {} as; cache.switch, addEntryFn := fun s ⟨e, n⟩ => s.insert e n } @[export lean_cache_closed_term_name] def cacheClosedTermName (env : Environment) (e : Expr) (n : Name) : Environment := closedTermCacheExt.addEntry env (e, n) @[export lean_get_closed_term_name] def getClosedTermName? (env : Environment) (e : Expr) : Option Name := (closedTermCacheExt.getState env).find? e end Lean
c29f83edaf00cb4b3f5e97e3aa7cdc578767b0f4
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/LocalContext.lean
288d4bab32c38a675a2342fc1c33896d48bb3b93
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,566
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.PersistentArray.Basic import Init.Data.PersistentHashMap.Basic import Init.Lean.Expr import Init.Lean.Hygiene namespace Lean inductive LocalDecl | cdecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) | ldecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) @[export lean_mk_local_decl] def mkLocalDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalDecl := LocalDecl.cdecl index fvarId userName type bi @[export lean_mk_let_decl] def mkLetDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : LocalDecl := LocalDecl.ldecl index fvarId userName type val @[export lean_local_decl_binder_info] def LocalDecl.binderInfoEx : LocalDecl → BinderInfo | LocalDecl.cdecl _ _ _ _ bi => bi | _ => BinderInfo.default namespace LocalDecl instance : Inhabited LocalDecl := ⟨ldecl (arbitrary _) (arbitrary _) (arbitrary _) (arbitrary _) (arbitrary _)⟩ def isLet : LocalDecl → Bool | cdecl _ _ _ _ _ => false | ldecl _ _ _ _ _ => true def index : LocalDecl → Nat | cdecl idx _ _ _ _ => idx | ldecl idx _ _ _ _ => idx def fvarId : LocalDecl → FVarId | cdecl _ id _ _ _ => id | ldecl _ id _ _ _ => id def userName : LocalDecl → Name | cdecl _ _ n _ _ => n | ldecl _ _ n _ _ => n def type : LocalDecl → Expr | cdecl _ _ _ t _ => t | ldecl _ _ _ t _ => t def binderInfo : LocalDecl → BinderInfo | cdecl _ _ _ _ bi => bi | ldecl _ _ _ _ _ => BinderInfo.default def value? : LocalDecl → Option Expr | cdecl _ _ _ _ _ => none | ldecl _ _ _ _ v => some v def value : LocalDecl → Expr | cdecl _ _ _ _ _ => panic! "let declaration expected" | ldecl _ _ _ _ v => v def updateUserName : LocalDecl → Name → LocalDecl | cdecl index id _ type bi, userName => cdecl index id userName type bi | ldecl index id _ type val, userName => ldecl index id userName type val def toExpr (decl : LocalDecl) : Expr := mkFVar decl.fvarId end LocalDecl structure LocalContext := (fvarIdToDecl : PersistentHashMap FVarId LocalDecl := {}) (decls : PersistentArray (Option LocalDecl) := {}) namespace LocalContext instance : Inhabited LocalContext := ⟨{}⟩ @[export lean_mk_empty_local_ctx] def mkEmpty : Unit → LocalContext := fun _ => {} def empty : LocalContext := {} @[export lean_local_ctx_is_empty] def isEmpty (lctx : LocalContext) : Bool := lctx.fvarIdToDecl.isEmpty /- Low level API for creating local declarations. It is used to implement actions in the monads `Elab` and `Tactic`. It should not be used directly since the argument `(name : Name)` is assumed to be "unique". -/ @[export lean_local_ctx_mk_local_decl] def mkLocalDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo := BinderInfo.default) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size; let decl := LocalDecl.cdecl idx fvarId userName type bi; { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } @[export lean_local_ctx_mk_let_decl] def mkLetDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size; let decl := LocalDecl.ldecl idx fvarId userName type value; { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } /- Low level API -/ def addDecl (lctx : LocalContext) (newDecl : LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => { fvarIdToDecl := map.insert newDecl.fvarId newDecl, decls := decls.set newDecl.index newDecl } @[export lean_local_ctx_find] def find? (lctx : LocalContext) (fvarId : FVarId) : Option LocalDecl := lctx.fvarIdToDecl.find? fvarId def findFVar? (lctx : LocalContext) (e : Expr) : Option LocalDecl := lctx.find? e.fvarId! def get! (lctx : LocalContext) (fvarId : FVarId) : LocalDecl := match lctx.find? fvarId with | some d => d | none => panic! "unknown free variable" def getFVar! (lctx : LocalContext) (e : Expr) : LocalDecl := lctx.get! e.fvarId! def contains (lctx : LocalContext) (fvarId : FVarId) : Bool := lctx.fvarIdToDecl.contains fvarId def containsFVar (lctx : LocalContext) (e : Expr) : Bool := lctx.contains e.fvarId! def getFVarIds (lctx : LocalContext) : Array FVarId := lctx.decls.foldl (fun (r : Array FVarId) decl? => match decl? with | some decl => r.push decl.fvarId | none => r) #[] def getFVars (lctx : LocalContext) : Array Expr := lctx.getFVarIds.map mkFVar private partial def popTailNoneAux : PArray (Option LocalDecl) → PArray (Option LocalDecl) | a => if a.size == 0 then a else match a.get! (a.size - 1) with | none => popTailNoneAux a.pop | some _ => a @[export lean_local_ctx_erase] def erase (lctx : LocalContext) (fvarId : FVarId) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match map.find? fvarId with | none => lctx | some decl => { fvarIdToDecl := map.erase fvarId, decls := popTailNoneAux (decls.set decl.index none) } @[export lean_local_ctx_pop] def pop (lctx : LocalContext): LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => if decls.size == 0 then lctx else match decls.get! (decls.size - 1) with | none => lctx -- unreachable | some decl => { fvarIdToDecl := map.erase decl.fvarId, decls := popTailNoneAux decls.pop } @[export lean_local_ctx_find_from_user_name] def findFromUserName? (lctx : LocalContext) (userName : Name) : Option LocalDecl := lctx.decls.findSomeRev? (fun decl => match decl with | none => none | some decl => if decl.userName == userName then some decl else none) @[export lean_local_ctx_uses_user_name] def usesUserName (lctx : LocalContext) (userName : Name) : Bool := (lctx.findFromUserName? userName).isSome private partial def getUnusedNameAux (lctx : LocalContext) (suggestion : Name) : Nat → Name × Nat | i => let curr := suggestion.appendIndexAfter i; if lctx.usesUserName curr then getUnusedNameAux (i + 1) else (curr, i + 1) @[export lean_local_ctx_get_unused_name] def getUnusedName (lctx : LocalContext) (suggestion : Name) : Name := let suggestion := suggestion.eraseMacroScopes; if lctx.usesUserName suggestion then (getUnusedNameAux lctx suggestion 1).1 else suggestion @[export lean_local_ctx_last_decl] def lastDecl (lctx : LocalContext) : Option LocalDecl := lctx.decls.get! (lctx.decls.size - 1) @[export lean_local_ctx_rename_user_name] def renameUserName (lctx : LocalContext) (fromName : Name) (toName : Name) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.findFromUserName? fromName with | none => lctx | some decl => let decl := decl.updateUserName toName; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } @[export lean_local_ctx_num_indices] def numIndices (lctx : LocalContext) : Nat := lctx.decls.size @[export lean_local_ctx_get] def getAt! (lctx : LocalContext) (i : Nat) : Option LocalDecl := lctx.decls.get! i section universes u v variables {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] def foldlM (lctx : LocalContext) (f : β → LocalDecl → m β) (b : β) : m β := lctx.decls.foldlM (fun b decl => match decl with | none => pure b | some decl => f b decl) b @[specialize] def forM (lctx : LocalContext) (f : LocalDecl → m PUnit) : m PUnit := lctx.decls.forM $ fun decl => match decl with | none => pure PUnit.unit | some decl => f decl @[specialize] def findDeclM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeM? $ fun decl => match decl with | none => pure none | some decl => f decl @[specialize] def findDeclRevM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeRevM? $ fun decl => match decl with | none => pure none | some decl => f decl @[specialize] def foldlFromM (lctx : LocalContext) (f : β → LocalDecl → m β) (b : β) (decl : LocalDecl) : m β := lctx.decls.foldlFromM (fun b decl => match decl with | none => pure b | some decl => f b decl) b decl.index end @[inline] def foldl {β} (lctx : LocalContext) (f : β → LocalDecl → β) (b : β) : β := Id.run $ lctx.foldlM f b @[inline] def findDecl? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run $ lctx.findDeclM? f @[inline] def findDeclRev? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run $ lctx.findDeclRevM? f @[inline] def foldlFrom {β} (lctx : LocalContext) (f : β → LocalDecl → β) (b : β) (decl : LocalDecl) : β := Id.run $ lctx.foldlFromM f b decl partial def isSubPrefixOfAux (a₁ a₂ : PArray (Option LocalDecl)) (exceptFVars : Array Expr) : Nat → Nat → Bool | i, j => if i < a₁.size then match a₁.get! i with | none => isSubPrefixOfAux (i+1) j | some decl₁ => if exceptFVars.any $ fun fvar => fvar.fvarId! == decl₁.fvarId then isSubPrefixOfAux (i+1) j else if j < a₂.size then match a₂.get! j with | none => isSubPrefixOfAux i (j+1) | some decl₂ => if decl₁.fvarId == decl₂.fvarId then isSubPrefixOfAux (i+1) (j+1) else isSubPrefixOfAux i (j+1) else false else true /- Given `lctx₁ - exceptFVars` of the form `(x_1 : A_1) ... (x_n : A_n)`, then return true iff there is a local context `B_1* (x_1 : A_1) ... B_n* (x_n : A_n)` which is a prefix of `lctx₂` where `B_i`'s are (possibly empty) sequences of local declarations. -/ def isSubPrefixOf (lctx₁ lctx₂ : LocalContext) (exceptFVars : Array Expr := #[]) : Bool := isSubPrefixOfAux lctx₁.decls lctx₂.decls exceptFVars 0 0 @[inline] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := let b := b.abstract xs; xs.size.foldRev (fun i b => let x := xs.get! i; match lctx.findFVar? x with | some (LocalDecl.cdecl _ _ n ty bi) => let ty := ty.abstractRange i xs; if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | some (LocalDecl.ldecl _ _ n ty val) => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs; let val := val.abstractRange i xs; mkLet n ty val b else b.lowerLooseBVars 1 1 | none => panic! "unknown free variable") b def mkLambda (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding true lctx xs b def mkForall (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding false lctx xs b section universes u variables {m : Type → Type u} [Monad m] @[inline] def anyM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.anyM $ fun d => match d with | some decl => p decl | none => pure false @[inline] def allM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.allM $ fun d => match d with | some decl => p decl | none => pure true end @[inline] def any (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run $ lctx.anyM p @[inline] def all (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run $ lctx.allM p end LocalContext end Lean
d17026900f3a7f1b12ba9e8157f83a0b712788fe
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/types/sigma.hlean
2fca3c659e5912f08e0838d85dd2842cbaab0333
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
22,127
hlean
/- Copyright (c) 2014-15 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about sigma-types (dependent sums) -/ import types.prod open eq sigma sigma.ops equiv is_equiv function is_trunc sum unit namespace sigma variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a} definition destruct := @sigma.cases_on /- Paths in a sigma-type -/ protected definition eta [unfold 3] : Π (u : Σa, B a), ⟨u.1 , u.2⟩ = u | eta ⟨u₁, u₂⟩ := idp definition eta2 : Π (u : Σa b, C a b), ⟨u.1, u.2.1, u.2.2⟩ = u | eta2 ⟨u₁, u₂, u₃⟩ := idp definition eta3 : Π (u : Σa b c, D a b c), ⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩ = u | eta3 ⟨u₁, u₂, u₃, u₄⟩ := idp definition dpair_eq_dpair [unfold 8] (p : a = a') (q : b =[p] b') : ⟨a, b⟩ = ⟨a', b'⟩ := apd011 sigma.mk p q definition sigma_eq [unfold 3 4] (p : u.1 = v.1) (q : u.2 =[p] v.2) : u = v := by induction u; induction v; exact (dpair_eq_dpair p q) definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 := ap pr1 p postfix `..1`:(max+1) := eq_pr1 definition eq_pr2 [unfold 5] (p : u = v) : u.2 =[p..1] v.2 := by induction p; exact idpo postfix `..2`:(max+1) := eq_pr2 definition dpair_sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) : ⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩ = ⟨p, q⟩ := by induction u; induction v;esimp at *;induction q;esimp definition sigma_eq_pr1 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..1 = p := (dpair_sigma_eq p q)..1 definition sigma_eq_pr2 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..2 =[sigma_eq_pr1 p q] q := (dpair_sigma_eq p q)..2 definition sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p := by induction p; induction u; reflexivity definition eq2_pr1 {p q : u = v} (r : p = q) : p..1 = q..1 := ap eq_pr1 r definition eq2_pr2 {p q : u = v} (r : p = q) : p..2 =[eq2_pr1 r] q..2 := !pathover_ap (apd eq_pr2 r) definition tr_pr1_sigma_eq {B' : A → Type} (p : u.1 = v.1) (q : u.2 =[p] v.2) : transport (λx, B' x.1) (sigma_eq p q) = transport B' p := by induction u; induction v; esimp at *;induction q; reflexivity protected definition ap_pr1 (p : u = v) : ap (λx : sigma B, x.1) p = p..1 := idp /- the uncurried version of sigma_eq. We will prove that this is an equivalence -/ definition sigma_eq_unc [unfold 5] : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), u = v | sigma_eq_unc ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂ definition dpair_sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), ⟨(sigma_eq_unc pq)..1, (sigma_eq_unc pq)..2⟩ = pq | dpair_sigma_eq_unc ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂ definition sigma_eq_pr1_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..1 = pq.1 := (dpair_sigma_eq_unc pq)..1 definition sigma_eq_pr2_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..2 =[sigma_eq_pr1_unc pq] pq.2 := (dpair_sigma_eq_unc pq)..2 definition sigma_eq_eta_unc (p : u = v) : sigma_eq_unc ⟨p..1, p..2⟩ = p := sigma_eq_eta p definition tr_sigma_eq_pr1_unc {B' : A → Type} (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : transport (λx, B' x.1) (@sigma_eq_unc A B u v pq) = transport B' pq.1 := destruct pq tr_pr1_sigma_eq definition is_equiv_sigma_eq [instance] [constructor] (u v : Σa, B a) : is_equiv (@sigma_eq_unc A B u v) := adjointify sigma_eq_unc (λp, ⟨p..1, p..2⟩) sigma_eq_eta_unc dpair_sigma_eq_unc definition sigma_eq_equiv [constructor] (u v : Σa, B a) : (u = v) ≃ (Σ(p : u.1 = v.1), u.2 =[p] v.2) := (equiv.mk sigma_eq_unc _)⁻¹ᵉ definition dpair_eq_dpair_con (p1 : a = a' ) (q1 : b =[p1] b' ) (p2 : a' = a'') (q2 : b' =[p2] b'') : dpair_eq_dpair (p1 ⬝ p2) (q1 ⬝o q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 := by induction q1; induction q2; reflexivity definition sigma_eq_con (p1 : u.1 = v.1) (q1 : u.2 =[p1] v.2) (p2 : v.1 = w.1) (q2 : v.2 =[p2] w.2) : sigma_eq (p1 ⬝ p2) (q1 ⬝o q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 := by induction u; induction v; induction w; apply dpair_eq_dpair_con local attribute dpair_eq_dpair [reducible] definition dpair_eq_dpair_con_idp (p : a = a') (q : b =[p] b') : dpair_eq_dpair p q = dpair_eq_dpair p !pathover_tr ⬝ dpair_eq_dpair idp (pathover_idp_of_eq (tr_eq_of_pathover q)) := by induction q; reflexivity /- eq_pr1 commutes with the groupoid structure. -/ definition eq_pr1_idp (u : Σa, B a) : (refl u) ..1 = refl (u.1) := idp definition eq_pr1_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := !ap_con definition eq_pr1_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := !ap_inv /- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/ definition ap_dpair (q : b₁ = b₂) : ap (sigma.mk a) q = dpair_eq_dpair idp (pathover_idp_of_eq q) := by induction q; reflexivity /- Dependent transport is the same as transport along a sigma_eq. -/ definition transportD_eq_transport (p : a = a') (c : C a b) : p ▸D c = transport (λu, C (u.1) (u.2)) (dpair_eq_dpair p !pathover_tr) c := by induction p; reflexivity definition sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : b =[p1] b'} {q2 : b =[q1] b'} (r : p1 = q1) (s : p2 =[r] q2) : sigma_eq p1 p2 = sigma_eq q1 q2 := by induction s; reflexivity /- A path between paths in a total space is commonly shown component wise. -/ definition sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : p..2 =[r] q..2) : p = q := begin induction p, induction u with u1 u2, transitivity sigma_eq q..1 q..2, apply sigma_eq_eq_sigma_eq r s, apply sigma_eq_eta, end definition sigma_eq2_unc {p q : u = v} (rs : Σ(r : p..1 = q..1), p..2 =[r] q..2) : p = q := destruct rs sigma_eq2 definition ap_dpair_eq_dpair (f : Πa, B a → A') (p : a = a') (q : b =[p] b') : ap (sigma.rec f) (dpair_eq_dpair p q) = apd011 f p q := by induction q; reflexivity /- Transport -/ /- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD]. In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/ definition sigma_transport (p : a = a') (bc : Σ(b : B a), C a b) : p ▸ bc = ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; reflexivity /- The special case when the second variable doesn't depend on the first is simpler. -/ definition sigma_transport_nondep {B : Type} {C : A → B → Type} (p : a = a') (bc : Σ(b : B), C a b) : p ▸ bc = ⟨bc.1, p ▸ bc.2⟩ := by induction p; induction bc; reflexivity /- Or if the second variable contains a first component that doesn't depend on the first. -/ definition sigma_transport2_nondep {C : A → Type} {D : Π a:A, B a → C a → Type} (p : a = a') (bcd : Σ(b : B a) (c : C a), D a b c) : p ▸ bcd = ⟨p ▸ bcd.1, p ▸ bcd.2.1, p ▸D2 bcd.2.2⟩ := begin induction p, induction bcd with b cd, induction cd, reflexivity end /- Pathovers -/ definition etao (p : a = a') (bc : Σ(b : B a), C a b) : bc =[p] ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; apply idpo -- TODO: interchange sigma_pathover and sigma_pathover' definition sigma_pathover (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b) (r : u.1 =[p] v.1) (s : u.2 =[apd011 C p r] v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, esimp [apd011] at s, induction s using idp_rec_on, apply idpo end definition sigma_pathover' (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b) (r : u.1 =[p] v.1) (s : pathover (λx, C x.1 x.2) u.2 (sigma_eq p r) v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, induction s using idp_rec_on, apply idpo end definition sigma_pathover_nondep {B : Type} {C : A → B → Type} (p : a = a') (u : Σ(b : B), C a b) (v : Σ(b : B), C a' b) (r : u.1 = v.1) (s : pathover (λx, C (prod.pr1 x) (prod.pr2 x)) u.2 (prod.prod_eq p r) v.2) : u =[p] v := begin induction p, induction u, induction v, esimp at *, induction r, induction s using idp_rec_on, apply idpo end /- TODO: * define the projections from the type u =[p] v * show that the uncurried version of sigma_pathover is an equivalence -/ /- Squares in a sigma type are characterized in cubical.squareover (to avoid circular imports) -/ /- Functorial action -/ variables (f : A → A') (g : Πa, B a → B' (f a)) definition sigma_functor [unfold 7] (u : Σa, B a) : Σa', B' a' := ⟨f u.1, g u.1 u.2⟩ definition total [reducible] [unfold 5] {B' : A → Type} (g : Πa, B a → B' a) : (Σa, B a) → (Σa, B' a) := sigma_functor id g /- Equivalences -/ definition is_equiv_sigma_functor [constructor] [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : is_equiv (sigma_functor f g) := adjointify (sigma_functor f g) (sigma_functor f⁻¹ (λ(a' : A') (b' : B' a'), ((g (f⁻¹ a'))⁻¹ (transport B' (right_inv f a')⁻¹ b')))) abstract begin intro u', induction u' with a' b', apply sigma_eq (right_inv f a'), rewrite [▸*,right_inv (g (f⁻¹ a')),▸*], apply tr_pathover end end abstract begin intro u, induction u with a b, apply (sigma_eq (left_inv f a)), apply pathover_of_tr_eq, rewrite [▸*,adj f,-(fn_tr_eq_tr_fn (left_inv f a) (λ a, (g a)⁻¹)), ▸*,tr_compose B' f,tr_inv_tr,left_inv] end end definition sigma_equiv_sigma_of_is_equiv [constructor] [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') := equiv.mk (sigma_functor f g) !is_equiv_sigma_functor definition sigma_equiv_sigma [constructor] (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (to_fun Hf a)) : (Σa, B a) ≃ (Σa', B' a') := sigma_equiv_sigma_of_is_equiv (to_fun Hf) (λ a, to_fun (Hg a)) definition sigma_equiv_sigma_right [constructor] {B' : A → Type} (Hg : Π a, B a ≃ B' a) : (Σa, B a) ≃ Σa, B' a := sigma_equiv_sigma equiv.rfl Hg definition sigma_equiv_sigma_left [constructor] (Hf : A ≃ A') : (Σa, B a) ≃ (Σa', B (to_inv Hf a')) := sigma_equiv_sigma Hf (λ a, equiv_ap B !right_inv⁻¹) definition sigma_equiv_sigma_left' [constructor] (Hf : A' ≃ A) : (Σa, B (Hf a)) ≃ (Σa', B a') := sigma_equiv_sigma Hf (λa, erfl) definition ap_sigma_functor_eq_dpair (p : a = a') (q : b =[p] b') : ap (sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) (pathover.rec_on q idpo) := by induction q; reflexivity -- definition ap_sigma_functor_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) -- : ap (sigma_functor f g) (sigma_eq p q) = -- sigma_eq (ap f p) -- ((tr_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) := -- by induction u; induction v; apply ap_sigma_functor_eq_dpair /- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/ definition is_equiv_pr1 [instance] [constructor] (B : A → Type) [H : Π a, is_contr (B a)] : is_equiv (@pr1 A B) := adjointify pr1 (λa, ⟨a, !center⟩) (λa, idp) (λu, sigma_eq idp (pathover_idp_of_eq !center_eq)) definition sigma_equiv_of_is_contr_right [constructor] [H : Π a, is_contr (B a)] : (Σa, B a) ≃ A := equiv.mk pr1 _ /- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/ definition sigma_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A] : (Σa, B a) ≃ B (center A) := equiv.MK (λu, (center_eq u.1)⁻¹ ▸ u.2) (λb, ⟨!center, b⟩) abstract (λb, ap (λx, x ▸ b) !prop_eq_of_is_contr) end abstract (λu, sigma_eq !center_eq !tr_pathover) end /- Associativity -/ --this proof is harder than in Coq because we don't have eta definitionally for sigma definition sigma_assoc_equiv [constructor] (C : (Σa, B a) → Type) : (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩) (λuc, ⟨uc.1.1, uc.1.2, !sigma.eta⁻¹ ▸ uc.2⟩) abstract begin intro uc, induction uc with u c, induction u, reflexivity end end abstract begin intro av, induction av with a v, induction v, reflexivity end end) open prod prod.ops definition assoc_equiv_prod [constructor] (C : (A × A') → Type) : (Σa a', C (a,a')) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨(av.1, av.2.1), av.2.2⟩) (λuc, ⟨pr₁ (uc.1), pr₂ (uc.1), !prod.eta⁻¹ ▸ uc.2⟩) abstract proof (λuc, destruct uc (λu, prod.destruct u (λa b c, idp))) qed end abstract proof (λav, destruct av (λa v, destruct v (λb c, idp))) qed end) /- Symmetry -/ definition comm_equiv_unc (C : A × A' → Type) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) := calc (Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod ... ≃ Σv, C (flip v) : sigma_equiv_sigma !prod_comm_equiv (λu, prod.destruct u (λa a', equiv.rfl)) ... ≃ Σa' a, C (a, a') : assoc_equiv_prod definition sigma_comm_equiv [constructor] (C : A → A' → Type) : (Σa a', C a a') ≃ (Σa' a, C a a') := comm_equiv_unc (λu, C (prod.pr1 u) (prod.pr2 u)) definition equiv_prod [constructor] (A B : Type) : (Σ(a : A), B) ≃ A × B := equiv.mk _ (adjointify (λs, (s.1, s.2)) (λp, ⟨pr₁ p, pr₂ p⟩) proof (λp, prod.destruct p (λa b, idp)) qed proof (λs, destruct s (λa b, idp)) qed) definition comm_equiv_nondep (A B : Type) : (Σ(a : A), B) ≃ Σ(b : B), A := calc (Σ(a : A), B) ≃ A × B : equiv_prod ... ≃ B × A : prod_comm_equiv ... ≃ Σ(b : B), A : equiv_prod definition sigma_assoc_comm_equiv {A : Type} (B C : A → Type) : (Σ(v : Σa, B a), C v.1) ≃ (Σ(u : Σa, C a), B u.1) := calc (Σ(v : Σa, B a), C v.1) ≃ (Σa (b : B a), C a) : sigma_assoc_equiv ... ≃ (Σa (c : C a), B a) : sigma_equiv_sigma_right (λa, !comm_equiv_nondep) ... ≃ (Σ(u : Σa, C a), B u.1) : sigma_assoc_equiv /- Interaction with other type constructors -/ definition sigma_empty_left [constructor] (B : empty → Type) : (Σx, B x) ≃ empty := begin fapply equiv.MK, { intro v, induction v, contradiction}, { intro x, contradiction}, { intro x, contradiction}, { intro v, induction v, contradiction}, end definition sigma_empty_right [constructor] (A : Type) : (Σ(a : A), empty) ≃ empty := begin fapply equiv.MK, { intro v, induction v, contradiction}, { intro x, contradiction}, { intro x, contradiction}, { intro v, induction v, contradiction}, end definition sigma_unit_left [constructor] (B : unit → Type) : (Σx, B x) ≃ B star := !sigma_equiv_of_is_contr_left definition sigma_unit_right [constructor] (A : Type) : (Σ(a : A), unit) ≃ A := !sigma_equiv_of_is_contr_right definition sigma_sum_left [constructor] (B : A + A' → Type) : (Σp, B p) ≃ (Σa, B (inl a)) + (Σa, B (inr a)) := begin fapply equiv.MK, { intro v, induction v with p b, induction p, { apply inl, constructor, assumption }, { apply inr, constructor, assumption }}, { intro p, induction p with v v: induction v; constructor; assumption}, { intro p, induction p with v v: induction v; reflexivity}, { intro v, induction v with p b, induction p: reflexivity}, end definition sigma_sum_right [constructor] (B C : A → Type) : (Σa, B a + C a) ≃ (Σa, B a) + (Σa, C a) := begin fapply equiv.MK, { intro v, induction v with a p, induction p, { apply inl, constructor, assumption}, { apply inr, constructor, assumption}}, { intro p, induction p with v v, { induction v, constructor, apply inl, assumption }, { induction v, constructor, apply inr, assumption }}, { intro p, induction p with v v: induction v; reflexivity}, { intro v, induction v with a p, induction p: reflexivity}, end definition sigma_sigma_eq_right {A : Type} (a : A) (P : Π(b : A), a = b → Type) : (Σ(b : A) (p : a = b), P b p) ≃ P a idp := calc (Σ(b : A) (p : a = b), P b p) ≃ (Σ(v : Σ(b : A), a = b), P v.1 v.2) : sigma_assoc_equiv ... ≃ P a idp : !sigma_equiv_of_is_contr_left definition sigma_sigma_eq_left {A : Type} (a : A) (P : Π(b : A), b = a → Type) : (Σ(b : A) (p : b = a), P b p) ≃ P a idp := calc (Σ(b : A) (p : b = a), P b p) ≃ (Σ(v : Σ(b : A), b = a), P v.1 v.2) : sigma_assoc_equiv ... ≃ P a idp : !sigma_equiv_of_is_contr_left /- ** Universal mapping properties -/ /- *** The positive universal property. -/ section definition is_equiv_sigma_rec [instance] (C : (Σa, B a) → Type) : is_equiv (sigma.rec : (Πa b, C ⟨a, b⟩) → Πab, C ab) := adjointify _ (λ g a b, g ⟨a, b⟩) (λ g, proof eq_of_homotopy (λu, destruct u (λa b, idp)) qed) (λ f, refl f) definition equiv_sigma_rec (C : (Σa, B a) → Type) : (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) := equiv.mk sigma.rec _ /- *** The negative universal property. -/ protected definition coind_unc (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A) : Σ(b : B a), C a b := ⟨fg.1 a, fg.2 a⟩ protected definition coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b := sigma.coind_unc ⟨f, g⟩ a --is the instance below dangerous? --in Coq this can be done without function extensionality definition is_equiv_coind [instance] (C : Πa, B a → Type) : is_equiv (@sigma.coind_unc _ _ C) := adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩) (λ h, proof eq_of_homotopy (λu, !sigma.eta) qed) (λfg, destruct fg (λ(f : Π (a : A), B a) (g : Π (x : A), C x (f x)), proof idp qed)) definition sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) := equiv.mk sigma.coind_unc _ end /- Subtypes (sigma types whose second components are props) -/ definition subtype [reducible] {A : Type} (P : A → Type) [H : Πa, is_prop (P a)] := Σ(a : A), P a notation [parsing_only] `{` binder `|` r:(scoped:1 P, subtype P) `}` := r /- To prove equality in a subtype, we only need equality of the first component. -/ definition subtype_eq [unfold_full] [H : Πa, is_prop (B a)] {u v : {a | B a}} : u.1 = v.1 → u = v := sigma_eq_unc ∘ inv pr1 definition is_equiv_subtype_eq [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a}) : is_equiv (subtype_eq : u.1 = v.1 → u = v) := !is_equiv_compose local attribute is_equiv_subtype_eq [instance] definition equiv_subtype [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a}) : (u.1 = v.1) ≃ (u = v) := equiv.mk !subtype_eq _ definition subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_prop (B a)] (u v : Σa, B a) : u = v → u.1 = v.1 := subtype_eq⁻¹ᶠ local attribute subtype_eq_inv [reducible] definition is_equiv_subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_prop (B a)] (u v : Σa, B a) : is_equiv (subtype_eq_inv u v) := _ /- truncatedness -/ theorem is_trunc_sigma (B : A → Type) (n : trunc_index) [HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) := begin revert A B HA HB, induction n with n IH, { intro A B HA HB, fapply is_trunc_equiv_closed_rev, apply sigma_equiv_of_is_contr_left}, { intro A B HA HB, apply is_trunc_succ_intro, intro u v, apply is_trunc_equiv_closed_rev, apply sigma_eq_equiv, exact IH _ _ _ _} end theorem is_trunc_subtype (B : A → Prop) (n : trunc_index) [HA : is_trunc (n.+1) A] : is_trunc (n.+1) (Σa, B a) := @(is_trunc_sigma B (n.+1)) _ (λa, !is_trunc_succ_of_is_prop) /- if the total space is a mere proposition, you can equate two points in the base type by finding points in their fibers -/ definition eq_base_of_is_prop_sigma {A : Type} (B : A → Type) (H : is_prop (Σa, B a)) {a a' : A} (b : B a) (b' : B a') : a = a' := (is_prop.elim ⟨a, b⟩ ⟨a', b'⟩)..1 end sigma attribute sigma.is_trunc_sigma [instance] [priority 1490] attribute sigma.is_trunc_subtype [instance] [priority 1200] namespace sigma /- pointed sigma type -/ open pointed definition pointed_sigma [instance] [constructor] {A : Type} (P : A → Type) [G : pointed A] [H : pointed (P pt)] : pointed (Σx, P x) := pointed.mk ⟨pt,pt⟩ definition psigma [constructor] {A : Type*} (P : A → Type*) : Type* := pointed.mk' (Σa, P a) notation `Σ*` binders `, ` r:(scoped P, psigma P) := r definition ppr1 [constructor] {A : Type*} {B : A → Type*} : (Σ*(x : A), B x) →* A := pmap.mk pr1 idp definition ppr2 [unfold_full] {A : Type*} {B : A → Type*} (v : (Σ*(x : A), B x)) : B (ppr1 v) := pr2 v definition ptsigma [constructor] {n : ℕ₋₂} {A : n-Type*} (P : A → n-Type*) : n-Type* := ptrunctype.mk' n (Σa, P a) end sigma
aa49d26c2444494af73185f37c6545e7f84f535c
16af888b14ca6cb84a768588040792cda8158ab8
/src/mathematica.lean
faa108856f537589f84eb00f3acb031377ddfb32
[]
no_license
robertylewis/mathematica
e67c9ad9ca2b2cdd4a26799ee8ff447a6a199cc8
5fa094b9a390a71821ba3f11aa2fd40377d6b017
refs/heads/master
1,670,299,844,147
1,668,914,224,000
1,668,914,224,000
99,119,937
26
4
null
1,553,861,645,000
1,501,680,840,000
Lean
UTF-8
Lean
false
false
30,159
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import .mathematica_parser system.io open expr string level name binder_info native namespace list variables {α β : Type} universes u v w def for : list α → (α → β) → list β := flip map end list meta def rb_lmap.of_list {key : Type} {data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data | [] := rb_lmap.mk key data | ((k, v)::ls) := rb_lmap.insert (rb_lmap.of_list ls) k v meta def rb_map.insert_list {key : Type} {data : Type} : rb_map key data → list (key × data) → rb_map key data | m [] := m | m ((k, d) :: t) := rb_map.insert_list (rb_map.insert m k d) t local attribute [instance] htfi -- this has the expected behavior only if i is under the max size of unsigned def unsigned_of_int (i : int) : unsigned := int.rec_on i (λ k, unsigned.of_nat k) (λ k, unsigned.of_nat k) meta def expand_let : expr → expr | (elet nm tp val bod) := expr.replace bod (λ e n, match e with |var n := some val | _ := none end) | e := e /- The following definitions are used to reflect Lean syntax into Mathematica. We reflect the types - name - level - list level - binder_info - expr -/ namespace mathematica meta def form_of_name : name → string | anonymous := "LeanNameAnonymous" | (mk_string s nm) := "LeanNameMkString[\"" ++ s ++ "\", " ++ form_of_name nm ++ "]" | (mk_numeral i nm) := "LeanNameMkNum[" ++ to_string i ++ ", " ++ form_of_name nm ++ "]" meta def form_of_lvl : level → string | zero := "LeanZeroLevel" | (succ l) := "LeanLevelSucc[" ++ form_of_lvl l ++ "]" | (level.max l1 l2) := "LeanLevelMax[" ++ form_of_lvl l1 ++ ", " ++ form_of_lvl l2 ++ "]" | (imax l1 l2) := "LeanLevelIMax[" ++ form_of_lvl l1 ++ ", " ++ form_of_lvl l2 ++ "]" | (param nm) := "LeanLevelParam[" ++ form_of_name nm ++ "]" | (mvar nm) := "LeanLevelMeta[" ++ form_of_name nm ++ "]" meta def form_of_lvl_list : list level → string | [] := "LeanLevelListNil" | (h :: t) := "LeanLevelListCons[" ++ form_of_lvl h ++ ", " ++ form_of_lvl_list t ++ "]" meta def form_of_binder_info : binder_info → string | binder_info.default := "BinderInfoDefault" | implicit := "BinderInfoImplicit" | strict_implicit := "BinderInfoStrictImplicit" | inst_implicit := "BinderInfoInstImplicit" | other := "BinderInfoOther" /- let expressions get unfolded before translation. translating macro expressions is not supported. -/ meta def form_of_expr : expr → string | (var i) := "LeanVar[" ++ (format.to_string (to_fmt i) options.mk) ++ "]" | (sort lvl) := "LeanSort[" ++ form_of_lvl lvl ++ "]" | (const nm lvls) := "LeanConst[" ++ form_of_name nm ++ ", " ++ form_of_lvl_list lvls ++ "]" | (mvar nm nm' tp) := "LeanMetaVar[" ++ form_of_name nm ++ ", " ++ form_of_expr tp ++ "]" | (local_const nm ppnm bi tp) := "LeanLocal[" ++ form_of_name nm ++ ", " ++ form_of_name ppnm ++ ", " ++ form_of_binder_info bi ++ ", " ++ form_of_expr tp ++ "]" | (app f e) := "LeanApp[" ++ form_of_expr f ++ ", " ++ form_of_expr e ++ "]" | (lam nm bi tp bod) := "LeanLambda[" ++ form_of_name nm ++ ", " ++ form_of_binder_info bi ++ ", " ++ form_of_expr tp ++ ", " ++ form_of_expr bod ++ "]" | (pi nm bi tp bod) := "LeanPi[" ++ form_of_name nm ++ ", " ++ form_of_binder_info bi ++ ", " ++ form_of_expr tp ++ ", " ++ form_of_expr bod ++ "]" | (elet nm tp val bod) := form_of_expr $ expand_let $ elet nm tp val bod | (macro mdf mlst) := "LeanMacro" /- The following definitions are used to make pexprs out of various types. -/ end mathematica meta def pexpr_of_nat : ℕ → pexpr | 0 := ```(0) | 1 := ```(1) | k := if k%2=0 then ```(bit0 %%(pexpr_of_nat (k/2))) else ```(bit1 %%(pexpr_of_nat (k/2))) meta def pexpr_of_int : int → pexpr | (int.of_nat n) := pexpr_of_nat n | (int.neg_succ_of_nat n) := ```(-%%(pexpr_of_nat (n+1))) namespace tactic namespace mathematica section def write_file (fn : string) (cnts : string) (mode := io.mode.write) : io unit := do h ← io.mk_file_handle fn io.mode.write, io.fs.write h cnts.to_char_buffer, io.fs.close h end /-- execute str evaluates str in Mathematica. The evaluation happens in a unique context; declarations that are made during evaluation will not be available in future evaluations. -/ meta def execute (cmd : string) (add_args : list string := []) : tactic char_buffer := let cmd' := escape_term cmd ++ "&!", args := ["_target/deps/mathematica/src/client2.py"].append add_args in if cmd'.length < 2040 then tactic.unsafe_run_io $ io.buffer_cmd { cmd := "python3", args := args.append [/-escape_quotes -/cmd'] } else do path ← mathematica.temp_file_name "exch", unsafe_run_io $ write_file path cmd' io.mode.write, unsafe_run_io $ io.buffer_cmd { cmd := "python3", args := args.append ["-f", path] } def get_cwd : io string := io.cmd {cmd := "pwd"} >>= λ s, pure $ strip_newline s meta def execute_and_eval (cmd : string) : tactic mmexpr := execute cmd >>= parse_mmexpr_tac /-- execute_global str evaluates str in Mathematica. The evaluation happens in the global context; declarations that are made during evaluation will persist. -/ meta def execute_global (cmd : string) : tactic char_buffer := execute cmd ["-g"] /-- Returns the path to {run_directory}/extras/ -/ meta def extras_path : tactic string := unsafe_run_io get_cwd >>= λ s, pure $ strip_trailing_whitespace s ++ "/src/extras/" end mathematica end tactic namespace mathematica open mmexpr tactic private meta def pexpr_mk_app : pexpr → list pexpr → pexpr | fn [] := fn | fn (h::t) := pexpr_mk_app (app fn h) t section translation open rb_lmap @[reducible] meta def trans_env := rb_map string expr meta def trans_env.empty := rb_map.mk string expr meta def sym_trans_pexpr_rule := string × pexpr meta def sym_trans_expr_rule := string × expr meta def app_trans_pexpr_keyed_rule := string × (trans_env → list mmexpr → tactic pexpr) meta def app_trans_expr_keyed_rule := string × (trans_env → list mmexpr → tactic expr) meta def app_trans_pexpr_unkeyed_rule := trans_env → mmexpr → list mmexpr → tactic pexpr meta def app_trans_expr_unkeyed_rule := trans_env → mmexpr → list mmexpr → tactic expr -- databases private meta def mk_sym_trans_pexpr_db (l : list name) : tactic (rb_lmap string pexpr) := do dcls ← monad.mapm (λ n, mk_const n >>= eval_expr sym_trans_pexpr_rule) l, return $ of_list dcls private meta def mk_sym_trans_expr_db (l : list name) : tactic (rb_lmap string expr) := do dcls ← monad.mapm (λ n, mk_const n >>= eval_expr sym_trans_expr_rule) l, return $ of_list dcls private meta def mk_app_trans_pexpr_keyed_db (l : list name) : tactic (rb_lmap string (trans_env → list mmexpr → tactic pexpr)) := do dcls ← monad.mapm (λ n, mk_const n >>= eval_expr app_trans_pexpr_keyed_rule) l, return $ of_list dcls private meta def mk_app_trans_expr_keyed_db (l : list name) : tactic (rb_lmap string (trans_env → list mmexpr → tactic expr)) := do dcls ← monad.mapm (λ n, mk_const n >>= eval_expr app_trans_expr_keyed_rule) l, return $ of_list dcls private meta def mk_app_trans_pexpr_unkeyed_db (l : list name) : tactic (list (trans_env → mmexpr → list mmexpr → tactic pexpr)) := monad.mapm (λ n, mk_const n >>= eval_expr app_trans_pexpr_unkeyed_rule) l private meta def mk_app_trans_expr_unkeyed_db (l : list name) : tactic (list (trans_env → mmexpr → list mmexpr → tactic expr)) := monad.mapm (λ n, mk_const n >>= eval_expr app_trans_expr_unkeyed_rule) l meta def ensure_has_type (e : expr) : name → nat → bool → command := λ decl_name _ _, do dcl ← get_decl decl_name, is_def_eq e (dcl.type) @[user_attribute] private meta def sym_to_pexpr_rule : user_attribute (rb_lmap string pexpr) unit := { name := `sym_to_pexpr, descr := "rule for translating a mmexpr.sym to a pexpr", cache_cfg := ⟨mk_sym_trans_pexpr_db, []⟩, after_set := ensure_has_type `(sym_trans_pexpr_rule) } @[user_attribute] private meta def sym_to_expr_rule : user_attribute (rb_lmap string expr) unit := { name := `sym_to_expr, descr := "rule for translating a mmexpr.sym to a expr", cache_cfg := ⟨mk_sym_trans_expr_db, []⟩, after_set := ensure_has_type `(sym_trans_expr_rule) } @[user_attribute] private meta def app_to_pexpr_keyed_rule : user_attribute (rb_lmap string (trans_env → list mmexpr → tactic pexpr)) := { name := `app_to_pexpr_keyed, descr := "rule for translating a mmexpr.app to a pexpr", cache_cfg := ⟨mk_app_trans_pexpr_keyed_db, []⟩, after_set := ensure_has_type `(app_trans_pexpr_keyed_rule) } @[user_attribute] private meta def app_to_expr_keyed_rule : user_attribute (rb_lmap string (trans_env → list mmexpr → tactic expr)) := { name := `app_to_expr_keyed, descr := "rule for translating a mmexpr.app to a expr", cache_cfg := ⟨mk_app_trans_expr_keyed_db, []⟩, after_set := ensure_has_type `(app_trans_expr_keyed_rule) } @[user_attribute] private meta def app_to_pexpr_unkeyed_rule : user_attribute (list (trans_env → mmexpr → list mmexpr → tactic pexpr)) := { name := `app_to_pexpr_unkeyed, descr := "rule for translating a mmexpr.app to a pexpr", cache_cfg := ⟨mk_app_trans_pexpr_unkeyed_db, []⟩, after_set := ensure_has_type `(app_trans_pexpr_unkeyed_rule) } @[user_attribute] private meta def app_to_expr_unkeyed_rule : user_attribute (list (trans_env → mmexpr → list mmexpr → tactic expr)) := { name := `app_to_expr_unkeyed, descr := "rule for translating a mmexpr.app to a expr", cache_cfg := ⟨mk_app_trans_expr_unkeyed_db, []⟩, after_set := ensure_has_type `(app_trans_expr_unkeyed_rule) } private meta def expr_of_mmexpr_app_keyed (env : trans_env) : mmexpr → list mmexpr → tactic expr | (sym hd) args := do expr_db ← app_to_expr_keyed_rule.get_cache, tactic.first $ (rb_lmap.find expr_db hd).for $ λ f, f env args | _ _ := failed private meta def expr_of_mmexpr_app_unkeyed (env : trans_env) (hd : mmexpr) (args : list mmexpr) : tactic expr := do expr_db ← app_to_expr_unkeyed_rule.get_cache, tactic.first (list.map (λ f : trans_env → mmexpr → list mmexpr → tactic expr, f env hd args) expr_db) private meta def expr_of_mmexpr_app (env : trans_env) (expr_of_mmexpr : trans_env → mmexpr → tactic expr) (m : mmexpr) (l : list mmexpr) : tactic expr := expr_of_mmexpr_app_keyed env m l <|> expr_of_mmexpr_app_unkeyed env m l private meta def pexpr_of_mmexpr_app_keyed (env : trans_env) : mmexpr → list mmexpr → tactic pexpr | (sym hd) args := do expr_db ← app_to_pexpr_keyed_rule.get_cache, tactic.first $ (rb_lmap.find expr_db hd).for $ λ f, f env args | _ _ := failed private meta def pexpr_of_mmexpr_app_unkeyed (env : trans_env) (hd : mmexpr) (args : list mmexpr) : tactic pexpr := do expr_db ← app_to_pexpr_unkeyed_rule.get_cache, tactic.first (list.map (λ f : trans_env → mmexpr → list mmexpr → tactic pexpr, f env hd args) expr_db) private meta def pexpr_of_mmexpr_app_decomp (env : trans_env) (pexpr_of_mmexpr : trans_env → mmexpr → tactic pexpr) (hd : mmexpr) (args : list mmexpr) : tactic pexpr := do hs ← pexpr_of_mmexpr env hd, args' ← monad.mapm (pexpr_of_mmexpr env) args, return $ pexpr_mk_app hs args' private meta def pexpr_of_mmexpr_app (env : trans_env) (pexpr_of_mmexpr : trans_env → mmexpr → tactic pexpr) (m : mmexpr) (l : list mmexpr) : tactic pexpr := pexpr_of_mmexpr_app_keyed env m l <|> pexpr_of_mmexpr_app_unkeyed env m l <|> pexpr_of_mmexpr_app_decomp env pexpr_of_mmexpr m l private meta def find_in_env (env : trans_env) (sym : string) : tactic expr := match rb_map.find env sym with | some e := return e | none := failed end /-- expr_of_mmexpr env m will attempt to translate m to an expr, using translation rules found by the attribute manager. env maps symbols (representing bound variables) to placeholder exprs. -/ meta def expr_of_mmexpr : trans_env → mmexpr → tactic expr | env (sym s) := find_in_env env s <|> do expr_db ← sym_to_expr_rule.get_cache, match rb_lmap.find expr_db s with | (h :: t) := return h | [] := fail ("Couldn't find translation for sym \"" ++ s ++ "\"") end | env (mstr s) := return (string.reflect s)--to_expr (_root_.quote s) | env (mreal r) := return (reflect r) | env (app hd args) := expr_of_mmexpr_app env expr_of_mmexpr hd args | env (mint i) := failed private meta def pexpr_of_mmexpr_aux (env : trans_env) (pexpr_of_mmexpr : trans_env → mmexpr → tactic pexpr) : mmexpr → tactic pexpr | (sym s) := do expr_db ← sym_to_pexpr_rule.get_cache, match rb_lmap.find expr_db s with | (h :: t) := return h | [] := parse_name_tac s >>= resolve_name <|> fail ("Couldn't find translation for sym \"" ++ s ++ "\"") end | (mint i ) := return $ pexpr_of_int i | (app hd args) := pexpr_of_mmexpr_app env pexpr_of_mmexpr hd args | (mstr s) := fail "unreachable, str case shouldn't reach pexpr_of_mmexpr_aux" | (mreal r) := fail "unreachable, real case shouldn't reach pexpr_of_mmexpr_aux" /-- pexpr_of_mmexpr env m will attempt to translate m to a pexpr, using translation rules found by the attribute manager. env maps symbols (representing bound variables) to placeholder exprs. -/ meta def pexpr_of_mmexpr : trans_env → mmexpr → tactic pexpr := λ env m, (do e ← expr_of_mmexpr env m, return ```(%%e)) <|> (pexpr_of_mmexpr_aux env pexpr_of_mmexpr m) end translation section unreflect meta def level_of_mmexpr : mmexpr → tactic level | (sym "LeanZeroLevel") := return $ level.zero | (app (sym "LeanLevelSucc") [m]) := do m' ← level_of_mmexpr m, return $ level.succ m' | (app (sym "LeanLevelMax") [m1, m2]) := do m1' ← level_of_mmexpr m1, m2' ← level_of_mmexpr m2, return $ level.max m1' m2' | (app (sym "LeanLevelIMax") [m1, m2]) := do m1' ← level_of_mmexpr m1, m2' ← level_of_mmexpr m2, return $ level.imax m1' m2' | (app (sym "LeanLevelParam") [mstr s]) := return $ level.param s | (app (sym "LeanLevelMeta") [mstr s]) := return $ level.mvar s | _ := failed meta def level_list_of_mmexpr : mmexpr → tactic (list level) | (sym "LeanLevelListNil") := return [] | (app (sym "LeanLevelListCons") [h, t]) := do h' ← level_of_mmexpr h, t' ← level_list_of_mmexpr t, return $ h' :: t' | _ := failed meta def name_of_mmexpr : mmexpr → tactic name | (sym "LeanNameAnonymous") := return $ name.anonymous | (app (sym "LeanNameMkString") [mstr s, m]) := do n ← name_of_mmexpr m, return $ name.mk_string s n | (app (sym "LeanNameMkNum") [mint i, m]) := do n ← name_of_mmexpr m, return $ name.mk_numeral (unsigned_of_int i) n | _ := failed meta def binder_info_of_mmexpr : mmexpr → tactic binder_info | (sym "BinderInfoDefault") := return $ binder_info.default | (sym "BinderInfoImplicit") := return $ binder_info.implicit | (sym "BinderInfoStrictImplicit") := return $ binder_info.strict_implicit | (sym "BinderInfoInstImplicit") := return $ binder_info.inst_implicit | (sym "BinderInfoOther") := return $ binder_info.aux_decl | _ := failed end unreflect section transl_expr_instances @[app_to_expr_keyed] meta def mmexpr_var_to_expr : app_trans_expr_keyed_rule := ⟨"LeanVar", λ _ args, match args with | [mint i] := return $ var (i.nat_abs) | _ := failed end⟩ @[app_to_expr_keyed] meta def mmexpr_sort_to_expr : app_trans_expr_keyed_rule := ⟨"LeanSort", λ _ args, match args with | [m] := do lvl ← level_of_mmexpr m, return $ sort lvl | _ := failed end⟩ @[app_to_expr_keyed] meta def mmexpr_const_to_expr : app_trans_expr_keyed_rule := ⟨"LeanConst", λ _ args, match args with | [nm, lvls] := do nm' ← name_of_mmexpr nm, lvls' ← level_list_of_mmexpr lvls, return $ const nm' lvls' | _ := failed end⟩ @[app_to_expr_keyed] meta def mmexpr_mvar_to_expr : app_trans_expr_keyed_rule := ⟨"LeanMetaVar", λ env args, match args with | [nm, tp] := do nm' ← name_of_mmexpr nm, tp' ← expr_of_mmexpr env tp, return $ mvar nm' `workaround tp' | _ := failed end⟩ @[app_to_expr_keyed] meta def mmexpr_local_to_expr : app_trans_expr_keyed_rule := ⟨"LeanLocal", λ env args, match args with | [nm, ppnm, bi, tp] := do nm' ← name_of_mmexpr nm, ppnm' ← name_of_mmexpr ppnm, bi' ← binder_info_of_mmexpr bi, tp' ← expr_of_mmexpr env tp, return $ expr.local_const nm' ppnm' bi' tp' | _ := failed end⟩ @[app_to_expr_keyed] meta def mmexpr_app_to_expr : app_trans_expr_keyed_rule := ⟨"LeanApp", λ env args, match args with | [hd, bd] := do hd' ← expr_of_mmexpr env hd, bd' ← expr_of_mmexpr env bd, return $ expr.app hd' bd' | _ := failed end⟩ @[app_to_expr_keyed] meta def mmexpr_lam_to_expr : app_trans_expr_keyed_rule := ⟨"LeanLambda", λ env args, match args with | [nm, bi, tp, bd] := do nm' ← name_of_mmexpr nm, bi' ← binder_info_of_mmexpr bi, tp' ← expr_of_mmexpr env tp, bd' ← expr_of_mmexpr env bd, return $ lam nm' bi' tp' bd' | _ := failed end⟩ @[app_to_expr_keyed] meta def mmexpr_pi_to_expr : app_trans_expr_keyed_rule := ⟨"LeanPi", λ env args, match args with | [nm, bi, tp, bd] := do nm' ← name_of_mmexpr nm, bi' ← binder_info_of_mmexpr bi, tp' ← expr_of_mmexpr env tp, bd' ← expr_of_mmexpr env bd, return $ lam nm' bi' tp' bd' | _ := failed end⟩ meta def pexpr_fold_op_aux (op : pexpr) : pexpr → list pexpr → pexpr | e [] := e | e (h::t) := pexpr_fold_op_aux ```(%%op %%e %%h) t meta def pexpr_fold_op (dflt op : pexpr) : list pexpr → pexpr | [] := dflt | [h] := h | (h::t) := pexpr_fold_op_aux op h t -- pexpr instances @[app_to_pexpr_keyed] meta def add_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Plus", λ env args, do args' ← monad.mapm (pexpr_of_mmexpr env) args, return $ pexpr_fold_op ```(0) ```(has_add.add) args'⟩ @[app_to_pexpr_keyed] meta def mul_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Times", λ env args, do args' ← monad.mapm (pexpr_of_mmexpr env) args, return $ pexpr_fold_op ```(1) ```(has_mul.mul) args'⟩ @[app_to_pexpr_keyed] meta def power_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Power", λ env args, match args with | [base, exp] := do base ← pexpr_of_mmexpr env base, exp ← pexpr_of_mmexpr env exp, return ``(%%base ^ %%exp) | _ := failed end⟩ @[app_to_pexpr_keyed] meta def list_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"List", λ env args, do args' ← monad.mapm (pexpr_of_mmexpr env) args, return $ list.foldr (λ h t, ```(%%h :: %%t)) ```([]) args'⟩ @[app_to_pexpr_keyed] meta def and_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"And", λ env args, do args' ← monad.mapm (pexpr_of_mmexpr env) args, return $ pexpr_fold_op ```(true) ```(and) args'⟩ @[app_to_pexpr_keyed] meta def or_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Or", λ env args, do args' ← monad.mapm (pexpr_of_mmexpr env) args, return $ pexpr_fold_op ```(false) ```(or) args'⟩ @[app_to_pexpr_keyed] meta def not_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Not", λ env args, match args with | [t] := do t' ← pexpr_of_mmexpr env t, return ```(¬ %%t') | _ := failed end⟩ @[app_to_pexpr_keyed] meta def implies_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Implies", λ env args, match args with | [h,c] := do h' ← pexpr_of_mmexpr env h, c' ← pexpr_of_mmexpr env c, return $ ```(%%h' → %%c') | _ := failed end⟩ @[app_to_pexpr_keyed] meta def hold_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Hold", λ env args, match args with | [h] := pexpr_of_mmexpr env h | _ := failed end⟩ private meta def replace_holds : mmexpr → list mmexpr | (app (sym "Hold") l) := l | m := [m] meta def is_hold : mmexpr → bool | (app (sym "Hold") l) := tt | _ := ff /-- F[Hold[a1, ..., an]] is equivalent to F[a1, ..., an]. F[t1, ..., Hold[p, q], ..., tn] is equivalent to F[t1, ..., p, q, ..., tn] -/ @[app_to_pexpr_unkeyed] meta def app_mvar_hold_to_pexpr : app_trans_pexpr_unkeyed_rule | env head [app (sym "Hold") l] := pexpr_of_mmexpr env (app head l) | env head l := if l.any is_hold then let ls := (l.map replace_holds).join in pexpr_of_mmexpr env (app head ls) else failed @[app_to_pexpr_unkeyed] meta def app_inactive_to_pexpr : app_trans_pexpr_unkeyed_rule | env (app (sym "Inactive") [t]) l := pexpr_of_mmexpr env (app t l) | _ _ _ := failed meta def pexpr.to_raw_expr : pexpr → expr | (var n) := var n | (sort l) := sort l | (const nm ls) := const nm ls | (mvar n n' e) := mvar n n' (pexpr.to_raw_expr e) | (local_const nm ppnm bi tp) := local_const nm ppnm bi (pexpr.to_raw_expr tp) | (app f a) := app (pexpr.to_raw_expr f) (pexpr.to_raw_expr a) | (lam nm bi tp bd) := lam nm bi (pexpr.to_raw_expr tp) (pexpr.to_raw_expr bd) | (pi nm bi tp bd) := pi nm bi (pexpr.to_raw_expr tp) (pexpr.to_raw_expr bd) | (elet nm tp df bd) := elet nm (pexpr.to_raw_expr tp) (pexpr.to_raw_expr df) (pexpr.to_raw_expr bd) | (macro md l) := macro md (l.map pexpr.to_raw_expr) meta def pexpr.of_raw_expr : expr → pexpr | (var n) := var n | (sort l) := sort l | (const nm ls) := const nm ls | (mvar n n' e) := mvar n n' (pexpr.of_raw_expr e) | (local_const nm ppnm bi tp) := local_const nm ppnm bi (pexpr.of_raw_expr tp) | (app f a) := app (pexpr.of_raw_expr f) (pexpr.of_raw_expr a) | (lam nm bi tp bd) := lam nm bi (pexpr.of_raw_expr tp) (pexpr.of_raw_expr bd) | (pi nm bi tp bd) := pi nm bi (pexpr.of_raw_expr tp) (pexpr.of_raw_expr bd) | (elet nm tp df bd) := elet nm (pexpr.of_raw_expr tp) (pexpr.of_raw_expr df) (pexpr.of_raw_expr bd) | (macro md l) := macro md (l.map pexpr.of_raw_expr) meta def mk_local_const_placeholder (n : name) : expr := let t := pexpr.mk_placeholder in local_const n n binder_info.default (pexpr.to_raw_expr t) meta def mk_local_const (n : name) (tp : pexpr): expr := local_const n n binder_info.default (pexpr.to_raw_expr tp) private meta def sym_to_lcs_using (env : trans_env) (e : mmexpr) : mmexpr → tactic (string × expr) | (sym s) := do p ← pexpr_of_mmexpr env e, return $ (s, mk_local_const s p) | _ := failed meta def sym_to_lcp : mmexpr → tactic (string × expr) | (sym s) := return $ (s, mk_local_const_placeholder s) | _ := failed meta def mk_lambdas (l : list expr) (b : pexpr) : pexpr := pexpr.of_raw_expr (lambdas l (pexpr.to_raw_expr b)) meta def mk_lambda' (x : expr) (b : pexpr) : pexpr := pexpr.of_raw_expr (lambdas [x] (pexpr.to_raw_expr b)) meta def mk_pis (l : list expr) (b : pexpr) : pexpr := pexpr.of_raw_expr (pis l (pexpr.to_raw_expr b)) meta def mk_pi' (x : expr) (b : pexpr) : pexpr := pexpr.of_raw_expr (pis [x] (pexpr.to_raw_expr b)) @[app_to_pexpr_keyed] meta def function_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Function", λ env args, match args with | [sym x, bd] := do v ← return $ mk_local_const_placeholder x, bd' ← pexpr_of_mmexpr (env.insert x v) bd, return $ mk_lambda' v bd' | [app (sym "List") l, bd] := do vs ← monad.mapm sym_to_lcp l, bd' ← pexpr_of_mmexpr (rb_map.insert_list env vs) bd, return $ mk_lambdas (list.map prod.snd vs) bd' | _ := failed end⟩ @[app_to_pexpr_keyed] meta def forall_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"ForAll", λ env args, match args with | [sym x, bd] := do v ← return $ mk_local_const_placeholder x, bd' ← pexpr_of_mmexpr (env.insert x v) bd, return $ mk_pi' v bd' | [app (sym "List") l, bd] := do vs ← monad.mapm sym_to_lcp l, bd' ← pexpr_of_mmexpr (rb_map.insert_list env vs) bd, return $ mk_pis (list.map prod.snd vs) bd' | [sym x, t, bd] := do v ← return $ mk_local_const_placeholder x, bd' ← pexpr_of_mmexpr (env.insert x v) (app (sym "Implies") [t,bd]), return $ mk_pi' v bd' | _ := failed end⟩ @[app_to_pexpr_keyed] meta def forall_typed_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"ForAllTyped", λ env args, match args with | [sym x, t, bd] := do (n, pe) ← sym_to_lcs_using env t (sym x), bd' ← pexpr_of_mmexpr (env.insert n pe) bd, return $ mk_pi' pe bd' | [app (sym "List") l, t, bd] := do vs ← monad.mapm (sym_to_lcs_using env t) l, bd' ← pexpr_of_mmexpr (rb_map.insert_list env vs) bd, return $ mk_pis (vs.map prod.snd) bd' | _ := failed end⟩ @[app_to_pexpr_keyed] meta def exists_to_pexpr : app_trans_pexpr_keyed_rule := ⟨"Exists", λ env args, match args with | [sym x, bd] := do v ← return $ mk_local_const_placeholder x, bd' ← pexpr_of_mmexpr (env.insert x v) bd, lm ← return $ mk_lambda' v bd', return ``(Exists %%lm) | [app (sym "List") [], bd] := pexpr_of_mmexpr env bd | [app (sym "List") (h::t), bd] := pexpr_of_mmexpr env (app (sym "Exists") [h, app (sym "Exists") [app (sym "List") t, bd]]) | _ := failed end⟩ @[sym_to_pexpr] meta def type_to_pexpr : sym_trans_pexpr_rule := ⟨"Type", ```(Type)⟩ @[sym_to_pexpr] meta def prop_to_pexpr : sym_trans_pexpr_rule := ⟨"Prop", ```(Prop)⟩ @[sym_to_pexpr] meta def inter_to_pexpr : sym_trans_pexpr_rule := ⟨"SetInter", ```(has_inter.inter)⟩ @[sym_to_pexpr] meta def union_to_pexpr : sym_trans_pexpr_rule := ⟨"SetUnion", ```(has_union.union)⟩ @[sym_to_pexpr] meta def compl_to_pexpr : sym_trans_pexpr_rule := ⟨"SetCompl", ```(has_compl.compl)⟩ @[sym_to_pexpr] meta def empty_to_pexpr : sym_trans_pexpr_rule := ⟨"EmptySet", ```(∅)⟩ @[sym_to_pexpr] meta def rat_to_pexpr : sym_trans_pexpr_rule := ⟨"Rational", ```(has_div.div)⟩ @[sym_to_pexpr] meta def eq_to_pexpr : sym_trans_pexpr_rule := ⟨"Equal", ```(eq)⟩ @[sym_to_expr] meta def true_to_expr : sym_trans_expr_rule := ⟨"True", `(true)⟩ @[sym_to_expr] meta def false_to_expr : sym_trans_expr_rule := ⟨"False", `(false)⟩ @[sym_to_pexpr] meta def less_to_pexpr : mathematica.sym_trans_pexpr_rule := ⟨"Less", ``(has_lt.lt)⟩ @[sym_to_pexpr] meta def greater_to_pexpr : mathematica.sym_trans_pexpr_rule := ⟨"Greater", ``(gt)⟩ @[sym_to_pexpr] meta def lesseq_to_pexpr : mathematica.sym_trans_pexpr_rule := ⟨"LessEqual", ``(has_le.le)⟩ @[sym_to_pexpr] meta def greatereq_to_pexpr : mathematica.sym_trans_pexpr_rule := ⟨"GreaterEqual", ``(ge)⟩ end transl_expr_instances end mathematica -- user-facing tactics namespace tactic namespace mathematica open _root_.mathematica meta def mk_get_cmd (path : string) : tactic string := do s ← extras_path, -- return $ "Get[\"" ++ path ++ "\",Path->{DirectoryFormat[\""++ s ++"\"]}];" return $ "Get[\"" ++ path ++ "\",Path->{DirectoryFormat[\""++ s ++"\"]}];" /-- load_file path will load the file found at path into Mathematica. The declarations will persist until the kernel is restarted. -/ meta def load_file (path : string) : tactic unit := do s ← mk_get_cmd path, execute_global s >> return () /-- run_command_on cmd e reflects e into Mathematica syntax, applies cmd to this reflection, evaluates this in Mathematica, and attempts to translate the result to a pexpr. -/ meta def run_command_on (cmd : string → string) (e : expr) : tactic pexpr := do rval ← execute_and_eval $ cmd $ form_of_expr e, --rval' ← eval_expr mmexpr rval, pexpr_of_mmexpr trans_env.empty rval /-- run_command_on_using cmd e path reflects e into Mathematica syntax, applies cmd to this reflection, evaluates this in Mathematica after importing the file at path, and attempts to translate the result to a pexpr. -/ meta def run_command_on_using (cmd : string → string) (e : expr) (path : string) : tactic pexpr := do p ← escape_slash <$> mk_get_cmd path, run_command_on (λ s, p ++ cmd s) e meta def run_command_on_2 (cmd : string → string → string) (e1 e2 : expr) : tactic pexpr := do rval ← execute_and_eval $ cmd (form_of_expr e1) (form_of_expr e2), --rval' ← eval_expr mmexpr rval, pexpr_of_mmexpr trans_env.empty rval /-- run_command_on_2_using cmd e1 e2 reflects e1 and e2 into Mathematica syntax, applies cmd to these reflections, evaluates this in Mathematica after importing the file at path, and attempts to translate the result to a pexpr. -/ meta def run_command_on_2_using (cmd : string → string → string) (e1 e2 : expr) (path : string) : tactic pexpr := do p ← escape_slash <$> mk_get_cmd path, run_command_on_2 (λ s1 s2, p ++ cmd s1 s2) e1 e2 private def sep_string : list string → string | [] := "" | [s] := s | (h::t) := h ++ ", " ++ sep_string t /-- run_command_on_list cmd l reflects each element of l into Mathematica syntax, applies cmd to a Mathematica list of these reflections, evaluates this in Mathematica, and attempts to translate the result to a pexpr. -/ meta def run_command_on_list (cmd : string → string) (l : list expr) : tactic pexpr := let lvs := "{" ++ (sep_string $ l.map form_of_expr) ++ "}" in do rval ← execute_and_eval $ cmd lvs, --rval' ← eval_expr mmexpr rval, pexpr_of_mmexpr trans_env.empty rval meta def run_command_on_list_using (cmd : string → string) (l : list expr) (path : string) : tactic pexpr := let lvs := "{" ++ (sep_string $ l.map form_of_expr) ++ "}" in do p ← mk_get_cmd path, rval ← execute_and_eval $ p ++ cmd lvs, --rval' ← eval_expr mmexpr rval, pexpr_of_mmexpr trans_env.empty rval end mathematica end tactic
df3aab4221adbc556db7bb0bde94d747daf0a2fe
690889011852559ee5ac4dfea77092de8c832e7e
/src/category_theory/limits/cones.lean
0a06ea52ec4251ea4d504e1b4f0762a56f4d2e66
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
14,948
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.const import category_theory.yoneda import category_theory.concrete_category.bundled_hom import category_theory.equivalence universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory -- There is an awkward difficulty with universes here. -- If we allowed `J` to be a small category in `Prop`, we'd run into trouble -- because `yoneda.obj (F : (J ⥤ C)ᵒᵖ)` will be a functor into `Sort (max v 1)`, -- not into `Sort v`. -- So we don't allow this case; it's not particularly useful anyway. variables {J : Type v} [small_category J] variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 open category_theory open category_theory.category open category_theory.functor open opposite namespace category_theory namespace functor variables {J C} (F : J ⥤ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F) lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl @[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) : (F.cones.map f t).app j = f.unop ≫ t.app j := rfl /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F) lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl @[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) : (F.cocones.map f t).app j = t.app j ≫ f := rfl end functor section variables (J C) /-- Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of cones with a given cone point. -/ @[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) := { obj := functor.cones, map := λ F G f, whisker_left (const J).op (yoneda.map f) } /-- Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of cocones with a given cocone point. -/ @[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) := { obj := λ F, functor.cocones (unop F), map := λ F G f, whisker_left (const J) (coyoneda.map f) } end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`. -/ structure cone (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) @[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') : c.π.app j ≫ F.map f = c.π.app j' := by convert ←(c.π.naturality f).symm; apply id_comp /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`. -/ structure cocone (F : J ⥤ C) := (X : C) (ι : F ⟶ (const J).obj X) @[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') : F.map f ≫ c.ι.app j' = c.ι.app j := by convert ←(c.ι.naturality f); apply comp_id variables {F : J ⥤ C} namespace cone def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X := { hom := λ c, ⟨op c.X, c.π⟩, inv := λ c, { X := unop c.1, π := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones := { app := λ X f, ((const J).map f) ≫ c.π } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F := { X := X, π := c.extensions.app (op X) f } @[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) : (extend c f).π = c.extensions.app X f := rfl @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := { X := c.X, π := whisker_left E c.π } -- We now prove a lemma about naturality of cones over functors into bundled categories. section omit 𝒞 variables {J' : Type u} [small_category J'] variables {C' : Type (u+1)} [𝒞' : concrete_category C'] include 𝒞' local attribute [instance] concrete_category.has_coe_to_sort local attribute [instance] concrete_category.has_coe_to_fun /-- Naturality of a cone over functors to a concrete category. -/ @[simp] lemma naturality_concrete {G : J' ⥤ C'} (s : cone G) {j j' : J'} (f : j ⟶ j') (x : s.X) : (G.map f) ((s.π.app j) x) = (s.π.app j') x := begin convert congr_fun (congr_arg (λ k : s.X ⟶ G.obj j', (k : s.X → G.obj j')) (s.π.naturality f).symm) x; { dsimp, simp }, end end end cone namespace cocone def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X := { hom := λ c, ⟨c.X, c.ι⟩, inv := λ c, { X := c.1, ι := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones := { app := λ X f, c.ι ≫ (const J).map f } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F := { X := X, ι := c.extensions.app X f } @[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) : (extend c f).ι = c.extensions.app X f := rfl @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) := { X := c.X, ι := whisker_left E c.ι } -- We now prove a lemma about naturality of cocones over functors into bundled categories. section omit 𝒞 variables {J' : Type u} [small_category J'] variables {C' : Type (u+1)} [𝒞' : concrete_category C'] include 𝒞' local attribute [instance] concrete_category.has_coe_to_sort local attribute [instance] concrete_category.has_coe_to_fun /-- Naturality of a cocone over functors into a concrete category. -/ @[simp] lemma naturality_concrete {G : J' ⥤ C'} (s : cocone G) {j j' : J'} (f : j ⟶ j') (x : G.obj j) : (s.ι.app j') ((G.map f) x) = (s.ι.app j) x := begin convert congr_fun (congr_arg (λ k : G.obj j ⟶ s.X, (k : G.obj j → s.X)) (s.ι.naturality f)) x; { dsimp, simp }, end end end cocone structure cone_morphism (A B : cone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously) restate_axiom cone_morphism.w' attribute [simp] cone_morphism.w @[extensionality] lemma cone_morphism.ext {A B : cone F} {f g : cone_morphism A B} (w : f.hom = g.hom) : f = g := by cases f; cases g; simpa using w @[simps] instance cone.category : category.{v} (cone F) := { hom := λ A B, cone_morphism A B, comp := λ X Y Z f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [assoc, g.w, f.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cones /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[extensionality, simps] def ext {c c' : cone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } } @[simps] def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G := { obj := λ c, { X := c.X, π := c.π ≫ α }, map := λ c₁ c₂ f, { hom := f.hom, w' := by intro; erw ← category.assoc; simp [-category.assoc] } } def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G := begin refine equivalence.mk (postcompose α.hom) (postcompose α.inv) _ _, { symmetry, refine (postcompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact postcompose_id }, { refine (postcompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact postcompose_id } end @[simps] def forget : cone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } section variables {D : Type u'} [𝒟 : category.{v} D] include 𝒟 @[simps] def functoriality (G : C ⥤ D) : cone F ⥤ cone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ X Y f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, f.w] } } end end cones structure cocone_morphism (A B : cocone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously) restate_axiom cocone_morphism.w' attribute [simp] cocone_morphism.w @[extensionality] lemma cocone_morphism.ext {A B : cocone F} {f g : cocone_morphism A B} (w : f.hom = g.hom) : f = g := by cases f; cases g; simpa using w @[simps] instance cocone.category : category.{v} (cocone F) := { hom := λ A B, cocone_morphism A B, comp := λ _ _ _ f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [←assoc, f.w, g.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cocones /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[extensionality, simps] def ext {c c' : cocone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } } @[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := { obj := λ c, { X := c.X, ι := α ≫ c.ι }, map := λ c₁ c₂ f, { hom := f.hom } } def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : precompose (α ≫ β) ≅ precompose β ⋙ precompose α := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G := begin refine equivalence.mk (precompose α.hom) (precompose α.inv) _ _, { symmetry, refine (precompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact precompose_id }, { refine (precompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact precompose_id } end @[simps] def forget : cocone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } section variables {D : Type u'} [𝒟 : category.{v} D] include 𝒟 @[simps] def functoriality (G : C ⥤ D) : cocone F ⥤ cocone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } end end cocones end limits namespace functor variables {D : Type u'} [category.{v} D] variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) open category_theory.limits /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality H).obj c /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality H).obj c @[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl @[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl def map_cone_inv [is_equivalence H] (c : cone (F ⋙ H)) : cone F := let t := (inv H).map_cone c in let α : (F ⋙ H) ⋙ inv H ⟶ F := ((whisker_left F (is_equivalence.unit_iso H).inv) : F ⋙ (H ⋙ inv H) ⟶ _) ≫ (functor.right_unitor _).hom in { X := t.X, π := ((category_theory.cones J C).map α).app (op t.X) t.π } @[simp] lemma map_cone_inv_X [is_equivalence H] (c : cone (F ⋙ H)) : (H.map_cone_inv c).X = (inv H).obj c.X := rfl def map_cone_morphism {c c' : cone F} (f : cone_morphism c c') : cone_morphism (H.map_cone c) (H.map_cone c') := (cones.functoriality H).map f def map_cocone_morphism {c c' : cocone F} (f : cocone_morphism c c') : cocone_morphism (H.map_cocone c) (H.map_cocone c') := (cocones.functoriality H).map f @[simp] lemma map_cone_π (c : cone F) (j : J) : (map_cone H c).π.app j = H.map (c.π.app j) := rfl @[simp] lemma map_cocone_ι (c : cocone F) (j : J) : (map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl end functor end category_theory namespace category_theory.limits variables {F : J ⥤ Cᵒᵖ} def cone_of_cocone_left_op (c : cocone F.left_op) : cone F := { X := op c.X, π := nat_trans.right_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) } @[simp] lemma cone_of_cocone_left_op_X (c : cocone F.left_op) : (cone_of_cocone_left_op c).X = op c.X := rfl @[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) : (cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op := by { dsimp [cone_of_cocone_left_op], simp } def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) := { X := unop c.X, ι := nat_trans.left_op c.π } @[simp] lemma cocone_left_op_of_cone_X (c : cone F) : (cocone_left_op_of_cone c).X = unop c.X := rfl @[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) : (cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop := by { dsimp [cocone_left_op_of_cone], simp } def cocone_of_cone_left_op (c : cone F.left_op) : cocone F := { X := op c.X, ι := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) } @[simp] lemma cocone_of_cone_left_op_X (c : cone F.left_op) : (cocone_of_cone_left_op c).X = op c.X := rfl @[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) : (cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op := by { dsimp [cocone_of_cone_left_op], simp } def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) := { X := unop c.X, π := nat_trans.left_op c.ι } @[simp] lemma cone_left_op_of_cocone_X (c : cocone F) : (cone_left_op_of_cocone c).X = unop c.X := rfl @[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) : (cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop := by { dsimp [cone_left_op_of_cocone], simp } end category_theory.limits
8bfe18d4cc8cc0746276f609de5df60e29030f2b
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/set_theory/cardinal.lean
137078adbd085d29f279e9b1bd9b1ac9f2723f0e
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,580
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, Floris van Doorn -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card import data.nat.enat /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.omega` or `ω` the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.omega.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`. * `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`. * `cardinal.sum` is the sum of a collection of cardinals. * `cardinal.sup` is the supremum of a collection of cardinals. * `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega, Cantor's theorem, König's theorem, Konig's theorem -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal instance can_lift_cardinal_Type : can_lift cardinal.{u} (Type u) := ⟨mk, λ c, true, λ c _, quot.induction_on c $ λ α, ⟨α, rfl⟩⟩ @[elab_as_eliminator] lemma induction_on {p : cardinal → Prop} (c : cardinal) (h : ∀ α, p (#α)) : p c := quotient.induction_on c h @[elab_as_eliminator] lemma induction_on₂ {p : cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (h : ∀ α β, p (#α) (#β)) : p c₁ c₂ := quotient.induction_on₂ c₁ c₂ h @[elab_as_eliminator] lemma induction_on₃ {p : cardinal → cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (c₃ : cardinal) (h : ∀ α β γ, p (#α) (#β) (#γ)) : p c₁ c₂ c₃ := quotient.induction_on₃ c₁ c₂ c₃ h protected lemma eq : #α = #β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (#α) := rfl @[simp] theorem mk_out (c : cardinal) : #(c.out) = c := quotient.out_eq _ /-- The representative of the cardinal of a type is equivalent ot the original type. -/ noncomputable def out_mk_equiv {α : Type v} : (#α).out ≃ α := nonempty.some $ cardinal.eq.mp (by simp) lemma mk_congr (e : α ≃ β) : # α = # β := quot.sound ⟨e⟩ alias mk_congr ← equiv.cardinal_eq /-- Lift a function between `Type*`s to a function between `cardinal`s. -/ def map (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) : cardinal.{u} → cardinal.{v} := quotient.map f (λ α β ⟨e⟩, ⟨hf α β e⟩) @[simp] lemma map_mk (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) (α : Type u) : map f hf (#α) = #(f α) := rfl /-- Lift a binary operation `Type* → Type* → Type*` to a binary operation on `cardinal`s. -/ def map₂ (f : Type u → Type v → Type w) (hf : ∀ α β γ δ, α ≃ β → γ ≃ δ → f α γ ≃ f β δ) : cardinal.{u} → cardinal.{v} → cardinal.{w} := quotient.map₂ f $ λ α β ⟨e₁⟩ γ δ ⟨e₂⟩, ⟨hf α β γ δ e₁ e₂⟩ /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{v} → cardinal.{max v u}` -/ def lift (c : cardinal.{v}) : cardinal.{max v u} := map ulift (λ α β e, equiv.ulift.trans $ e.trans equiv.ulift.symm) c @[simp] theorem mk_ulift (α) : #(ulift.{v u} α) = lift.{v} (#α) := rfl theorem lift_umax : lift.{(max u v) u} = lift.{v u} := funext $ λ a, induction_on a $ λ α, (equiv.ulift.trans equiv.ulift.symm).cardinal_eq theorem lift_id' (a : cardinal.{max u v}) : lift.{u} a = a := induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id (a : cardinal) : lift.{u u} a = a := lift_id'.{u u} a @[simp] theorem lift_lift (a : cardinal) : lift.{w} (lift.{v} a) = lift.{(max v w)} a := induction_on a $ λ α, (equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm).cardinal_eq /-- We define the order on cardinal numbers by `#α ≤ #β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_def (α β : Type u) : #α ≤ #β ↔ nonempty (α ↪ β) := iff.rfl theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : #α ≤ #β := ⟨⟨f, hf⟩⟩ theorem _root_.function.embedding.cardinal_le {α β : Type u} (f : α ↪ β) : #α ≤ #β := ⟨f⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : #β ≤ #α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ #α ↔ ∃ p : set α, #p = c := ⟨induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, (equiv.of_injective f hf).cardinal_eq.symm⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } noncomputable instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by { rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩, exact quotient.sound (e₁.antisymm e₂) }, le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total, decidable_le := classical.dec_rel _ } -- short-circuit type class inference noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance theorem lift_mk_le {α : Type u} {β : Type v} : lift.{(max v w)} (#α) ≤ lift.{(max u w)} (#β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ /-- A variant of `lift_mk_le` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_le' {α : Type u} {β : Type v} : lift.{v} (#α) ≤ lift.{u} (#β) ↔ nonempty (α ↪ β) := lift_mk_le.{u v 0} theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{(max v w)} (#α) = lift.{(max u w)} (#β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ /-- A variant of `lift_mk_eq` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_eq' {α : Type u} {β : Type v} : lift.{v} (#α) = lift.{u} (#β) ↔ nonempty (α ≃ β) := lift_mk_eq.{u v 0} @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := induction_on₂ a b $ λ α β, by { rw ← lift_umax, exact lift_mk_le } @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] instance : has_zero cardinal.{u} := ⟨#pempty⟩ instance : inhabited cardinal.{u} := ⟨0⟩ @[simp] lemma mk_eq_zero (α : Type u) [is_empty α] : #α = 0 := (equiv.equiv_pempty α).cardinal_eq @[simp] theorem lift_zero : lift 0 = 0 := mk_congr (equiv.equiv_pempty _) lemma mk_eq_zero_iff {α : Type u} : #α = 0 ↔ is_empty α := ⟨λ e, let ⟨h⟩ := quotient.exact e in h.is_empty, @mk_eq_zero α⟩ theorem mk_ne_zero_iff {α : Type u} : #α ≠ 0 ↔ nonempty α := (not_iff_not.2 mk_eq_zero_iff).trans not_is_empty_iff @[simp] lemma mk_ne_zero (α : Type u) [nonempty α] : #α ≠ 0 := mk_ne_zero_iff.2 ‹_› instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, mk_ne_zero _⟩⟩ theorem le_one_iff_subsingleton {α : Type u} : #α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ theorem one_lt_iff_nontrivial {α : Type u} : 1 < #α ↔ nontrivial α := by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp } instance : has_add cardinal.{u} := ⟨map₂ sum $ λ α β γ δ, equiv.sum_congr⟩ @[simp] theorem add_def (α β : Type u) : #α + #β = #(α ⊕ β) := rfl lemma add (α : Type u) (β : Type v) : #(α ⊕ β) = lift.{v u} (#α) + lift.{u v} (#β) := begin rw [←cardinal.mk_ulift, ←cardinal.mk_ulift, add_def], exact cardinal.eq.2 ⟨equiv.sum_congr (equiv.ulift).symm (equiv.ulift).symm⟩, end @[simp] theorem mk_option {α : Type u} : #(option α) = #α + 1 := (equiv.option_equiv_sum_punit α).cardinal_eq instance : has_mul cardinal.{u} := ⟨map₂ prod $ λ α β γ δ, equiv.prod_congr⟩ @[simp] theorem mul_def (α β : Type u) : #α * #β = #(α × β) := rfl lemma mul (α : Type u) (β : Type v) : #(α × β) = lift.{v u} (#α) * lift.{u v} (#β) := begin rw [←cardinal.mk_ulift, ←cardinal.mk_ulift, mul_def], exact cardinal.eq.2 ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩, end protected theorem add_comm (a b : cardinal.{u}) : a + b = b + a := induction_on₂ a b $ λ α β, mk_congr (equiv.sum_comm α β) protected theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := induction_on₂ a b $ λ α β, mk_congr (equiv.prod_comm α β) protected theorem zero_add (a : cardinal.{u}) : 0 + a = a := induction_on a $ λ α, mk_congr (equiv.empty_sum pempty α) protected theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := induction_on a $ λ α, mk_congr (equiv.pempty_prod α) protected theorem one_mul (a : cardinal.{u}) : 1 * a = a := induction_on a $ λ α, mk_congr (equiv.punit_prod α) protected theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := induction_on₃ a b c $ λ α β γ, mk_congr (equiv.prod_sum_distrib α β γ) protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} : a * b = 0 → a = 0 ∨ b = 0 := begin induction a using cardinal.induction_on with α, induction b using cardinal.induction_on with β, simp only [mul_def, mk_eq_zero_iff, is_empty_prod], exact id end /-- The cardinal exponential. `#α ^ #β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := map₂ (λ α β : Type u, β → α) (λ α β γ δ e₁ e₂, e₂.arrow_congr e₁) a b instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : #α ^ #β = #(β → α) := rfl @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := induction_on₂ a b $ λ α β, (equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm).cardinal_eq @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := induction_on a $ assume α, (equiv.pempty_arrow_equiv_punit α).cardinal_eq @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := induction_on a $ assume α, (equiv.punit_arrow_equiv α).cardinal_eq theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := induction_on₃ a b c $ assume α β γ, (equiv.sum_arrow_equiv_prod_arrow β γ α).cardinal_eq instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := cardinal.zero_add, add_zero := assume a, by rw [cardinal.add_comm a 0, cardinal.zero_add a], add_assoc := λa b c, induction_on₃ a b c $ assume α β γ, mk_congr (equiv.sum_assoc α β γ), add_comm := cardinal.add_comm, zero_mul := cardinal.zero_mul, mul_zero := assume a, by rw [cardinal.mul_comm a 0, cardinal.zero_mul a], one_mul := cardinal.one_mul, mul_one := assume a, by rw [cardinal.mul_comm a 1, cardinal.one_mul a], mul_assoc := λa b c, induction_on₃ a b c $ assume α β γ, mk_congr (equiv.prod_assoc α β γ), mul_comm := cardinal.mul_comm, left_distrib := cardinal.left_distrib, right_distrib := assume a b c, by rw [cardinal.mul_comm (a + b) c, cardinal.left_distrib c a b, cardinal.mul_comm c a, cardinal.mul_comm c b], npow := λ n c, c ^ n, npow_zero' := @power_zero, npow_succ' := λ n c, by rw [nat.cast_succ, power_add, power_one, cardinal.mul_comm] } @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := induction_on a $ assume α, (equiv.arrow_punit_equiv_punit α).cardinal_eq @[simp] theorem prop_eq_two : #(ulift Prop) = 2 := (equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit).cardinal_eq @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := induction_on a $ assume α heq, mk_eq_zero_iff.2 $ is_empty_pi.2 $ let ⟨a⟩ := mk_ne_zero_iff.1 heq in ⟨a, pempty.is_empty⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := induction_on₂ a b $ λ α β h, let ⟨a⟩ := mk_ne_zero_iff.1 h in mk_ne_zero_iff.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := induction_on₃ a b c $ assume α β γ, (equiv.arrow_prod_equiv_prod_arrow α β γ).cardinal_eq theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c := by rw [mul_comm b c]; from (induction_on₃ a b c $ assume α β γ, mk_congr (equiv.curry γ β α)) @[simp] lemma pow_cast_right (κ : cardinal.{u}) (n : ℕ) : (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n := rfl section order_properties open sum protected theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_is_empty⟩ protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := cardinal.add_le_add (le_refl _) protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨#↥(range f)ᶜ, mk_congr this.symm⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩ instance : order_bot cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order } instance : canonically_ordered_comm_semiring cardinal.{u} := { add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h, le_iff_exists_add := @cardinal.le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} := { .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}), .. cardinal.linear_order } @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one @[simp] theorem lift_one : lift 1 = 1 := mk_congr (equiv.ulift.trans equiv.punit_equiv_punit) @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := induction_on₂ a b $ λ α β, mk_congr (equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm) @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := induction_on₂ a b $ λ α β, mk_congr (equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm) @[simp] theorem lift_bit0 (a : cardinal) : lift (bit0 a) = bit0 (lift a) := lift_add a a @[simp] theorem lift_bit1 (a : cardinal) : lift (bit1 a) = bit1 (lift a) := by simp [bit1] theorem lift_two : lift.{u v} 2 = 2 := by simp theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := mk_ne_zero_iff.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ end order_properties /-- **Cantor's theorem** -/ theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ @[simp] theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal.{u}) : c + 1 ≤ succ c := begin refine le_min.2 (λ b, _), rcases ⟨b, c⟩ with ⟨⟨⟨β⟩, hlt⟩, ⟨γ⟩⟩, cases hlt.le with f, have : ¬ surjective f := λ hn, hlt.not_le (mk_le_of_surjective hn), simp only [surjective, not_forall] at this, rcases this with ⟨b, hb⟩, calc #γ + 1 = #(option γ) : mk_option.symm ... ≤ #β : (f.option_elim b hb).cardinal_le end lemma succ_pos (c : cardinal) : 0 < succ c := by simp lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := (succ_pos _).ne' /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, #(f i)) = #(Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ #(f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = #ι * a := induction_on a $ λ α, by simp; exact mk_congr (equiv.sigma_equiv_prod _ _) theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ #ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} [is_empty ι] : sup f = 0 := by { rw [← nonpos_iff_eq_zero, sup_le], exact is_empty_elim } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := #(Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, #(f i)) = #(Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ #(f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ #ι := induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_eq_zero {ι} (f : ι → cardinal.{u}) : prod f = 0 ↔ ∃ i, f i = 0 := by { lift f to ι → Type u using λ _, trivial, simp [mk_eq_zero_iff] } theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := by simp [prod_eq_zero] @[simp] theorem lift_prod {ι : Type u} (c : ι → cardinal.{v}) : lift.{w} (prod c) = prod (λ i, lift.{w} (c i)) := begin lift c to ι → Type v using λ _, trivial, simp only [prod_mk, ←mk_ulift], exact cardinal.mk_congr (equiv.ulift.trans $ equiv.Pi_congr_right $ λ i, equiv.ulift.symm) end @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := induction_on₂ a b $ λ α β, by rw [← lift_id (#β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨#(set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{(max v w)} a = lift.{(max u w)} b ↔ lift.{v} a = lift.{u} b := calc lift.{(max v w)} a = lift.{(max u w)} b ↔ lift.{w} (lift.{v} a) = lift.{w} (lift.{u} b) : by simp ... ↔ lift.{v} a = lift.{u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : #(α × β) = lift.{v} (#α) * lift.{u} (#β) := mk_congr (equiv.ulift.symm.prod_congr equiv.ulift.symm) theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{v} (#ι) * lift.{u} a := begin induction a using cardinal.induction_on with α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact mk_congr (equiv.sigma_equiv_prod ι α) end protected lemma le_sup_iff {ι : Type v} {f : ι → cardinal.{max v w}} {c : cardinal} : (c ≤ sup f) ↔ (∀ b, (∀ i, f i ≤ b) → c ≤ b) := ⟨λ h b hb, le_trans h (sup_le.mpr hb), λ h, h _ $ λ i, le_sup f i⟩ /-- The lift of a supremum is the supremum of the lifts. -/ lemma lift_sup {ι : Type v} (f : ι → cardinal.{max v w}) : lift.{u} (sup.{v w} f) = sup.{v (max u w)} (λ i : ι, lift.{u} (f i)) := begin apply le_antisymm, { rw [cardinal.le_sup_iff], intros c hc, by_contra h, obtain ⟨d, rfl⟩ := cardinal.lift_down (not_le.mp h).le, simp only [lift_le, sup_le] at h hc, exact h hc }, { simp only [cardinal.sup_le, lift_le, le_sup, implies_true_iff] } end /-- To prove that the lift of a supremum is bounded by some cardinal `t`, it suffices to show that the lift of each cardinal is bounded by `t`. -/ lemma lift_sup_le {ι : Type v} (f : ι → cardinal.{max v w}) (t : cardinal.{max u v w}) (w : ∀ i, lift.{u} (f i) ≤ t) : lift.{u} (sup f) ≤ t := by { rw lift_sup, exact sup_le.mpr w, } @[simp] lemma lift_sup_le_iff {ι : Type v} (f : ι → cardinal.{max v w}) (t : cardinal.{max u v w}) : lift.{u} (sup f) ≤ t ↔ ∀ i, lift.{u} (f i) ≤ t := ⟨λ h i, (lift_le.mpr (le_sup f i)).trans h, λ h, lift_sup_le f t h⟩ universes v' w' /-- To prove an inequality between the lifts to a common universe of two different supremums, it suffices to show that the lift of each cardinal from the smaller supremum if bounded by the lift of some cardinal from the larger supremum. -/ lemma lift_sup_le_lift_sup {ι : Type v} {ι' : Type v'} (f : ι → cardinal.{max v w}) (f' : ι' → cardinal.{max v' w'}) (g : ι → ι') (h : ∀ i, lift.{(max v' w')} (f i) ≤ lift.{(max v w)} (f' (g i))) : lift.{(max v' w')} (sup f) ≤ lift.{(max v w)} (sup f') := begin apply lift_sup_le.{(max v' w')} f, intro i, apply le_trans (h i), simp only [lift_le], apply le_sup, end /-- A variant of `lift_sup_le_lift_sup` with universes specialized via `w = v` and `w' = v'`. This is sometimes necessary to avoid universe unification issues. -/ lemma lift_sup_le_lift_sup' {ι : Type v} {ι' : Type v'} (f : ι → cardinal.{v}) (f' : ι' → cardinal.{v'}) (g : ι → ι') (h : ∀ i, lift.{v'} (f i) ≤ lift.{v} (f' (g i))) : lift.{v'} (sup.{v v} f) ≤ lift.{v} (sup.{v' v'} f') := lift_sup_le_lift_sup f f' g h /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (#ℕ) localized "notation `ω` := cardinal.omega" in cardinal lemma mk_nat : #ℕ = ω := (lift_id _).symm theorem omega_ne_zero : ω ≠ 0 := mk_ne_zero _ theorem omega_pos : 0 < ω := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift ω = ω := lift_lift _ @[simp] theorem omega_le_lift {c : cardinal.{u}} : ω ≤ lift.{v} c ↔ ω ≤ c := by rw [← lift_omega, lift_le] @[simp] theorem lift_le_omega {c : cardinal.{u}} : lift.{v} c ≤ ω ↔ c ≤ ω := by rw [← lift_omega, lift_le] /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), #(fin n) = n | 0 := mk_eq_zero _ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (#(fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : #α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (#α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ #α := begin rw (_ : (s.card : cardinal) = #s), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] instance : char_zero cardinal := ⟨strict_mono.injective $ λ m n, nat_cast_lt.2⟩ theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := nat.cast_inj lemma nat_cast_injective : injective (coe : ℕ → cardinal) := nat.cast_injective @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < ω := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, λ a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < ω := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < ω ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : ω ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : #α < ω ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : #S < ω ↔ finite S := lt_omega_iff_fintype.trans finite_def.symm instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < ω, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < ω) (hb : b < ω) : a + b < ω := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < ω ↔ a < ω ∧ b < ω := ⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ lemma omega_le_add_iff {a b : cardinal} : ω ≤ a + b ↔ ω ≤ a ∨ ω ≤ b := by simp only [← not_lt, add_lt_omega_iff, not_and_distrib] theorem mul_lt_omega {a b : cardinal} (ha : a < ω) (hb : b < ω) : a * b < ω := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < ω ↔ a = 0 ∨ b = 0 ∨ a < ω ∧ b < ω := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul' (le_refl a) hb) h }, { rw [← one_mul b], refine lt_of_le_of_lt (mul_le_mul' ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < ω ↔ a < ω ∧ b < ω := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < ω) (hb : b < ω) : a ^ b < ω := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_unique {α : Type*} : #α = 1 ↔ subsingleton α ∧ nonempty α := calc #α = 1 ↔ #α ≤ 1 ∧ ¬#α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, mk_ne_zero_iff] end theorem infinite_iff {α : Type u} : infinite α ↔ ω ≤ #α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_iff, is_empty_fintype] lemma omega_le_mk (α : Type u) [infinite α] : ω ≤ #α := infinite_iff.1 ‹_› lemma encodable_iff {α : Type u} : nonempty (encodable α) ↔ #α ≤ ω := ⟨λ ⟨h⟩, ⟨(@encodable.encode' α h).trans equiv.ulift.symm.to_embedding⟩, λ ⟨h⟩, ⟨encodable.of_inj _ (h.trans equiv.ulift.to_embedding).injective⟩⟩ @[simp] lemma mk_le_omega [encodable α] : #α ≤ ω := encodable_iff.1 ⟨‹_›⟩ lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ #α = ω := ⟨λ ⟨h⟩, mk_congr ((@denumerable.eqv α h).trans equiv.ulift.symm), λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ @[simp] lemma mk_denumerable (α : Type u) [denumerable α] : #α = ω := denumerable_iff.1 ⟨‹_›⟩ @[simp] lemma mk_set_le_omega (s : set α) : #s ≤ ω ↔ countable s := begin rw [countable_iff_exists_injective], split, { rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ }, { rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩ } end @[simp] lemma omega_add_omega : ω + ω = ω := mk_denumerable _ @[simp] lemma omega_mul_omega : ω * ω = ω := mk_denumerable _ @[simp] lemma add_le_omega {c₁ c₂ : cardinal} : c₁ + c₂ ≤ ω ↔ c₁ ≤ ω ∧ c₂ ≤ ω := ⟨λ h, ⟨le_self_add.trans h, le_add_self.trans h⟩, λ h, omega_add_omega ▸ add_le_add h.1 h.2⟩ /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to 0. -/ noncomputable def to_nat : zero_hom cardinal ℕ := ⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0, begin have h : 0 < ω := nat_lt_omega 0, rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero], end⟩ lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < ω) : c.to_nat = classical.some (lt_omega.1 h) := dif_pos h @[simp] lemma to_nat_apply_of_omega_le {c : cardinal} (h : ω ≤ c) : c.to_nat = 0 := dif_neg (not_lt_of_le h) @[simp] lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < ω) : ↑c.to_nat = c := by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)] @[simp] lemma cast_to_nat_of_omega_le {c : cardinal} (h : ω ≤ c) : ↑c.to_nat = (0 : cardinal) := by rw [to_nat_apply_of_omega_le h, nat.cast_zero] @[simp] lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n := begin rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj], exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm, end /-- `to_nat` has a right-inverse: coercion. -/ lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective @[simp] lemma mk_to_nat_of_infinite [h : infinite α] : (#α).to_nat = 0 := dif_neg (not_lt_of_le (infinite_iff.1 h)) @[simp] lemma mk_to_nat_eq_card [fintype α] : (#α).to_nat = fintype.card α := by simp [fintype_card] @[simp] lemma zero_to_nat : to_nat 0 = 0 := by rw [← to_nat_cast 0, nat.cast_zero] @[simp] lemma one_to_nat : to_nat 1 = 1 := by rw [← to_nat_cast 1, nat.cast_one] @[simp] lemma to_nat_eq_one {c : cardinal} : to_nat c = 1 ↔ c = 1 := ⟨λ h, (cast_to_nat_of_lt_omega (lt_of_not_ge (one_ne_zero ∘ h.symm.trans ∘ to_nat_apply_of_omega_le))).symm.trans ((congr_arg coe h).trans nat.cast_one), λ h, (congr_arg to_nat h).trans one_to_nat⟩ lemma to_nat_eq_one_iff_unique {α : Type*} : (#α).to_nat = 1 ↔ subsingleton α ∧ nonempty α := to_nat_eq_one.trans eq_one_iff_unique @[simp] lemma to_nat_lift (c : cardinal.{v}) : (lift.{u v} c).to_nat = c.to_nat := begin apply nat_cast_injective, cases lt_or_ge c ω with hc hc, { rw [cast_to_nat_of_lt_omega, ←lift_nat_cast, cast_to_nat_of_lt_omega hc], rwa [←lift_omega, lift_lt] }, { rw [cast_to_nat_of_omega_le, ←lift_nat_cast, cast_to_nat_of_omega_le hc, lift_zero], rwa [←lift_omega, lift_le] }, end lemma to_nat_congr {β : Type v} (e : α ≃ β) : (#α).to_nat = (#β).to_nat := by rw [←to_nat_lift, lift_mk_eq.mpr ⟨e⟩, to_nat_lift] lemma to_nat_mul (x y : cardinal) : (x * y).to_nat = x.to_nat * y.to_nat := begin by_cases hx1 : x = 0, { rw [comm_semiring.mul_comm, hx1, mul_zero, zero_to_nat, nat.zero_mul] }, by_cases hy1 : y = 0, { rw [hy1, zero_to_nat, mul_zero, mul_zero, zero_to_nat] }, refine nat_cast_injective (eq.trans _ (nat.cast_mul _ _).symm), cases lt_or_ge x ω with hx2 hx2, { cases lt_or_ge y ω with hy2 hy2, { rw [cast_to_nat_of_lt_omega, cast_to_nat_of_lt_omega hx2, cast_to_nat_of_lt_omega hy2], exact mul_lt_omega hx2 hy2 }, { rw [cast_to_nat_of_omega_le hy2, mul_zero, cast_to_nat_of_omega_le], exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hy2 h.2)) } }, { rw [cast_to_nat_of_omega_le hx2, zero_mul, cast_to_nat_of_omega_le], exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hx2 h.1)) }, end /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to `⊤`. -/ noncomputable def to_enat : cardinal →+ enat := { to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤, map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)], map_add' := λ x y, begin by_cases hx : x < ω, { obtain ⟨x0, rfl⟩ := lt_omega.1 hx, by_cases hy : y < ω, { obtain ⟨y0, rfl⟩ := lt_omega.1 hy, simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true], rw [← nat.cast_add, to_nat_cast, nat.cast_add] }, { rw [if_neg hy, if_neg, enat.add_top], contrapose! hy, apply lt_of_le_of_lt le_add_self hy } }, { rw [if_neg hx, if_neg, enat.top_add], contrapose! hx, apply lt_of_le_of_lt le_self_add hx }, end } @[simp] lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < ω) : c.to_enat = c.to_nat := if_pos h @[simp] lemma to_enat_apply_of_omega_le {c : cardinal} (h : ω ≤ c) : c.to_enat = ⊤ := if_neg (not_lt_of_le h) @[simp] lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n := by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast] @[simp] lemma mk_to_enat_of_infinite [h : infinite α] : (#α).to_enat = ⊤ := to_enat_apply_of_omega_le (infinite_iff.1 h) lemma to_enat_surjective : surjective to_enat := begin intro x, exact enat.cases_on x ⟨ω, to_enat_apply_of_omega_le (le_refl ω)⟩ (λ n, ⟨n, to_enat_cast n⟩), end @[simp] lemma mk_to_enat_eq_coe_card [fintype α] : (#α).to_enat = fintype.card α := by simp [fintype_card] lemma mk_int : #ℤ = ω := mk_denumerable ℤ lemma mk_pnat : #ℕ+ = ω := mk_denumerable ℕ+ lemma two_le_iff : (2 : cardinal) ≤ #α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ #α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- **König's theorem** -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin haveI : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ mk_ne_zero_iff.1 _⟩, rw mk_out, exact (H i).ne_bot }, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : #empty = 0 := fintype_card empty @[simp] theorem mk_pempty : #pempty = 0 := fintype_card pempty theorem mk_unit : #unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : #punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : #({x} : set α) = 1 := mk_congr (equiv.set.singleton x) @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : #(plift p) = 1 := mk_congr (equiv.plift.trans $ equiv.prop_equiv_punit h) @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : #(plift p) = 0 := mk_congr (equiv.plift.trans $ equiv.prop_equiv_pempty h) @[simp] theorem mk_bool : #bool = 2 := mk_congr (equiv.bool_equiv_punit_sum_punit) @[simp] theorem mk_Prop : #Prop = 2 := (mk_congr equiv.Prop_equiv_bool).trans mk_bool @[simp] theorem mk_set {α : Type u} : #(set α) = 2 ^ #α := begin rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq], exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩, end theorem mk_list_eq_sum_pow (α : Type u) : #(list α) = sum (λ n : ℕ, (#α)^(n:cardinal.{u})) := calc #(list α) = #(Σ n, vector α n) : mk_congr ((equiv.sigma_preimage_equiv list.length).symm) ... = #(Σ n, fin n → α) : mk_congr (equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩) ... = #(Σ n : ℕ, ulift.{u} (fin n) → α) : mk_congr (equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)) ... = sum (λ n : ℕ, (#α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, ←mk_ulift, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : #(quot r) ≤ #α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : #(quotient s) ≤ #α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : #(subtype p) ≤ #α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : #(subtype p) ≤ #(subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : #(∅ : set α) = 0 := mk_eq_zero _ lemma mk_emptyc_iff {α : Type u} {s : set α} : #s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : #s = #pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end @[simp] theorem mk_univ {α : Type u} : #(@univ α) = #α := mk_congr (equiv.set.univ α) theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : #(f '' s) ≤ #s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{u} (#(f '' s)) ≤ lift.{v} (#s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : #(range f) ≤ #α := mk_le_of_surjective surjective_onto_range theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} : lift.{u} (#(range f)) ≤ lift.{v} (#α) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_range⟩ lemma mk_range_eq (f : α → β) (h : injective f) : #(range f) = #α := mk_congr ((equiv.of_injective f h).symm) lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{u} (#(range f)) = lift.{v} (#α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.of_injective f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{(max u w)} (# (range f)) = lift.{(max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : #(f '' s) = #s := mk_congr ((equiv.set.image f s hf).symm) theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : #(⋃ i, f i) ≤ sum (λ i, #(f i)) := calc #(⋃ i, f i) ≤ #(Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, #(f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : #(⋃ i, f i) = sum (λ i, #(f i)) := calc #(⋃ i, f i) = #(Σ i, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, #(f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : #(⋃ i, f i) ≤ #ι * cardinal.sup.{u u} (λ i, #(f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : #(⋃₀ A) ≤ #A * cardinal.sup.{u u} (λ s : A, #s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : #(⋃(x ∈ s), A x) ≤ #s * cardinal.sup.{u u} (λ x : s, #(A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = #s := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : #(↑s : set α) < ω := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} : #s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n := begin split, { intro h, have : # s < omega, by { rw h, exact nat_lt_omega n }, refine ⟨(lt_omega_iff_finite.1 this).to_finset, finite.coe_to_finset _, nat_cast_inj.1 _⟩, rwa [finset_card, finite.coe_sort_to_finset] }, { rintro ⟨t, rfl, rfl⟩, exact finset_card.symm } end theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : #(S ∪ T : set α) + #(S ∩ T : set α) = #S + #T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : #(S ∪ T : set α) ≤ #S + #T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (#(S ∪ T : set α)) (#(S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : #(S ∪ T : set α) = #S + #T := quot.sound ⟨equiv.set.union H⟩ theorem mk_insert {α : Type u} {s : set α} {a : α} (h : a ∉ s) : #(insert a s : set α) = #s + 1 := by { rw [← union_singleton, mk_union_of_disjoint, mk_singleton], simpa } lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := mk_congr (equiv.set.sum_compl s) lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : #s ≤ #t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : #{x // p x} ≤ #{x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : #s ≤ #α := mk_subtype_le s lemma mk_union_le_omega {α} {P Q : set α} : #((P ∪ Q : set α)) ≤ ω ↔ #P ≤ ω ∧ #Q ≤ ω := by simp lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{u} (#(f '' s)) = lift.{v} (#s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{u} (#(f '' s)) = lift.{v} (#s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : #(f '' s) = #s := mk_congr ((equiv.set.image_of_inj_on f s h).symm) lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : #{a : α // p (e a)} = #{b : β // p b} := mk_congr (equiv.subtype_equiv_of_subtype e) lemma mk_sep (s : set α) (t : α → Prop) : #({ x ∈ s | t x } : set α) = #{ x : s | t x.1 } := mk_congr (equiv.set.sep s t) lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{v} (#(f ⁻¹' s)) ≤ lift.{u} (#s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{u} (#s) ≤ lift.{v} (#(f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{v} (#(f ⁻¹' s)) = lift.{u} (#s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : #(f ⁻¹' s) ≤ #s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : #s ≤ #(f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : #(f ⁻¹' s) = #s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{u} (#t) ≤ lift.{v} (#({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : #t ≤ #({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ #s ↔ ∃ p : set α, p ⊆ s ∧ #p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // #s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // #s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // #s < c'}), #s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : #↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := begin convert sup_eq_zero, exact subtype.is_empty_of_false (λ x, (zero_le _).not_lt), end end cardinal
89588ac19af1c3fc71c75d9604485d8ff0f68dec
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebra/gcd_domain.lean
03c4c77e333c559d8a9826866b91fdc9c12395d7
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
26,082
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker GCD domain and integral domains with normalization functions TODO: abstract the domains to to semi domains (i.e. domains on semirings) to include ℕ and ℕ[X] etc. -/ import algebra.associated data.int.gcd variables {α : Type*} set_option old_structure_cmd true /-- Normalization domain: multiplying with `norm_unit` gives a normal form for associated elements. -/ class normalization_domain (α : Type*) extends integral_domain α := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) export normalization_domain (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_domain variable [normalization_domain α] def normalize (x : α) : α := x * norm_unit x theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 @[simp] lemma normalize_zero : normalize (0 : α) = 0 := by rw [normalize, zero_mul] @[simp] lemma normalize_one : normalize (1 : α) = 1 := by rw [normalize, norm_unit_one, units.coe_one, mul_one] lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by rw [normalize, norm_unit_coe_units, ← units.coe_mul, mul_inv_self, units.coe_one] theorem normalize_mul (x y : α) : normalize (x * y) = normalize x * normalize y := classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, normalize_zero, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, normalize_zero, mul_zero]) $ λ hy, by simp only [normalize, norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y] lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu.symm ▸ normalize_coe_units u⟩ theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by rw [normalize, normalize, norm_unit_mul_norm_unit, units.coe_one, mul_one] theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨dvd_mul_unit_iff.1 ⟨_, h.symm⟩, dvd_mul_unit_iff.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba @[simp] lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := dvd_mul_unit_iff @[simp] lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := mul_unit_dvd_iff end normalization_domain namespace associates variable [normalization_domain α] local attribute [instance] associated.setoid protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (mul_unit_dvd_iff.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates /-- GCD domain: an integral domain with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the correpsonding `lcm` facts from `gcd`. -/ class gcd_domain (α : Type*) extends normalization_domain α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) export gcd_domain (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_domain variables [gcd_domain α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_domain.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_domain.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize_mul, normalize_gcd, one_mul, domain.mul_left_inj h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd (units.coe_dvd _ _) (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) end lcm end gcd_domain namespace int section normalization_domain instance : normalization_domain ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos (le_refl _), norm_unit_mul := assume a b hna hnb, begin by_cases ha : 0 ≤ a; by_cases hb : 0 ≤ b; simp [ha, hb], exact if_pos (mul_nonneg ha hb), exact if_neg (assume h, hb $ nonneg_of_mul_nonneg_left h $ lt_of_le_of_ne ha hna.symm), exact if_neg (assume h, ha $ nonneg_of_mul_nonneg_right h $ lt_of_le_of_ne hb hnb.symm), exact if_pos (mul_nonneg_of_nonpos_of_nonpos (le_of_not_ge ha) (le_of_not_ge hb)) end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by simp [@neg_lt ℤ _ 1 0])), .. (infer_instance : integral_domain ℤ) } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end end normalization_domain /-- ℤ specific version of least common multiple. -/ def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j) theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl section gcd_domain theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _ theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _ theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) := by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul] instance : gcd_domain ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, normalize_gcd := assume a b, normalize_coe_nat _, gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _, .. int.normalization_domain } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_domain.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_domain.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_domain.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_domain.lcm i j) = int.lcm i j := rfl end gcd_domain theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd] @[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _ @[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _ theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : gcd i j > 0 := nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero) theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : gcd i j > 0 := nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero) theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := by rw [← int.coe_nat_eq_coe_nat_iff, int.coe_nat_zero, coe_gcd, gcd_eq_zero_iff] theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / nat_abs k := by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2]; exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2) theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j) theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i := nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _) (by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j := by rw [gcd_comm, gcd_eq_left H] /- lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_comm] theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_assoc] @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_left _ _ theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_right _ _ theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := by rw [coe_lcm]; exact lcm_dvd end int theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) := ⟨λ hp, ⟨nat.pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one, λ a b, hp.dvd_mul.1⟩, λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩, λ a h, let ⟨b, hab⟩ := h in (hp.2.2 a b (hab ▸ dvd_refl _)).elim (λ ha, or.inr (nat.dvd_antisymm h ha)) (λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb (hab.symm ▸ dvd_mul_left _ _), (nat.mul_left_inj (show 0 < p, from nat.pos_of_ne_zero hp.1)).1 $ by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩ lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt is_unit_int.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt is_unit_nat.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { assume n, show int.nat_abs (normalize n) = n, rw [← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end
3dc2d46ac9d3e78ed9e35ccf4f2bfd1a8726ad90
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/von_mangoldt.lean
999937c3d0cb54b1acbabe83ddb79b949c2542f1
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,045
lean
/- Copyright (c) 2022 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import algebra.is_prime_pow import number_theory.arithmetic_function import analysis.special_functions.log.basic /-! # The von Mangoldt Function In this file we define the von Mangoldt function: the function on natural numbers that returns `log p` if the input can be expressed as `p^k` for a prime `p`. ## Main Results The main definition for this file is - `nat.arithmetic_function.von_mangoldt`: The von Mangoldt function `Λ`. We then prove the classical summation property of the von Mangoldt function in `nat.arithmetic_function.von_mangoldt_sum`, that `∑ i in n.divisors, Λ i = real.log n`, and use this to deduce alternative expressions for the von Mangoldt function via Möbius inversion, see `nat.arithmetic_function.sum_moebius_mul_log_eq`. ## Notation We use the standard notation `Λ` to represent the von Mangoldt function. -/ namespace nat namespace arithmetic_function open finset open_locale arithmetic_function /-- `log` as an arithmetic function `ℕ → ℝ`. Note this is in the `nat.arithmetic_function` namespace to indicate that it is bundled as an `arithmetic_function` rather than being the usual real logarithm. -/ noncomputable def log : arithmetic_function ℝ := ⟨λ n, real.log n, by simp⟩ @[simp] lemma log_apply {n : ℕ} : log n = real.log n := rfl /-- The `von_mangoldt` function is the function on natural numbers that returns `log p` if the input can be expressed as `p^k` for a prime `p`. In the case when `n` is a prime power, `min_fac` will give the appropriate prime, as it is the smallest prime factor. In the `arithmetic_function` locale, we have the notation `Λ` for this function. -/ noncomputable def von_mangoldt : arithmetic_function ℝ := ⟨λ n, if is_prime_pow n then real.log (min_fac n) else 0, if_neg not_is_prime_pow_zero⟩ localized "notation `Λ` := nat.arithmetic_function.von_mangoldt" in arithmetic_function lemma von_mangoldt_apply {n : ℕ} : Λ n = if is_prime_pow n then real.log (min_fac n) else 0 := rfl @[simp] lemma von_mangoldt_apply_one : Λ 1 = 0 := by simp [von_mangoldt_apply] @[simp] lemma von_mangoldt_nonneg {n : ℕ} : 0 ≤ Λ n := begin rw [von_mangoldt_apply], split_ifs, { exact real.log_nonneg (one_le_cast.2 (nat.min_fac_pos n)) }, refl end lemma von_mangoldt_apply_pow {n k : ℕ} (hk : k ≠ 0) : Λ (n ^ k) = Λ n := by simp only [von_mangoldt_apply, is_prime_pow_pow_iff hk, pow_min_fac hk] lemma von_mangoldt_apply_prime {p : ℕ} (hp : p.prime) : Λ p = real.log p := by rw [von_mangoldt_apply, prime.min_fac_eq hp, if_pos (nat.prime_iff.1 hp).is_prime_pow] open_locale big_operators lemma von_mangoldt_sum {n : ℕ} : ∑ i in n.divisors, Λ i = real.log n := begin refine rec_on_prime_coprime _ _ _ n, { simp }, { intros p k hp, rw [sum_divisors_prime_pow hp, cast_pow, real.log_pow, finset.sum_range_succ', pow_zero, von_mangoldt_apply_one], simp [von_mangoldt_apply_pow (nat.succ_ne_zero _), von_mangoldt_apply_prime hp] }, intros a b ha' hb' hab ha hb, simp only [von_mangoldt_apply, ←sum_filter] at ha hb ⊢, rw [mul_divisors_filter_prime_pow hab, filter_union, sum_union (disjoint_divisors_filter_prime_pow hab), ha, hb, nat.cast_mul, real.log_mul (nat.cast_ne_zero.2 (pos_of_gt ha').ne') (nat.cast_ne_zero.2 (pos_of_gt hb').ne')], end @[simp] lemma von_mangoldt_mul_zeta : Λ * ζ = log := by { ext n, rw [coe_mul_zeta_apply, von_mangoldt_sum], refl } @[simp] lemma zeta_mul_von_mangoldt : (ζ : arithmetic_function ℝ) * Λ = log := by { rw [mul_comm], simp } @[simp] lemma log_mul_moebius_eq_von_mangoldt : log * μ = Λ := by rw [←von_mangoldt_mul_zeta, mul_assoc, coe_zeta_mul_coe_moebius, mul_one] @[simp] lemma moebius_mul_log_eq_von_mangoldt : (μ : arithmetic_function ℝ) * log = Λ := by { rw [mul_comm], simp } lemma sum_moebius_mul_log_eq {n : ℕ} : ∑ d in n.divisors, (μ d : ℝ) * log d = - Λ n := begin simp only [←log_mul_moebius_eq_von_mangoldt, mul_comm log, mul_apply, log_apply, int_coe_apply, ←finset.sum_neg_distrib, neg_mul_eq_mul_neg], rw sum_divisors_antidiagonal (λ i j, (μ i : ℝ) * -real.log j), have : ∑ (i : ℕ) in n.divisors, (μ i : ℝ) * -real.log (n / i : ℕ) = ∑ (i : ℕ) in n.divisors, ((μ i : ℝ) * real.log i - μ i * real.log n), { apply sum_congr rfl, simp only [and_imp, int.cast_eq_zero, mul_eq_mul_left_iff, ne.def, neg_inj, mem_divisors], intros m mn hn, have : (m : ℝ) ≠ 0, { rw [cast_ne_zero], rintro rfl, exact hn (by simpa using mn) }, rw [nat.cast_div mn this, real.log_div (cast_ne_zero.2 hn) this, neg_sub, mul_sub] }, rw [this, sum_sub_distrib, ←sum_mul, ←int.cast_sum, ←coe_mul_zeta_apply, eq_comm, sub_eq_self, moebius_mul_coe_zeta, mul_eq_zero, int.cast_eq_zero], rcases eq_or_ne n 1 with hn | hn; simp [hn], end end arithmetic_function end nat
69ec294c7037979ddc3a0cb636441942d2dbe72b
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/ring_theory/adjoin_root.lean
46b947b05040f28487e232fb6c18d5d5a21572d1
[ "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
25,750
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import data.polynomial.field_division import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import ring_theory.power_basis import ring_theory.principal_ideal_domain /-! # Adjoining roots of polynomials This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is irreducible, the field structure on `adjoin_root f` is constructed. ## Main definitions and results The main definitions are in the `adjoin_root` namespace. * `mk f : R[X] →+* adjoin_root f`, the natural ring homomorphism. * `of f : R →+* adjoin_root f`, the natural ring homomorphism. * `root f : adjoin_root f`, the image of X in R[X]/(f). * `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`. * `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x` * `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S` -/ noncomputable theory open_locale classical open_locale big_operators polynomial universes u v w variables {R : Type u} {S : Type v} {K : Type w} open polynomial ideal /-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring as the quotient of `polynomial R` by the principal ideal generated by `f`. -/ def adjoin_root [comm_ring R] (f : R[X]) : Type u := polynomial R ⧸ (span {f} : ideal R[X]) namespace adjoin_root section comm_ring variables [comm_ring R] (f : R[X]) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : inhabited (adjoin_root f) := ⟨0⟩ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ protected lemma nontrivial [is_domain R] (h : degree f ≠ 0) : nontrivial (adjoin_root f) := ideal.quotient.nontrivial begin simp_rw [ne.def, span_singleton_eq_top, polynomial.is_unit_iff, not_exists, not_and], rintro x hx rfl, exact h (degree_C hx.ne_zero), end /-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/ def mk : R[X] →+* adjoin_root f := ideal.quotient.mk _ @[elab_as_eliminator] theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f) (ih : ∀ p : R[X], C (mk f p)) : C x := quotient.induction_on' x ih /-- Embedding of the original ring `R` into `adjoin_root f`. -/ def of : R →+* adjoin_root f := (mk f).comp C instance [comm_semiring S] [algebra S R] : algebra S (adjoin_root f) := ideal.quotient.algebra S instance [comm_semiring S] [comm_semiring K] [has_smul S K] [algebra S R] [algebra K R] [is_scalar_tower S K R] : is_scalar_tower S K (adjoin_root f) := submodule.quotient.is_scalar_tower _ _ instance [comm_semiring S] [comm_semiring K] [algebra S R] [algebra K R] [smul_comm_class S K R] : smul_comm_class S K (adjoin_root f) := submodule.quotient.smul_comm_class _ _ @[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl variables (S) lemma algebra_map_eq' [comm_semiring S] [algebra S R] : algebra_map S (adjoin_root f) = (of f).comp (algebra_map S R) := rfl variables {S} /-- The adjoined root. -/ def root : adjoin_root f := mk f X variables {f} instance has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩ @[simp] lemma mk_eq_mk {g h : R[X]} : mk f g = mk f h ↔ f ∣ g - h := ideal.quotient.eq.trans ideal.mem_span_singleton @[simp] lemma mk_self : mk f f = 0 := quotient.sound' $ quotient_add_group.left_rel_apply.mpr (mem_span_singleton.2 $ by simp) @[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl @[simp] lemma mk_X : mk f X = root f := rfl @[simp] lemma aeval_eq (p : R[X]) : aeval (root f) p = mk f p := polynomial.induction_on p (λ x, by { rw aeval_C, refl }) (λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq]) (λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X, ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl }) theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ := algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p, (algebra.adjoin_singleton_eq_range_aeval R (root f)).symm ▸ ⟨p, aeval_eq p⟩ @[simp] lemma eval₂_root (f : R[X]) : f.eval₂ (of f) (root f) = 0 := by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self] lemma is_root_root (f : R[X]) : is_root (f.map (of f)) (root f) := by rw [is_root, eval_map, eval₂_root] lemma is_algebraic_root (hf : f ≠ 0) : is_algebraic R (root f) := ⟨f, hf, eval₂_root f⟩ variables [comm_ring S] /-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/ def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S := begin apply ideal.quotient.lift _ (eval₂_ring_hom i x), intros g H, rcases mem_span_singleton.1 H with ⟨y, hy⟩, rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul] end variables {i : R →+* S} {a : S} (h : f.eval₂ i a = 0) @[simp] lemma lift_mk (g : R[X]) : lift i a h (mk f g) = g.eval₂ i a := ideal.quotient.lift_mk _ _ _ @[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X] @[simp] lemma lift_of {x : R} : lift i a h x = i x := by rw [← mk_C x, lift_mk, eval₂_C] @[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i := ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _ variables (f) [algebra R S] /-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to a root of `f` in `S`. -/ def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S := { commutes' := λ r, show lift _ _ hfx r = _, from lift_of hfx, .. lift (algebra_map R S) x hfx } @[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) : (lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl @[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 := begin have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes), rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂], refl, end @[simp] lemma lift_hom_eq_alg_hom (f : R[X]) (ϕ : adjoin_root f →ₐ[R] S) : lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ := begin suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤, { exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm }, rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff], exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm, end variables (hfx : aeval a f = 0) @[simp] lemma lift_hom_mk {g : R[X]} : lift_hom f a hfx (mk f g) = aeval a g := lift_mk hfx g @[simp] lemma lift_hom_root : lift_hom f a hfx (root f) = a := lift_root hfx @[simp] lemma lift_hom_of {x : R} : lift_hom f a hfx (of f x) = algebra_map _ _ x := lift_of hfx end comm_ring section irreducible variables [field K] {f : K[X]} instance span_maximal_of_irreducible [fact (irreducible f)] : (span {f}).is_maximal := principal_ideal_ring.is_maximal_of_irreducible $ fact.out _ noncomputable instance field [fact (irreducible f)] : field (adjoin_root f) := { ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal K[X]) } lemma coe_injective (h : degree f ≠ 0) : function.injective (coe : K → adjoin_root f) := have _ := adjoin_root.nontrivial f h, by exactI (of f).injective lemma coe_injective' [fact (irreducible f)] : function.injective (coe : K → adjoin_root f) := (of f).injective variable (f) lemma mul_div_root_cancel [fact (irreducible f)] : ((X - C (root f)) * (f.map (of f) / (X - C (root f)))) = f.map (of f) := mul_div_eq_iff_is_root.2 $ is_root_root _ end irreducible section is_noetherian_ring instance [comm_ring R] [is_noetherian_ring R] {f : R[X]} : is_noetherian_ring (adjoin_root f) := ideal.quotient.is_noetherian_ring _ end is_noetherian_ring section power_basis variables [comm_ring R] {g : R[X]} lemma is_integral_root' (hg : g.monic) : is_integral R (root g) := ⟨g, hg, eval₂_root g⟩ /-- `adjoin_root.mod_by_monic_hom` sends the equivalence class of `f` mod `g` to `f %ₘ g`. This is a well-defined right inverse to `adjoin_root.mk`, see `adjoin_root.mk_left_inverse`. -/ def mod_by_monic_hom (hg : g.monic) : adjoin_root g →ₗ[R] R[X] := (submodule.liftq _ (polynomial.mod_by_monic_hom g) (λ f (hf : f ∈ (ideal.span {g}).restrict_scalars R), (mem_ker_mod_by_monic hg).mpr (ideal.mem_span_singleton.mp hf))).comp $ (submodule.quotient.restrict_scalars_equiv R (ideal.span {g} : ideal R[X])) .symm.to_linear_map @[simp] lemma mod_by_monic_hom_mk (hg : g.monic) (f : R[X]) : mod_by_monic_hom hg (mk g f) = f %ₘ g := rfl lemma mk_left_inverse (hg : g.monic) : function.left_inverse (mk g) (mod_by_monic_hom hg) := λ f, induction_on g f $ λ f, begin rw [mod_by_monic_hom_mk hg, mk_eq_mk, mod_by_monic_eq_sub_mul_div _ hg, sub_sub_cancel_left, dvd_neg], apply dvd_mul_right end lemma mk_surjective (hg : g.monic) : function.surjective (mk g) := (mk_left_inverse hg).surjective /-- The elements `1, root g, ..., root g ^ (d - 1)` form a basis for `adjoin_root g`, where `g` is a monic polynomial of degree `d`. -/ @[simps] def power_basis_aux' (hg : g.monic) : basis (fin g.nat_degree) R (adjoin_root g) := basis.of_equiv_fun { to_fun := λ f i, (mod_by_monic_hom hg f).coeff i, inv_fun := λ c, mk g $ ∑ (i : fin g.nat_degree), monomial i (c i), map_add' := λ f₁ f₂, funext $ λ i, by simp only [(mod_by_monic_hom hg).map_add, coeff_add, pi.add_apply], map_smul' := λ f₁ f₂, funext $ λ i, by simp only [(mod_by_monic_hom hg).map_smul, coeff_smul, pi.smul_apply, ring_hom.id_apply], left_inv := λ f, induction_on g f (λ f, eq.symm $ mk_eq_mk.mpr $ by { simp only [mod_by_monic_hom_mk, sum_mod_by_monic_coeff hg degree_le_nat_degree], rw [mod_by_monic_eq_sub_mul_div _ hg, sub_sub_cancel], exact dvd_mul_right _ _ }), right_inv := λ x, funext $ λ i, begin nontriviality R, simp only [mod_by_monic_hom_mk], rw [(mod_by_monic_eq_self_iff hg).mpr, finset_sum_coeff, finset.sum_eq_single i]; try { simp only [coeff_monomial, eq_self_iff_true, if_true] }, { intros j _ hj, exact if_neg (fin.coe_injective.ne hj) }, { intros, have := finset.mem_univ i, contradiction }, { refine (degree_sum_le _ _).trans_lt ((finset.sup_lt_iff _).mpr (λ j _, _)), { exact bot_lt_iff_ne_bot.mpr (mt degree_eq_bot.mp hg.ne_zero) }, { refine (degree_monomial_le _ _).trans_lt _, rw [degree_eq_nat_degree hg.ne_zero, with_bot.coe_lt_coe], exact j.2 } }, end} /-- The power basis `1, root g, ..., root g ^ (d - 1)` for `adjoin_root g`, where `g` is a monic polynomial of degree `d`. -/ @[simps] def power_basis' (hg : g.monic) : power_basis R (adjoin_root g) := { gen := root g, dim := g.nat_degree, basis := power_basis_aux' hg, basis_eq_pow := λ i, begin simp only [power_basis_aux', basis.coe_of_equiv_fun, linear_equiv.coe_symm_mk], rw finset.sum_eq_single i, { rw [function.update_same, monomial_one_right_eq_X_pow, (mk g).map_pow, mk_X] }, { intros j _ hj, rw ← monomial_zero_right _, convert congr_arg _ (function.update_noteq hj _ _) }, -- Fix `decidable_eq` mismatch { intros, have := finset.mem_univ i, contradiction }, end} variables [field K] {f : K[X]} lemma is_integral_root (hf : f ≠ 0) : is_integral K (root f) := is_algebraic_iff_is_integral.mp (is_algebraic_root hf) lemma minpoly_root (hf : f ≠ 0) : minpoly K (root f) = f * C (f.leading_coeff⁻¹) := begin have f'_monic : monic _ := monic_mul_leading_coeff_inv hf, refine (minpoly.unique K _ f'_monic _ _).symm, { rw [alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, nat_degree_mul hf, nat_degree_C, add_zero], apply nat_degree_le_of_dvd, { have : mk f q = 0, by rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero], rwa [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem] }, { exact q_monic.ne_zero }, { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] }, end /-- The elements `1, root f, ..., root f ^ (d - 1)` form a basis for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ def power_basis_aux (hf : f ≠ 0) : basis (fin f.nat_degree) K (adjoin_root f) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have minpoly_eq : minpoly K (root f) = f' := minpoly_root hf, apply @basis.mk _ _ _ (λ (i : fin f.nat_degree), (root f ^ i.val)), { rw [← deg_f', ← minpoly_eq], exact (is_integral_root hf).linear_independent_pow }, { rintros y -, rw [← deg_f', ← minpoly_eq], apply (is_integral_root hf).mem_span_pow, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ @[simps] def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, basis := power_basis_aux hf, basis_eq_pow := basis.mk_apply _ _ } lemma minpoly_power_basis_gen (hf : f ≠ 0) : minpoly K (power_basis hf).gen = f * C (f.leading_coeff⁻¹) := by rw [power_basis_gen, minpoly_root hf] lemma minpoly_power_basis_gen_of_monic (hf : f.monic) (hf' : f ≠ 0 := hf.ne_zero) : minpoly K (power_basis hf').gen = f := by rw [minpoly_power_basis_gen hf', hf.leading_coeff, inv_one, C.map_one, mul_one] end power_basis section minpoly variables [comm_ring R] [comm_ring S] [algebra R S] (x : S) (R) open algebra polynomial /-- The surjective algebra morphism `R[X]/(minpoly R x) → R[x]`. If `R` is a GCD domain and `x` is integral, this is an isomorphism, see `adjoin_root.minpoly.equiv_adjoin`. -/ @[simps] def minpoly.to_adjoin : adjoin_root (minpoly R x) →ₐ[R] adjoin R ({x} : set S) := lift_hom _ ⟨x, self_mem_adjoin_singleton R x⟩ (by simp [← subalgebra.coe_eq_zero, aeval_subalgebra_coe]) variables {R x} lemma minpoly.to_adjoin_apply' (a : adjoin_root (minpoly R x)) : minpoly.to_adjoin R x a = lift_hom (minpoly R x) (⟨x, self_mem_adjoin_singleton R x⟩ : adjoin R ({x} : set S)) (by simp [← subalgebra.coe_eq_zero, aeval_subalgebra_coe]) a := rfl lemma minpoly.to_adjoin.apply_X : minpoly.to_adjoin R x (mk (minpoly R x) X) = ⟨x, self_mem_adjoin_singleton R x⟩ := by simp variables (R x) lemma minpoly.to_adjoin.surjective : function.surjective (minpoly.to_adjoin R x) := begin rw [← range_top_iff_surjective, _root_.eq_top_iff, ← adjoin_adjoin_coe_preimage], refine adjoin_le _, simp only [alg_hom.coe_range, set.mem_range], rintro ⟨y₁, y₂⟩ h, refine ⟨mk (minpoly R x) X, by simpa using h.symm⟩ end variables {R} {x} [is_domain R] [normalized_gcd_monoid R] [is_domain S] [no_zero_smul_divisors R S] lemma minpoly.to_adjoin.injective (hx : is_integral R x) : function.injective (minpoly.to_adjoin R x) := begin refine (injective_iff_map_eq_zero _).2 (λ P₁ hP₁, _), obtain ⟨P, hP⟩ := mk_surjective (minpoly.monic hx) P₁, by_cases hPzero : P = 0, { simpa [hPzero] using hP.symm }, have hPcont : P.content ≠ 0 := λ h, hPzero (content_eq_zero_iff.1 h), rw [← hP, minpoly.to_adjoin_apply', lift_hom_mk, ← subalgebra.coe_eq_zero, aeval_subalgebra_coe, set_like.coe_mk, P.eq_C_content_mul_prim_part, aeval_mul, aeval_C] at hP₁, replace hP₁ := eq_zero_of_ne_zero_of_mul_left_eq_zero ((map_ne_zero_iff _ (no_zero_smul_divisors.algebra_map_injective R S)).2 hPcont) hP₁, obtain ⟨Q, hQ⟩ := minpoly.gcd_domain_dvd hx P.is_primitive_prim_part.ne_zero hP₁, rw [P.eq_C_content_mul_prim_part] at hP, simpa [hQ] using hP.symm end /-- The algebra isomorphism `adjoin_root (minpoly R x) ≃ₐ[R] adjoin R x` -/ @[simps] def minpoly.equiv_adjoin (hx : is_integral R x) : adjoin_root (minpoly R x) ≃ₐ[R] adjoin R ({x} : set S) := alg_equiv.of_bijective (minpoly.to_adjoin R x) ⟨minpoly.to_adjoin.injective hx, minpoly.to_adjoin.surjective R x⟩ /-- The `power_basis` of `adjoin R {x}` given by `x`. See `algebra.adjoin.power_basis` for a version over a field. -/ @[simps] def _root_.algebra.adjoin.power_basis' (hx : _root_.is_integral R x) : _root_.power_basis R (algebra.adjoin R ({x} : set S)) := power_basis.map (adjoin_root.power_basis' (minpoly.monic hx)) (minpoly.equiv_adjoin hx) /-- The power basis given by `x` if `B.gen ∈ adjoin R {x}`. -/ @[simps] noncomputable def _root_.power_basis.of_gen_mem_adjoin' (B : _root_.power_basis R S) (hint : is_integral R x) (hx : B.gen ∈ adjoin R ({x} : set S)) : _root_.power_basis R S := (algebra.adjoin.power_basis' hint).map $ (subalgebra.equiv_of_eq _ _ $ power_basis.adjoin_eq_top_of_gen_mem_adjoin hx).trans subalgebra.top_equiv end minpoly section equiv section is_domain variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] [algebra R S] variables (g : R[X]) (pb : _root_.power_basis R S) /-- If `S` is an extension of `R` with power basis `pb` and `g` is a monic polynomial over `R` such that `pb.gen` has a minimal polynomial `g`, then `S` is isomorphic to `adjoin_root g`. Compare `power_basis.equiv_of_root`, which would require `h₂ : aeval pb.gen (minpoly R (root g)) = 0`; that minimal polynomial is not guaranteed to be identical to `g`. -/ @[simps {fully_applied := ff}] def equiv' (h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) : adjoin_root g ≃ₐ[R] S := { to_fun := adjoin_root.lift_hom g pb.gen h₂, inv_fun := pb.lift (root g) h₁, left_inv := λ x, induction_on g x $ λ f, by rw [lift_hom_mk, pb.lift_aeval, aeval_eq], right_inv := λ x, begin obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval x, rw [pb.lift_aeval, aeval_eq, lift_hom_mk] end, .. adjoin_root.lift_hom g pb.gen h₂ } @[simp] lemma equiv'_to_alg_hom (h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) : (equiv' g pb h₁ h₂).to_alg_hom = adjoin_root.lift_hom g pb.gen h₂ := rfl @[simp] lemma equiv'_symm_to_alg_hom (h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) : (equiv' g pb h₁ h₂).symm.to_alg_hom = pb.lift (root g) h₁ := rfl end is_domain section field variables (K) (L F : Type*) [field F] [field K] [field L] [algebra F K] [algebra F L] variables (pb : _root_.power_basis F K) /-- If `L` is a field extension of `F` and `f` is a polynomial over `F` then the set of maps from `F[x]/(f)` into `L` is in bijection with the set of roots of `f` in `L`. -/ def equiv (f : F[X]) (hf : f ≠ 0) : (adjoin_root f →ₐ[F] L) ≃ {x // x ∈ (f.map (algebra_map F L)).roots} := (power_basis hf).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x, begin rw [power_basis_gen, minpoly_root hf, polynomial.map_mul, roots_mul, polynomial.map_C, roots_C, add_zero, equiv.refl_apply], { rw ← polynomial.map_mul, exact map_monic_ne_zero (monic_mul_leading_coeff_inv hf) } end)) end field end equiv section open ideal double_quot polynomial variables [comm_ring R] (I : ideal R) (f : polynomial R) /-- The natural isomorphism `R[α]/(I[α]) ≅ R[α]/((I[x] ⊔ (f)) / (f))` for `α` a root of `f : polynomial R` and `I : ideal R`. See `adjoin_root.quot_map_of_equiv` for the isomorphism with `(R/I)[X] / (f mod I)`. -/ def quot_map_of_equiv_quot_map_C_map_span_mk : adjoin_root f ⧸ I.map (of f) ≃+* adjoin_root f ⧸ (I.map (C : R →+* R[X])).map (span {f})^.quotient.mk := ideal.quot_equiv_of_eq (by rw [of, adjoin_root.mk, ideal.map_map]) @[simp] lemma quot_map_of_equiv_quot_map_C_map_span_mk_mk (x : adjoin_root f) : quot_map_of_equiv_quot_map_C_map_span_mk I f (ideal.quotient.mk (I.map (of f)) x) = ideal.quotient.mk _ x := rfl --this lemma should have the simp tag but this causes a lint issue lemma quot_map_of_equiv_quot_map_C_map_span_mk_symm_mk (x : adjoin_root f) : (quot_map_of_equiv_quot_map_C_map_span_mk I f).symm (ideal.quotient.mk ((I.map (C : R →+* R[X])).map (span {f})^.quotient.mk) x) = ideal.quotient.mk (I.map (of f)) x := by rw [quot_map_of_equiv_quot_map_C_map_span_mk, ideal.quot_equiv_of_eq_symm, quot_equiv_of_eq_mk] /-- The natural isomorphism `R[α]/((I[x] ⊔ (f)) / (f)) ≅ (R[x]/I[x])/((f) ⊔ I[x] / I[x])` for `α` a root of `f : polynomial R` and `I : ideal R`-/ def quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk : (adjoin_root f) ⧸ (I.map (C : R →+* R[X])).map (span ({f} : set R[X]))^.quotient.mk ≃+* (R[X] ⧸ I.map (C : R →+* R[X])) ⧸ (span ({f} : set R[X])).map (I.map (C : R →+* R[X]))^.quotient.mk := quot_quot_equiv_comm (ideal.span ({f} : set (polynomial R))) (I.map (C : R →+* polynomial R)) @[simp] lemma quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_mk (p : R[X]) : quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk I f (ideal.quotient.mk _ (mk f p)) = quot_quot_mk (I.map C) (span {f}) p := rfl @[simp] lemma quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_symm_quot_quot_mk (p : R[X]) : (quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk I f).symm (quot_quot_mk (I.map C) (span {f}) p) = (ideal.quotient.mk _ (mk f p)) := rfl /-- The natural isomorphism `(R/I)[x]/(f mod I) ≅ (R[x]/I*R[x])/(f mod I[x])` where `f : polynomial R` and `I : ideal R`-/ def polynomial.quot_quot_equiv_comm : (R ⧸ I)[X] ⧸ span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I))) ≃+* (R[X] ⧸ map C I) ⧸ span ({(ideal.quotient.mk (I.map C)) f} : set (R[X] ⧸ map C I)) := quotient_equiv (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I)))) (span {ideal.quotient.mk (I.map polynomial.C) f}) (polynomial_quotient_equiv_quotient_polynomial I) (by rw [map_span, set.image_singleton, ring_equiv.coe_to_ring_hom, polynomial_quotient_equiv_quotient_polynomial_map_mk I f]) @[simp] lemma polynomial.quot_quot_equiv_comm_mk (p : R[X]) : (polynomial.quot_quot_equiv_comm I f) (ideal.quotient.mk _ (p.map I^.quotient.mk)) = (ideal.quotient.mk _ (ideal.quotient.mk _ p)) := by simp only [polynomial.quot_quot_equiv_comm, quotient_equiv_mk, polynomial_quotient_equiv_quotient_polynomial_map_mk] @[simp] lemma polynomial.quot_quot_equiv_comm_symm_mk_mk (p : R[X]) : (polynomial.quot_quot_equiv_comm I f).symm (ideal.quotient.mk _ (ideal.quotient.mk _ p)) = (ideal.quotient.mk _ (p.map I^.quotient.mk)) := by simp only [polynomial.quot_quot_equiv_comm, quotient_equiv_symm_mk, polynomial_quotient_equiv_quotient_polynomial_symm_mk] /-- The natural isomorphism `R[α]/I[α] ≅ (R/I)[X]/(f mod I)` for `α` a root of `f : polynomial R` and `I : ideal R`-/ def quot_adjoin_root_equiv_quot_polynomial_quot : (adjoin_root f) ⧸ (I.map (of f)) ≃+* polynomial (R ⧸ I) ⧸ (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I)))) := (quot_map_of_equiv_quot_map_C_map_span_mk I f).trans ((quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk I f).trans ((ideal.quot_equiv_of_eq (show (span ({f} : set (polynomial R))).map (I.map (C : R →+* polynomial R))^.quotient.mk = span ({(ideal.quotient.mk (I.map polynomial.C)) f} : set (polynomial R ⧸ map C I)), from by rw [map_span, set.image_singleton])).trans (polynomial.quot_quot_equiv_comm I f).symm)) @[simp] lemma quot_adjoin_root_equiv_quot_polynomial_quot_mk_of (p : R[X]) : quot_adjoin_root_equiv_quot_polynomial_quot I f (ideal.quotient.mk (I.map (of f)) (mk f p)) = ideal.quotient.mk (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I)))) (p.map I^.quotient.mk) := by rw [quot_adjoin_root_equiv_quot_polynomial_quot, ring_equiv.trans_apply, ring_equiv.trans_apply, ring_equiv.trans_apply, quot_map_of_equiv_quot_map_C_map_span_mk_mk, quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_mk, quot_quot_mk, ring_hom.comp_apply, quot_equiv_of_eq_mk, polynomial.quot_quot_equiv_comm_symm_mk_mk] @[simp] lemma quot_adjoin_root_equiv_quot_polynomial_quot_symm_mk_mk (p : R[X]) : (quot_adjoin_root_equiv_quot_polynomial_quot I f).symm (ideal.quotient.mk (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I)))) (p.map I^.quotient.mk)) = (ideal.quotient.mk (I.map (of f)) (mk f p)) := by rw [quot_adjoin_root_equiv_quot_polynomial_quot, ring_equiv.symm_trans_apply, ring_equiv.symm_trans_apply, ring_equiv.symm_trans_apply, ring_equiv.symm_symm, polynomial.quot_quot_equiv_comm_mk, ideal.quot_equiv_of_eq_symm, ideal.quot_equiv_of_eq_mk, ← ring_hom.comp_apply, ← double_quot.quot_quot_mk, quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_symm_quot_quot_mk, quot_map_of_equiv_quot_map_C_map_span_mk_symm_mk] end end adjoin_root
7e4a5b389e471de5a09142810f3b49e1e82b9768
74caf7451c921a8d5ab9c6e2b828c9d0a35aae95
/library/init/algebra/ordered_group.lean
1d605090897286f6413e3f722c5e801db34ea99b
[ "Apache-2.0" ]
permissive
sakas--/lean
f37b6fad4fd4206f2891b89f0f8135f57921fc3f
570d9052820be1d6442a5cc58ece37397f8a9e4c
refs/heads/master
1,586,127,145,194
1,480,960,018,000
1,480,960,635,000
40,137,176
0
0
null
1,438,621,351,000
1,438,621,351,000
null
UTF-8
Lean
false
false
18,599
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.order init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe variable u class ordered_mul_cancel_comm_monoid (α : Type u) extends comm_monoid α, left_cancel_semigroup α, right_cancel_semigroup α, order_pair α := (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) (mul_lt_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) @[class] def ordered_cancel_comm_monoid : Type u → Type (max 1 u) := ordered_mul_cancel_comm_monoid instance add_comm_monoid_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_comm_monoid α := @ordered_mul_cancel_comm_monoid.to_comm_monoid α s instance add_left_cancel_semigroup_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_left_cancel_semigroup α := @ordered_mul_cancel_comm_monoid.to_left_cancel_semigroup α s instance add_right_cancel_semigroup_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_right_cancel_semigroup α := @ordered_mul_cancel_comm_monoid.to_right_cancel_semigroup α s instance order_pair_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : order_pair α := @ordered_mul_cancel_comm_monoid.to_order_pair α s section ordered_cancel_comm_monoid variable {α : Type u} variable [s : ordered_cancel_comm_monoid α] lemma add_le_add_left {a b : α} (h : a ≤ b) (c : α) : c + a ≤ c + b := @ordered_mul_cancel_comm_monoid.mul_le_mul_left α s a b h c lemma le_of_add_le_add_left {a b c : α} (h : a + b ≤ a + c) : b ≤ c := @ordered_mul_cancel_comm_monoid.le_of_mul_le_mul_left α s a b c h lemma add_lt_add_left {a b : α} (h : a < b) (c : α) : c + a < c + b := @ordered_mul_cancel_comm_monoid.mul_lt_mul_left α s a b h c lemma lt_of_add_lt_add_left {a b c : α} (h : a + b < a + c) : b < c := @ordered_mul_cancel_comm_monoid.lt_of_mul_lt_mul_left α s a b c h end ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variable {α : Type u} variable [ordered_cancel_comm_monoid α] lemma add_le_add_right {a b : α} (h : a ≤ b) (c : α) : a + c ≤ b + c := add_comm c a ▸ add_comm c b ▸ add_le_add_left h c theorem add_lt_add_right {a b : α} (h : a < b) (c : α) : a + c < b + c := begin rw [add_comm a c, add_comm b c], exact (add_lt_add_left h c) end lemma add_le_add {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (add_le_add_right h₁ c) (add_le_add_left h₂ b) lemma le_add_of_nonneg_right {a b : α} (h : b ≥ 0) : a ≤ a + b := have a + b ≥ a + 0, from add_le_add_left h a, by rwa add_zero at this lemma le_add_of_nonneg_left {a b : α} (h : b ≥ 0) : a ≤ b + a := have 0 + a ≤ b + a, from add_le_add_right h a, by rwa zero_add at this lemma add_lt_add {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (add_lt_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_le_of_lt {a b c d : α} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d := lt_of_le_of_lt (add_le_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_lt_of_le {a b c d : α} (h₁ : a < b) (h₂ : c ≤ d) : a + c < b + d := lt_of_lt_of_le (add_lt_add_right h₁ c) (add_le_add_left h₂ b) lemma lt_add_of_pos_right (a : α) {b : α} (h : b > 0) : a < a + b := have a + 0 < a + b, from add_lt_add_left h a, by rwa [add_zero] at this lemma lt_add_of_pos_left (a : α) {b : α} (h : b > 0) : a < b + a := have 0 + a < b + a, from add_lt_add_right h a, by rwa [zero_add] at this lemma le_of_add_le_add_right {a b c : α} (h : a + b ≤ c + b) : a ≤ c := le_of_add_le_add_left (show b + a ≤ b + c, begin rw [add_comm b a, add_comm b c], assumption end) lemma lt_of_add_lt_add_right {a b c : α} (h : a + b < c + b) : a < c := lt_of_add_lt_add_left (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) end ordered_cancel_comm_monoid class ordered_mul_comm_group (α : Type u) extends comm_group α, order_pair α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) @[class] def ordered_comm_group : Type u → Type (max 1 u) := ordered_mul_comm_group instance add_comm_group_of_ordered_comm_group (α : Type u) [s : ordered_comm_group α] : add_comm_group α := @ordered_mul_comm_group.to_comm_group α s section ordered_mul_comm_group variable {α : Type u} variable [ordered_mul_comm_group α] lemma ordered_mul_comm_group.le_of_mul_le_mul_left {a b c : α} (h : a * b ≤ a * c) : b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_mul_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end lemma ordered_mul_comm_group.lt_of_mul_lt_mul_left {a b c : α} (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_mul_comm_group.mul_lt_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end end ordered_mul_comm_group instance ordered_mul_comm_group.to_ordered_mul_cancel_comm_monoid (α : Type u) [s : ordered_mul_comm_group α] : ordered_mul_cancel_comm_monoid α := { s with mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, le_of_mul_le_mul_left := @ordered_mul_comm_group.le_of_mul_le_mul_left α _, lt_of_mul_lt_mul_left := @ordered_mul_comm_group.lt_of_mul_lt_mul_left α _ } instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := @ordered_mul_comm_group.to_ordered_mul_cancel_comm_monoid α s section ordered_comm_group variables {α : Type u} [ordered_comm_group α] theorem neg_le_neg {a b : α} (h : a ≤ b) : -b ≤ -a := have 0 ≤ -a + b, from add_left_neg a ▸ add_le_add_left h (-a), have 0 + -b ≤ -a + b + -b, from add_le_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma le_of_neg_le_neg {a b : α} (h : -b ≤ -a) : a ≤ b := suffices -(-a) ≤ -(-b), from begin simp [neg_neg] at this, assumption end, neg_le_neg h lemma nonneg_of_neg_nonpos {a : α} (h : -a ≤ 0) : 0 ≤ a := have -a ≤ -0, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonpos_of_nonneg {a : α} (h : 0 ≤ a) : -a ≤ 0 := have -a ≤ -0, from neg_le_neg h, by rwa neg_zero at this lemma nonpos_of_neg_nonneg {a : α} (h : 0 ≤ -a) : a ≤ 0 := have -0 ≤ -a, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonneg_of_nonpos {a : α} (h : a ≤ 0) : 0 ≤ -a := have -0 ≤ -a, from neg_le_neg h, by rwa neg_zero at this lemma neg_lt_neg {a b : α} (h : a < b) : -b < -a := have 0 < -a + b, from add_left_neg a ▸ add_lt_add_left h (-a), have 0 + -b < -a + b + -b, from add_lt_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma lt_of_neg_lt_neg {a b : α} (h : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg h lemma pos_of_neg_neg {a : α} (h : -a < 0) : 0 < a := have -a < -0, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_neg_of_pos {a : α} (h : 0 < a) : -a < 0 := have -a < -0, from neg_lt_neg h, by rwa neg_zero at this lemma neg_of_neg_pos {a : α} (h : 0 < -a) : a < 0 := have -0 < -a, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_pos_of_neg {a : α} (h : a < 0) : 0 < -a := have -0 < -a, from neg_lt_neg h, by rwa neg_zero at this lemma le_neg_of_le_neg {a b : α} (h : a ≤ -b) : b ≤ -a := begin pose h := neg_le_neg h, rwa neg_neg at h end lemma neg_le_of_neg_le {a b : α} (h : -a ≤ b) : -b ≤ a := begin pose h := neg_le_neg h, rwa neg_neg at h end lemma lt_neg_of_lt_neg {a b : α} (h : a < -b) : b < -a := begin pose h := neg_lt_neg h, rwa neg_neg at h end lemma neg_lt_of_neg_lt {a b : α} (h : -a < b) : -b < a := begin pose h := neg_lt_neg h, rwa neg_neg at h end lemma sub_nonneg_of_le {a b : α} (h : b ≤ a) : 0 ≤ a - b := begin pose h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg {a b : α} (h : 0 ≤ a - b) : b ≤ a := begin pose h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le {a b : α} (h : a ≤ b) : a - b ≤ 0 := begin pose h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos {a b : α} (h : a - b ≤ 0) : a ≤ b := begin pose h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt {a b : α} (h : b < a) : 0 < a - b := begin pose h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos {a b : α} (h : 0 < a - b) : b < a := begin pose h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt {a b : α} (h : a < b) : a - b < 0 := begin pose h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg {a b : α} (h : a - b < 0) : a < b := begin pose h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_neg_add {a b c : α} (h : b ≤ -a + c) : a + b ≤ c := begin pose h := add_le_add_left h a, rwa add_neg_cancel_left at h end lemma le_neg_add_of_add_le {a b c : α} (h : a + b ≤ c) : b ≤ -a + c := begin pose h := add_le_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_le_of_le_sub_left {a b c : α} (h : b ≤ c - a) : a + b ≤ c := begin pose 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 {a b c : α} (h : a + b ≤ c) : b ≤ c - a := begin pose 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 {a b c : α} (h : a ≤ c - b) : a + b ≤ c := begin pose h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le {a b c : α} (h : a + b ≤ c) : a ≤ c - b := begin pose h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin pose h := add_le_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_le_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin pose h := add_le_add_left h (-b), rwa neg_add_cancel_left at h end lemma le_add_of_sub_left_le {a b c : α} (h : a - b ≤ c) : a ≤ b + c := begin pose h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - b ≤ c := begin pose 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 {a b c : α} (h : a - c ≤ b) : a ≤ b + c := begin pose h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - c ≤ b := begin pose h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le_left {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_left_le h end lemma neg_add_le_left_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin rw add_comm, exact sub_left_le_of_le_add h end lemma le_add_of_neg_add_le_right {a b c : α} (h : -c + a ≤ b) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_right_le h end lemma neg_add_le_right_of_le_add {a b c : α} (h : a ≤ b + c) : -c + a ≤ b := begin rw add_comm at h, apply neg_add_le_left_of_le_add h end lemma le_add_of_neg_le_sub_left {a b c : α} (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 {a b c : α} (h : c ≤ a + b) : -a ≤ b - c := begin pose 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 {a b c : α} (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 {a b c : α} (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 {a b c : α} (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 {a b : α} (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right {a b : α} (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_neg_add {a b c : α} (h : b < -a + c) : a + b < c := begin pose h := add_lt_add_left h a, rwa add_neg_cancel_left at h end lemma lt_neg_add_of_add_lt {a b c : α} (h : a + b < c) : b < -a + c := begin pose h := add_lt_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_lt_of_lt_sub_left {a b c : α} (h : b < c - a) : a + b < c := begin pose 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 {a b c : α} (h : a + b < c) : b < c - a := begin pose 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 {a b c : α} (h : a < c - b) : a + b < c := begin pose h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt {a b c : α} (h : a + b < c) : a < c - b := begin pose h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt {a b c : α} (h : -b + a < c) : a < b + c := begin pose h := add_lt_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_lt_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin pose h := add_lt_add_left h (-b), rwa neg_add_cancel_left at h end lemma lt_add_of_sub_left_lt {a b c : α} (h : a - b < c) : a < b + c := begin pose h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add {a b c : α} (h : a < b + c) : a - b < c := begin pose 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 {a b c : α} (h : a - c < b) : a < b + c := begin pose h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add {a b c : α} (h : a < b + c) : a - c < b := begin pose h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt_left {a b c : α} (h : -b + a < c) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_left_lt h end lemma neg_add_lt_left_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin rw add_comm, exact sub_left_lt_of_lt_add h end lemma lt_add_of_neg_add_lt_right {a b c : α} (h : -c + a < b) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_right_lt h end lemma neg_add_lt_right_of_lt_add {a b c : α} (h : a < b + c) : -c + a < b := begin rw add_comm at h, apply neg_add_lt_left_of_lt_add h end lemma lt_add_of_neg_lt_sub_left {a b c : α} (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 {a b c : α} (h : c < a + b) : -a < b - c := begin pose 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 {a b c : α} (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 {a b c : α} (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 {a b c : α} (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 {a b : α} (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right {a b : α} (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub {a b c d : α} (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 {a b c d : α} (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 {a b c d : α} (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 : b ≥ 0) : 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 : b > 0) : 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 lemma add_le_add_three {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a + b + c ≤ d + e + f := begin apply le_trans, apply add_le_add, apply add_le_add, repeat {assumption}, apply le_refl end end ordered_comm_group class decidable_linear_ordered_mul_comm_group (α : Type u) extends comm_group α, decidable_linear_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) @[class] def decidable_linear_ordered_comm_group : Type u → Type (max 1 u) := decidable_linear_ordered_mul_comm_group instance add_comm_group_of_decidable_linear_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : add_comm_group α := @decidable_linear_ordered_mul_comm_group.to_comm_group α s instance decidable_linear_order_of_decidable_linear_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : decidable_linear_order α := @decidable_linear_ordered_mul_comm_group.to_decidable_linear_order α s instance decidable_linear_ordered_mul_comm_group.to_ordered_mul_comm_group (α : Type u) [s : decidable_linear_ordered_mul_comm_group α] : ordered_mul_comm_group α := {s with le_of_lt := @le_of_lt α _, lt_of_le_of_lt := @lt_of_le_of_lt α _, lt_of_lt_of_le := @lt_of_lt_of_le α _ } instance decidable_linear_ordered_comm_group.to_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : ordered_comm_group α := @decidable_linear_ordered_mul_comm_group.to_ordered_mul_comm_group α s
e2d660731eaa58539a9e7fb29083decd5ff04258
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/StxQuot.lean
55703590f7a31bd4c987ffd4dffd6c29f684b0d3
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,088
lean
import Lean open Lean open Lean.Elab def run {α} [ToString α] : Unhygienic α → String := toString ∘ Unhygienic.run #eval run `(Nat.one) #eval run `($Syntax.missing) namespace Lean.Syntax #eval run `($missing) #eval run `($(missing)) #eval run `($(id Syntax.missing) + 1) #eval run $ let id := Syntax.missing; `($id + 1) end Lean.Syntax #eval run `(1 + 1) #eval run $ `(fun a => a) >>= pure #eval run $ `(def foo := 1) #eval run $ `(def foo := 1 def bar := 2) #eval run $ do let a ← `(Nat.one); `($a) #eval run $ do `($(← `(Nat.one))) #eval run $ do let a ← `(Nat.one); `(f $a $a) #eval run $ do let a ← `(Nat.one); `(f $ f $a 1) #eval run $ do let a ← `(Nat.one); `(f $(id a)) #eval run $ do let a ← `(Nat.one); `($(a).b) #eval run $ do let a ← `(1 + 2); match a with | `($a + $b) => `($b + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(1 + 2); match a with | stx@`($a + $b) => `($stx + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1); match a with | `($f:command) => pure f | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1 def bar := 2); match a with | `($f:command $g:command) => `($g:command $f:command) | _ => pure Syntax.missing #eval run $ do let a ← `(aa); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval match mkIdent `aa with | `(aa) => 0 | _ => 1 #eval match mkIdent `aa with | `(ab) => 0 | _ => 1 #eval run $ do let a ← `(1 + 2); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval run $ do let params ← #[`(a), `((b : Nat))].mapM id; `(fun $params* => 1) #eval run $ do let a ← `(fun (a : Nat) b => c); match a with | `(fun $aa* => $e) => pure aa | _ => pure #[] #eval run $ do let a ← `(∀ a, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a -- this one should NOT check the kind of the matched node #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $a, $e) => pure a | _ => pure a #eval run $ do let a ← `(a); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(a.{0}); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(match a with | a => 1 | _ => 2); match a with | `(match $e with $eqns:matchAlt*) => pure eqns | _ => pure #[] def f (stx : Syntax) : Unhygienic Syntax := match stx with | `({ $f:ident := $e $[: $a]?}) => `({ $f:ident := $e $[: $(id a)]?}) | _ => unreachable! #eval run do f (← `({ a := a : a })) #eval run do f (← `({ a := a })) def f' (stx : Syntax) : Unhygienic Syntax := match stx with | `(section $(id?)?) => `(section $(id?)?) | _ => unreachable! #eval run do f' (← `(section)) #eval run do f' (← `(section foo)) #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $[| $pats =>%$arr $rhss]*) => `(match $e:term with $[| $pats =>%$arr $rhss]*) | _ => unreachable! #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $alts:matchAlt*) => `(match $e:term with $alts:matchAlt*) | _ => unreachable! open Parser.Term #eval run do match ← `(structInstField|a := b) with | `(Parser.Term.structInstField| $lhs:ident := $rhs) => #[lhs, rhs] | _ => unreachable! #eval run do match ← `({ a := a : a }) with | `({ $f:ident := $e : 0 }) => "0" | `({ $f:ident := $e $[: $a?]?}) => "1" | stx => "2" #eval run `(sufficesDecl|x from x) #eval run do match ← `([1, 2, 3, 4]) with | `([$x, $ys,*, $z]) => #[x, mkNullNode ys, z] | _ => unreachable! #eval run do match ← `([1, 2]) with | `([$x, $y, $zs,*]) => zs.getElems | `([$x, $ys,*]) => ys.getElems | _ => unreachable! #check (match · with | `([1, $ys,*, 2, $zs,*, 3]) => _) #eval run do match Syntax.setHeadInfo (← `(fun x =>%$(Syntax.atom (SourceInfo.synthetic 2 2) "") x)) (SourceInfo.synthetic 1 1) with | `(fun%$i1 $x =>%$i2 $y) => pure #[i1.getPos?, i2.getPos?] | _ => unreachable!
6d1a4c80f537861d93c3d134b826194b3bd568b8
618003631150032a5676f229d13a079ac875ff77
/src/data/int/sqrt.lean
4a309d2c8fc6cfe309f2c1f172f709a167aa2dcf
[ "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
892
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.nat.sqrt import data.int.basic namespace int /-- `sqrt n` is the square root of an integer `n`. If `n` is not a perfect square, and is positive, it returns the largest `k:ℤ` such that `k*k ≤ n`. If it is negative, it returns 0. For example, `sqrt 2 = 1` and `sqrt 1 = 1` and `sqrt (-1) = 0` -/ def sqrt (n : ℤ) : ℤ := nat.sqrt $ int.to_nat n theorem sqrt_eq (n : ℤ) : sqrt (n*n) = n.nat_abs := by rw [sqrt, ← nat_abs_mul_self, to_nat_coe_nat, nat.sqrt_eq] theorem exists_mul_self (x : ℤ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, ← int.coe_nat_mul, nat_abs_mul_self], λ h, ⟨sqrt x, h⟩⟩ theorem sqrt_nonneg (n : ℤ) : 0 ≤ sqrt n := trivial end int
8b30b749c048bccb33c1f263b1fa8bf2e745a783
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/group/inj_surj.lean
fd8c755f4d99a98fc0de33f8e980b69a46019937
[ "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
15,068
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.group.defs import logic.function.basic /-! # Lifting algebraic data classes along injective/surjective maps This file provides definitions that are meant to deal with situations such as the following: Suppose that `G` is a group, and `H` is a type endowed with `has_one H`, `has_mul H`, and `has_inv H`. Suppose furthermore, that `f : G → H` is a surjective map that respects the multiplication, and the unit elements. Then `H` satisfies the group axioms. The relevant definition in this case is `function.surjective.group`. Dually, there is also `function.injective.group`. And there are versions for (additive) (commutative) semigroups/monoids. -/ namespace function /-! ### Injective -/ namespace injective variables {M₁ : Type*} {M₂ : Type*} [has_mul M₁] /-- A type endowed with `*` is a semigroup, if it admits an injective map that preserves `*` to a semigroup. -/ @[to_additive "A type endowed with `+` is an additive semigroup, if it admits an injective map that preserves `+` to an additive semigroup."] protected def semigroup [semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : semigroup M₁ := { mul_assoc := λ x y z, hf $ by erw [mul, mul, mul, mul, mul_assoc], ..‹has_mul M₁› } /-- A type endowed with `*` is a commutative semigroup, if it admits an injective map that preserves `*` to a commutative semigroup. -/ @[to_additive "A type endowed with `+` is an additive commutative semigroup, if it admits an injective map that preserves `+` to an additive commutative semigroup."] protected def comm_semigroup [comm_semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semigroup M₁ := { mul_comm := λ x y, hf $ by erw [mul, mul, mul_comm], .. hf.semigroup f mul } /-- A type endowed with `*` is a left cancel semigroup, if it admits an injective map that preserves `*` to a left cancel semigroup. -/ @[to_additive add_left_cancel_semigroup "A type endowed with `+` is an additive left cancel semigroup, if it admits an injective map that preserves `+` to an additive left cancel semigroup."] protected def left_cancel_semigroup [left_cancel_semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : left_cancel_semigroup M₁ := { mul := (*), mul_left_cancel := λ x y z H, hf $ (mul_right_inj (f x)).1 $ by erw [← mul, ← mul, H]; refl, .. hf.semigroup f mul } /-- A type endowed with `*` is a right cancel semigroup, if it admits an injective map that preserves `*` to a right cancel semigroup. -/ @[to_additive add_right_cancel_semigroup "A type endowed with `+` is an additive right cancel semigroup, if it admits an injective map that preserves `+` to an additive right cancel semigroup."] protected def right_cancel_semigroup [right_cancel_semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : right_cancel_semigroup M₁ := { mul := (*), mul_right_cancel := λ x y z H, hf $ (mul_left_inj (f y)).1 $ by erw [← mul, ← mul, H]; refl, .. hf.semigroup f mul } variables [has_one M₁] /-- A type endowed with `1` and `*` is a monoid, if it admits an injective map that preserves `1` and `*` to a monoid. -/ @[to_additive "A type endowed with `0` and `+` is an additive monoid, if it admits an injective map that preserves `0` and `+` to an additive monoid."] protected def monoid [monoid M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid M₁ := { one_mul := λ x, hf $ by erw [mul, one, one_mul], mul_one := λ x, hf $ by erw [mul, one, mul_one], .. hf.semigroup f mul, ..‹has_one M₁› } /-- A type endowed with `1` and `*` is a left cancel monoid, if it admits an injective map that preserves `1` and `*` to a left cancel monoid. -/ @[to_additive add_left_cancel_monoid "A type endowed with `0` and `+` is an additive left cancel monoid, if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid."] protected def left_cancel_monoid [left_cancel_monoid M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : left_cancel_monoid M₁ := { .. hf.left_cancel_semigroup f mul, .. hf.monoid f one mul } /-- A type endowed with `1` and `*` is a commutative monoid, if it admits an injective map that preserves `1` and `*` to a commutative monoid. -/ @[to_additive "A type endowed with `0` and `+` is an additive commutative monoid, if it admits an injective map that preserves `0` and `+` to an additive commutative monoid."] protected def comm_monoid [comm_monoid M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid M₁ := { .. hf.comm_semigroup f mul, .. hf.monoid f one mul } variables [has_inv M₁] /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `div_inv_monoid` if it admits an injective map that preserves `1`, `*`, `⁻¹`, and `/` to a `div_inv_monoid`. -/ @[to_additive "A type endowed with `0`, `+`, unary `-`, and binary `-` is a `sub_neg_monoid` if it admits an injective map that preserves `0`, `+`, unary `-`, and binary `-` to a `sub_neg_monoid`."] protected def div_inv_monoid [has_div M₁] [div_inv_monoid M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : div_inv_monoid M₁ := { div_eq_mul_inv := λ x y, hf $ by erw [div, mul, inv, div_eq_mul_inv], .. hf.monoid f one mul, .. ‹has_inv M₁›, .. ‹has_div M₁› } /-- A type endowed with `1`, `*` and `⁻¹` is a group, if it admits an injective map that preserves `1`, `*` and `⁻¹` to a group. -/ @[to_additive "A type endowed with `0` and `+` is an additive group, if it admits an injective map that preserves `0` and `+` to an additive group."] protected def group [group M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : group M₁ := { mul_left_inv := λ x, hf $ by erw [mul, inv, mul_left_inv, one], .. hf.monoid f one mul, ..‹has_inv M₁› } /-- A type endowed with `1`, `*`, `⁻¹` and `/` is a group, if it admits an injective map to a group that preserves these operations. This version of `injective.group` makes sure that the `/` operation is defeq to the specified division operator. -/ @[to_additive "A type endowed with `0`, `+` and `-` (unary and binary) is an additive group, if it admits an injective map to an additive group that preserves these operations. This version of `injective.add_group` makes sure that the `-` operation is defeq to the specified subtraction operator."] protected def group_div [has_div M₁] [group M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : group M₁ := { .. hf.div_inv_monoid f one mul inv div, .. hf.group f one mul inv } /-- A type endowed with `1`, `*` and `⁻¹` is a commutative group, if it admits an injective map that preserves `1`, `*` and `⁻¹` to a commutative group. -/ @[to_additive "A type endowed with `0` and `+` is an additive commutative group, if it admits an injective map that preserves `0` and `+` to an additive commutative group."] protected def comm_group [comm_group M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : comm_group M₁ := { .. hf.comm_monoid f one mul, .. hf.group f one mul inv } /-- A type endowed with `1`, `*`, `⁻¹` and `/` is a commutative group, if it admits an injective map to a commutative group that preserves these operations. This version of `injective.comm_group` makes sure that the `/` operation is defeq to the specified division operator. -/ @[to_additive "A type endowed with `0`, `+` and `-` is an additive commutative group, if it admits an injective map to an additive commutative group that preserves these operations. This version of `injective.add_comm_group` makes sure that the `-` operation is defeq to the specified subtraction operator."] protected def comm_group_div [has_div M₁] [comm_group M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : comm_group M₁ := { .. hf.comm_monoid f one mul, .. hf.group_div f one mul inv div } end injective /-! ### Surjective -/ namespace surjective variables {M₁ : Type*} {M₂ : Type*} [has_mul M₂] /-- A type endowed with `*` is a semigroup, if it admits a surjective map that preserves `*` from a semigroup. -/ @[to_additive "A type endowed with `+` is an additive semigroup, if it admits a surjective map that preserves `+` from an additive semigroup."] protected def semigroup [semigroup M₁] (f : M₁ → M₂) (hf : surjective f) (mul : ∀ x y, f (x * y) = f x * f y) : semigroup M₂ := { mul_assoc := hf.forall₃.2 $ λ x y z, by simp only [← mul, mul_assoc], ..‹has_mul M₂› } /-- A type endowed with `*` is a commutative semigroup, if it admits a surjective map that preserves `*` from a commutative semigroup. -/ @[to_additive "A type endowed with `+` is an additive commutative semigroup, if it admits a surjective map that preserves `+` from an additive commutative semigroup."] protected def comm_semigroup [comm_semigroup M₁] (f : M₁ → M₂) (hf : surjective f) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semigroup M₂ := { mul_comm := hf.forall₂.2 $ λ x y, by erw [← mul, ← mul, mul_comm], .. hf.semigroup f mul } variables [has_one M₂] /-- A type endowed with `1` and `*` is a monoid, if it admits a surjective map that preserves `1` and `*` from a monoid. -/ @[to_additive "A type endowed with `0` and `+` is an additive monoid, if it admits a surjective map that preserves `0` and `+` to an additive monoid."] protected def monoid [monoid M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid M₂ := { one_mul := hf.forall.2 $ λ x, by erw [← one, ← mul, one_mul], mul_one := hf.forall.2 $ λ x, by erw [← one, ← mul, mul_one], ..‹has_one M₂›, .. hf.semigroup f mul } /-- A type endowed with `1` and `*` is a commutative monoid, if it admits a surjective map that preserves `1` and `*` from a commutative monoid. -/ @[to_additive "A type endowed with `0` and `+` is an additive commutative monoid, if it admits a surjective map that preserves `0` and `+` to an additive commutative monoid."] protected def comm_monoid [comm_monoid M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid M₂ := { .. hf.comm_semigroup f mul, .. hf.monoid f one mul } variables [has_inv M₂] /-- A type endowed with `1`, `*` and `⁻¹` is a group, if it admits a surjective map that preserves `1`, `*` and `⁻¹` from a group. -/ @[to_additive "A type endowed with `0`, `+`, and unary `-` is an additive group, if it admits a surjective map that preserves `0`, `+`, and `-` from an additive group."] protected def group [group M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : group M₂ := { mul_left_inv := hf.forall.2 $ λ x, by erw [← inv, ← mul, mul_left_inv, one]; refl, ..‹has_inv M₂›, .. hf.monoid f one mul } /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `div_inv_monoid`, if it admits a surjective map that preserves `1`, `*`, `⁻¹`, and `/` from a `div_inv_monoid` -/ @[to_additive "A type endowed with `0`, `+`, and `-` (unary and binary) is an additive group, if it admits a surjective map that preserves `0`, `+`, and `-` from a `sub_neg_monoid`"] protected def div_inv_monoid [has_div M₂] [div_inv_monoid M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : div_inv_monoid M₂ := { div_eq_mul_inv := hf.forall₂.2 $ λ x y, by erw [← inv, ← mul, ← div, div_eq_mul_inv], .. hf.monoid f one mul, .. ‹has_div M₂›, .. ‹has_inv M₂› } /-- A type endowed with `1`, `*`, `⁻¹` and `/` is a group, if it admits an surjective map from a group that preserves these operations. This version of `surjective.group` makes sure that the `/` operation is defeq to the specified division operator. -/ @[to_additive "A type endowed with `0`, `+` and `-` is an additive group, if it admits an surjective map from an additive group that preserves these operations. This version of `surjective.add_group` makes sure that the `-` operation is defeq to the specified subtraction operator."] protected def group_div [has_div M₂] [group M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : group M₂ := { .. hf.div_inv_monoid f one mul inv div, .. hf.group f one mul inv } /-- A type endowed with `1`, `*` and `⁻¹` is a commutative group, if it admits a surjective map that preserves `1`, `*` and `⁻¹` from a commutative group. -/ @[to_additive "A type endowed with `0` and `+` is an additive commutative group, if it admits a surjective map that preserves `0` and `+` to an additive commutative group."] protected def comm_group [comm_group M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : comm_group M₂ := { .. hf.comm_monoid f one mul, .. hf.group f one mul inv } /-- A type endowed with `1`, `*`, `⁻¹` and `/` is a commutative group, if it admits an surjective map from a commutative group that preserves these operations. This version of `surjective.comm_group` makes sure that the `/` operation is defeq to the specified division operator. -/ @[to_additive "A type endowed with `0`, `+` and `-` is an additive commutative group, if it admits an surjective map from an additive commutative group that preserves these operations. This version of `surjective.add_comm_group` makes sure that the `-` operation is defeq to the specified subtraction operator."] protected def comm_group_div [has_div M₂] [comm_group M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : comm_group M₂ := { .. hf.comm_monoid f one mul, .. hf.group_div f one mul inv div } end surjective end function
eccce72328ce5d049a6365f7a9f13edb0c389263
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/Exercises 9/x32_library.lean
0c048c323161408db544a42333e7e58aa20fc539
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
4,192
lean
/- Library 3.2: Program Semantics — Hoare Logic -/ /- This file contains some basic material for the Hoare logic lecture, exercise, and homework. This file contains the following concepts: * `state`: representing the state space of an imperative program (defined as `string → ℕ`) * `∅` is the empty state; mapping every variable to `0` * `s.update n v` or `s & n ::= v`: replace the name `n` in the state `s` by value `v` * `s n` variable `n` of state `s` * `program` syntax for WHILE programs over `state` as state space. This is a slight modification of the lecture 3.1. Instead of over an arbitrary state space `σ` we are now fixed on `state`; and also `assign` only allows changing one variable. * `(p, s) ⟹ t`: big-step semantics over `program` It is all under the `lecture` namespace. -/ meta def tactic.dec_trivial := `[exact dec_trivial] @[simp] lemma not_not_iff (p : Prop) [decidable p] : ¬ (¬ p) ↔ p := by by_cases p; simp [h] @[simp] lemma and_imp (p q r : Prop) : ((p ∧ q) → r) ↔ (p → q → r) := iff.intro (assume h hp hq, h ⟨hp, hq⟩) (assume h ⟨hp, hq⟩, h hp hq) namespace lecture /- `state` to represent state spaces -/ def state := string → ℕ def state.update (name : string) (val : ℕ) (s : state) : state := λn, if n = name then val else s n notation s ` & ` n ` ::= ` v := state.update n v s namespace state instance : has_emptyc state := ⟨λ_, 0⟩ @[simp] lemma update_apply (name : string) (val : ℕ) (s : state) : (s & name ::= val) name = val := if_pos rfl @[simp] lemma update_apply_ne (name name' : string) (val : ℕ) (s : state) (h : name' ≠ name . tactic.dec_trivial): (s & name ::= val) name' = s name' := if_neg h @[simp] lemma update_override (name : string) (val₁ val₂ : ℕ) (s : state) : (s & name ::= val₂ & name ::= val₁) = (s & name ::= val₁) := by funext name'; by_cases name' = name; simp [h] @[simp] lemma update_swap (name₁ name₂ : string) (val₁ val₂ : ℕ) (s : state) (h : name₁ ≠ name₂ . tactic.dec_trivial): (s & name₂ ::= val₂ & name₁ ::= val₁) = (s & name₁ ::= val₁ & name₂ ::= val₂) := by funext name'; by_cases h₁ : name' = name₁; by_cases h₂ : name' = name₂; simp * at * end state example (s : state) : (s & "a" ::= 0 & "a" ::= 2) = (s & "a" ::= 2) := by simp example (s : state) : (s & "a" ::= 0 & "b" ::= 2) = (s & "b" ::= 2 & "a" ::= 0) := by simp /- A WHILE programming language -/ inductive program : Type | skip {} : program | assign : string → (state → ℕ) → program | seq : program → program → program | ite : (state → Prop) → program → program → program | while : (state → Prop) → program → program | unless : program → (state → Prop) → program | do_while: program → (state → Prop) → program infixr ` ;; `:90 := program.seq open program /- We use the **big step** semantics -/ inductive big_step : (program × state) → state → Prop | skip {s} : big_step (skip, s) s | assign {n f s} : big_step (assign n f, s) (s.update n (f s)) | seq {p₁ p₂ s u} (t) (h₁ : big_step (p₁, s) t) (h₂ : big_step (p₂, t) u) : big_step (seq p₁ p₂, s) u | ite_true {c : state → Prop} {p₁ p₀ s t} (hs : c s) (h : big_step (p₁, s) t) : big_step (ite c p₁ p₀, s) t | ite_false {c : state → Prop} {p₁ p₀ s t} (hs : ¬ c s) (h : big_step (p₀, s) t) : big_step (ite c p₁ p₀, s) t | while_true {c : state → Prop} {p s u} (t) (hs : c s) (hp : big_step (p, s) t) (hw : big_step (while c p, t) u) : big_step (while c p, s) u | while_false {c : state → Prop} {p s} (hs : ¬ c s) : big_step (while c p, s) s |unless_false {c : state → Prop} {p s t} (hs: ¬ c s) (h: big_step (p, s) t): big_step (unless p c, s) t |unless_true {c : state → Prop} {p s t} (hs: c s) (h: big_step (p, s) t) : big_step (skip, s) t |do_while_true {c : state → Prop} {p s u} (t) (hp : big_step (p, s) t) (hw : big_step (while c p, t) u) (hs : c s) : big_step (do_while p c, s) u | do_while_false {c : state → Prop} {p s} (hs : ¬ c s) : big_step (do_while p c, s) s infix ` ⟹ `:110 := big_step end lecture
00a3e158179862390299a039be925d11cf4df706
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter6/examples.lean
9f053e1e4ed27b55e0f962da2e1ef9802a79d684
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
450
lean
variables m n : ℕ variables i j : ℤ #check ↑m + i #check ↑(m + n) + i #check ↑m + ↑n + i #check eq #check @eq #check eq.symm #check @eq.symm #print eq.symm #check and #check and.intro #check @and.intro -- a user-defined function def foo {α : Type} (x : α) : α := x #check foo #check @foo #reduce foo #reduce (foo nat.zero) #print foo #print instances ring #check neg_neg #check @neg_neg #check add_group #check @add_le_add_left
c9783a7abd8e1af3dae50377bdb2d274704313a0
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/rat/basic.lean
3e3308e669cc93282469ac9507c818c3cd9f24b6
[ "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
23,981
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The rational numbers as a field generated by the integers, defined as the usual quotient. -/ import data.int algebra.field open int quot eq.ops record prerat : Type := (num : ℤ) (denom : ℤ) (denom_pos : denom > 0) /- prerat: the representations of the rationals as integers num, denom, with denom > 0. note: names are not protected, because it is not expected that users will open prerat. -/ namespace prerat /- the equivalence relation -/ definition equiv (a b : prerat) : Prop := num a * denom b = num b * denom a infix ≡ := equiv theorem equiv.refl [refl] (a : prerat) : a ≡ a := rfl theorem equiv.symm [symm] {a b : prerat} (H : a ≡ b) : b ≡ a := !eq.symm H theorem num_eq_zero_of_equiv {a b : prerat} (H : a ≡ b) (na_zero : num a = 0) : num b = 0 := have num a * denom b = 0, from !zero_mul ▸ na_zero ▸ rfl, have num b * denom a = 0, from H ▸ this, show num b = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) (ne_of_gt (denom_pos a)) theorem num_pos_of_equiv {a b : prerat} (H : a ≡ b) (na_pos : num a > 0) : num b > 0 := have num a * denom b > 0, from mul_pos na_pos (denom_pos b), have num b * denom a > 0, from H ▸ this, show num b > 0, from pos_of_mul_pos_right this (le_of_lt (denom_pos a)) theorem num_neg_of_equiv {a b : prerat} (H : a ≡ b) (na_neg : num a < 0) : num b < 0 := have H₁ : num a * denom b = num b * denom a, from H, have num a * denom b < 0, from mul_neg_of_neg_of_pos na_neg (denom_pos b), have -(-num b * denom a) < 0, begin rewrite [neg_mul_eq_neg_mul, neg_neg, -H₁], exact this end, have -num b > 0, from pos_of_mul_pos_right (pos_of_neg_neg this) (le_of_lt (denom_pos a)), neg_of_neg_pos this theorem equiv_of_num_eq_zero {a b : prerat} (H1 : num a = 0) (H2 : num b = 0) : a ≡ b := by rewrite [↑equiv, H1, H2, *zero_mul] theorem equiv.trans [trans] {a b c : prerat} (H1 : a ≡ b) (H2 : b ≡ c) : a ≡ c := decidable.by_cases (suppose num b = 0, have num a = 0, from num_eq_zero_of_equiv (equiv.symm H1) `num b = 0`, have num c = 0, from num_eq_zero_of_equiv H2 `num b = 0`, equiv_of_num_eq_zero `num a = 0` `num c = 0`) (suppose num b ≠ 0, have H3 : num b * denom b ≠ 0, from mul_ne_zero this (ne_of_gt (denom_pos b)), have H4 : (num b * denom b) * (num a * denom c) = (num b * denom b) * (num c * denom a), from calc (num b * denom b) * (num a * denom c) = (num a * denom b) * (num b * denom c) : by rewrite [*mul.assoc, *mul.left_comm (num a), *mul.left_comm (num b)] ... = (num b * denom a) * (num b * denom c) : {H1} ... = (num b * denom a) * (num c * denom b) : {H2} ... = (num b * denom b) * (num c * denom a) : by rewrite [*mul.assoc, *mul.left_comm (denom a), *mul.left_comm (denom b), mul.comm (denom a)], eq_of_mul_eq_mul_left H3 H4) theorem equiv.is_equivalence : equivalence equiv := mk_equivalence equiv equiv.refl @equiv.symm @equiv.trans definition setoid : setoid prerat := setoid.mk equiv equiv.is_equivalence /- field operations -/ definition of_int (i : int) : prerat := prerat.mk i 1 !of_nat_succ_pos definition zero : prerat := of_int 0 definition one : prerat := of_int 1 private theorem mul_denom_pos (a b : prerat) : denom a * denom b > 0 := mul_pos (denom_pos a) (denom_pos b) definition add (a b : prerat) : prerat := prerat.mk (num a * denom b + num b * denom a) (denom a * denom b) (mul_denom_pos a b) definition mul (a b : prerat) : prerat := prerat.mk (num a * num b) (denom a * denom b) (mul_denom_pos a b) definition neg (a : prerat) : prerat := prerat.mk (- num a) (denom a) (denom_pos a) definition smul (a : ℤ) (b : prerat) (H : a > 0) : prerat := prerat.mk (a * num b) (a * denom b) (mul_pos H (denom_pos b)) theorem of_int_add (a b : ℤ) : of_int (a + b) ≡ add (of_int a) (of_int b) := by esimp [equiv, one, add, of_int]; rewrite [*int.mul_one] theorem of_int_mul (a b : ℤ) : of_int (a * b) ≡ mul (of_int a) (of_int b) := !equiv.refl theorem of_int_neg (a : ℤ) : of_int (-a) ≡ neg (of_int a) := !equiv.refl theorem of_int.inj {a b : ℤ} : of_int a ≡ of_int b → a = b := by rewrite [↑of_int, ↑equiv, *mul_one]; intros; assumption definition inv : prerat → prerat | inv (prerat.mk nat.zero d dp) := zero | inv (prerat.mk (nat.succ n) d dp) := prerat.mk d (nat.succ n) !of_nat_succ_pos | inv (prerat.mk -[1+n] d dp) := prerat.mk (-d) (nat.succ n) !of_nat_succ_pos theorem equiv_zero_of_num_eq_zero {a : prerat} (H : num a = 0) : a ≡ zero := by rewrite [↑equiv, H, ↑zero, ↑of_int, *zero_mul] theorem num_eq_zero_of_equiv_zero {a : prerat} : a ≡ zero → num a = 0 := by rewrite [↑equiv, ↑zero, ↑of_int, mul_one, zero_mul]; intro H; exact H theorem inv_zero {d : int} (dp : d > 0) : inv (mk nat.zero d dp) = zero := begin rewrite [↑inv, ▸*] end theorem inv_zero' : inv zero = zero := inv_zero (of_nat_succ_pos nat.zero) open nat theorem inv_of_pos {n d : int} (np : n > 0) (dp : d > 0) : inv (mk n d dp) ≡ mk d n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have (n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this, have d * n = d * nat.succ k, by rewrite [Hn', Hk], Hn'⁻¹ ▸ (Hk⁻¹ ▸ this) theorem inv_neg {n d : int} (np : n > 0) (dp : d > 0) : inv (mk (-n) d dp) ≡ mk (-d) n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have (n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this, have -d * n = -d * nat.succ k, by rewrite [Hn', Hk], have H3 : inv (mk -[1+k] d dp) ≡ mk (-d) n np, from this, have H4 : -[1+k] = -n, from calc -[1+k] = -(nat.succ k) : rfl ... = -n : by rewrite [Hk⁻¹, Hn'], H4 ▸ H3 theorem inv_of_neg {n d : int} (nn : n < 0) (dp : d > 0) : inv (mk n d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn) := have inv (mk (-(-n)) d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn), from inv_neg (neg_pos_of_neg nn) dp, !neg_neg ▸ this /- operations respect equiv -/ theorem add_equiv_add {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) : add a1 b1 ≡ add a2 b2 := calc (num a1 * denom b1 + num b1 * denom a1) * (denom a2 * denom b2) = num a1 * denom a2 * denom b1 * denom b2 + num b1 * denom b2 * denom a1 * denom a2 : by rewrite [right_distrib, *mul.assoc, mul.left_comm (denom b1), mul.comm (denom b2), *mul.assoc] ... = num a2 * denom a1 * denom b1 * denom b2 + num b2 * denom b1 * denom a1 * denom a2 : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * denom b2 + num b2 * denom a2) * (denom a1 * denom b1) : by rewrite [right_distrib, *mul.assoc, *mul.left_comm (denom b2), *mul.comm (denom b1), *mul.assoc, mul.left_comm (denom a2)] theorem mul_equiv_mul {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) : mul a1 b1 ≡ mul a2 b2 := calc (num a1 * num b1) * (denom a2 * denom b2) = (num a1 * denom a2) * (num b1 * denom b2) : by rewrite [*mul.assoc, mul.left_comm (num b1)] ... = (num a2 * denom a1) * (num b2 * denom b1) : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * num b2) * (denom a1 * denom b1) : by rewrite [*mul.assoc, mul.left_comm (num b2)] theorem neg_equiv_neg {a b : prerat} (eqv : a ≡ b) : neg a ≡ neg b := calc -num a * denom b = -(num a * denom b) : neg_mul_eq_neg_mul ... = -(num b * denom a) : {eqv} ... = -num b * denom a : neg_mul_eq_neg_mul theorem inv_equiv_inv : ∀{a b : prerat}, a ≡ b → inv a ≡ inv b | (mk an ad adp) (mk bn bd bdp) := assume H, lt.by_cases (assume an_neg : an < 0, have bn_neg : bn < 0, from num_neg_of_equiv H an_neg, calc inv (mk an ad adp) ≡ mk (-ad) (-an) (neg_pos_of_neg an_neg) : inv_of_neg an_neg adp ... ≡ mk (-bd) (-bn) (neg_pos_of_neg bn_neg) : by rewrite [↑equiv at *, ▸*, *neg_mul_neg, mul.comm ad, mul.comm bd, H] ... ≡ inv (mk bn bd bdp) : (inv_of_neg bn_neg bdp)⁻¹) (assume an_zero : an = 0, have bn_zero : bn = 0, from num_eq_zero_of_equiv H an_zero, eq.subst (calc inv (mk an ad adp) = inv (mk 0 ad adp) : {an_zero} ... = zero : inv_zero adp ... = inv (mk 0 bd bdp) : inv_zero bdp ... = inv (mk bn bd bdp) : bn_zero) !equiv.refl) (assume an_pos : an > 0, have bn_pos : bn > 0, from num_pos_of_equiv H an_pos, calc inv (mk an ad adp) ≡ mk ad an an_pos : inv_of_pos an_pos adp ... ≡ mk bd bn bn_pos : by rewrite [↑equiv at *, ▸*, mul.comm ad, mul.comm bd, H] ... ≡ inv (mk bn bd bdp) : (inv_of_pos bn_pos bdp)⁻¹) theorem smul_equiv {a : ℤ} {b : prerat} (H : a > 0) : smul a b H ≡ b := by esimp[equiv, smul]; rewrite[mul.assoc, mul.left_comm] /- properties -/ protected theorem add.comm (a b : prerat) : add a b ≡ add b a := by rewrite [↑add, ↑equiv, ▸*, add.comm, mul.comm (denom a)] protected theorem add.assoc (a b c : prerat) : add (add a b) c ≡ add a (add b c) := by rewrite [↑add, ↑equiv, ▸*, *(mul.comm (num c)), *(λy, mul.comm y (denom a)), *left_distrib, *right_distrib, *mul.assoc, *add.assoc] protected theorem add_zero (a : prerat) : add a zero ≡ a := by rewrite [↑add, ↑equiv, ↑zero, ↑of_int, ▸*, *mul_one, zero_mul, add_zero] protected theorem add_left_inv (a : prerat) : add (neg a) a ≡ zero := by rewrite [↑add, ↑equiv, ↑neg, ↑zero, ↑of_int, ▸*, -neg_mul_eq_neg_mul, add.left_inv, *zero_mul] protected theorem mul_comm (a b : prerat) : mul a b ≡ mul b a := by rewrite [↑mul, ↑equiv, mul.comm (num a), mul.comm (denom a)] protected theorem mul_assoc (a b c : prerat) : mul (mul a b) c ≡ mul a (mul b c) := by rewrite [↑mul, ↑equiv, *mul.assoc] protected theorem mul_one (a : prerat) : mul a one ≡ a := by rewrite [↑mul, ↑one, ↑of_int, ↑equiv, ▸*, *mul_one] protected theorem mul_left_distrib (a b c : prerat) : mul a (add b c) ≡ add (mul a b) (mul a c) := have H : smul (denom a) (mul a (add b c)) (denom_pos a) = add (mul a b) (mul a c), from begin rewrite[↑smul, ↑mul, ↑add], congruence, rewrite[*left_distrib, *right_distrib, -+(int.mul_assoc)], have T : ∀ {x y z w : ℤ}, x*y*z*w=y*z*x*w, from λx y z w, (!int.mul_assoc ⬝ !int.mul_comm) ▸ rfl, exact !congr_arg2 T T, rewrite [mul.left_comm (denom a) (denom b) (denom c)], rewrite int.mul_assoc end, equiv.symm (H ▸ smul_equiv (denom_pos a)) theorem mul_inv_cancel : ∀{a : prerat}, ¬ a ≡ zero → mul a (inv a) ≡ one | (mk an ad adp) := assume H, let a := mk an ad adp in lt.by_cases (assume an_neg : an < 0, let ia := mk (-ad) (-an) (neg_pos_of_neg an_neg) in calc mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_neg an_neg adp) ... ≡ one : begin esimp [equiv, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, mul.comm, neg_mul_comm] end) (assume an_zero : an = 0, absurd (equiv_zero_of_num_eq_zero an_zero) H) (assume an_pos : an > 0, let ia := mk ad an an_pos in calc mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_pos an_pos adp) ... ≡ one : begin esimp [equiv, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, mul.comm] end) theorem zero_not_equiv_one : ¬ zero ≡ one := begin esimp [equiv, zero, one, of_int], rewrite [zero_mul, int.mul_one], exact zero_ne_one end theorem mul_denom_equiv (a : prerat) : mul a (of_int (denom a)) ≡ of_int (num a) := by esimp [mul, of_int, equiv]; rewrite [*int.mul_one] /- Reducing a fraction to lowest terms. Needed to choose a canonical representative of rat, and define numerator and denominator. -/ definition reduce : prerat → prerat | (mk an ad adpos) := have pos : ad / gcd an ad > 0, from div_pos_of_pos_of_dvd adpos !gcd_nonneg !gcd_dvd_right, if an = 0 then prerat.zero else mk (an / gcd an ad) (ad / gcd an ad) pos protected theorem eq {a b : prerat} (Hn : num a = num b) (Hd : denom a = denom b) : a = b := begin cases a with [an, ad, adpos], cases b with [bn, bd, bdpos], generalize adpos, generalize bdpos, esimp at *, rewrite [Hn, Hd], intros, apply rfl end theorem reduce_equiv : ∀ a : prerat, reduce a ≡ a | (mk an ad adpos) := decidable.by_cases (assume anz : an = 0, begin rewrite [↑reduce, if_pos anz, ↑equiv, anz], krewrite zero_mul end) (assume annz : an ≠ 0, by rewrite [↑reduce, if_neg annz, ↑equiv, mul.comm, -!int.mul_div_assoc !gcd_dvd_left, -!int.mul_div_assoc !gcd_dvd_right, mul.comm]) theorem reduce_eq_reduce : ∀ {a b : prerat}, a ≡ b → reduce a = reduce b | (mk an ad adpos) (mk bn bd bdpos) := assume H : an * bd = bn * ad, decidable.by_cases (assume anz : an = 0, have H' : bn * ad = 0, by rewrite [-H, anz, zero_mul], have bnz : bn = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt adpos), by rewrite [↑reduce, if_pos anz, if_pos bnz]) (assume annz : an ≠ 0, have bnnz : bn ≠ 0, from assume bnz, have H' : an * bd = 0, by rewrite [H, bnz, zero_mul], have anz : an = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt bdpos), show false, from annz anz, begin rewrite [↑reduce, if_neg annz, if_neg bnnz], apply prerat.eq, {apply div_gcd_eq_div_gcd H adpos bdpos}, {esimp, rewrite [gcd.comm, gcd.comm bn], apply div_gcd_eq_div_gcd_of_nonneg, rewrite [mul.comm, -H, mul.comm], apply annz, apply bnnz, apply le_of_lt adpos, apply le_of_lt bdpos}, end) end prerat /- the rationals -/ definition rat : Type.{1} := quot prerat.setoid notation `ℚ` := rat local attribute prerat.setoid [instance] namespace rat /- operations -/ definition of_int [coercion] (i : ℤ) : ℚ := ⟦prerat.of_int i⟧ definition of_nat [coercion] (n : ℕ) : ℚ := n definition of_num [coercion] [reducible] (n : num) : ℚ := n protected definition prio := num.pred int.prio definition rat_has_zero [instance] [priority rat.prio] : has_zero rat := has_zero.mk (of_int 0) definition rat_has_one [instance] [priority rat.prio] : has_one rat := has_one.mk (of_int 1) theorem of_int_zero : of_int (0:int) = (0:rat) := rfl theorem of_int_one : of_int (1:int) = (1:rat) := rfl protected definition add : ℚ → ℚ → ℚ := quot.lift₂ (λ a b : prerat, ⟦prerat.add a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.add_equiv_add H1 H2)) protected definition mul : ℚ → ℚ → ℚ := quot.lift₂ (λ a b : prerat, ⟦prerat.mul a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.mul_equiv_mul H1 H2)) protected definition neg : ℚ → ℚ := quot.lift (λ a : prerat, ⟦prerat.neg a⟧) (take a1 a2, assume H, quot.sound (prerat.neg_equiv_neg H)) protected definition inv : ℚ → ℚ := quot.lift (λ a : prerat, ⟦prerat.inv a⟧) (take a1 a2, assume H, quot.sound (prerat.inv_equiv_inv H)) definition reduce : ℚ → prerat := quot.lift (λ a : prerat, prerat.reduce a) @prerat.reduce_eq_reduce definition num (a : ℚ) : ℤ := prerat.num (reduce a) definition denom (a : ℚ) : ℤ := prerat.denom (reduce a) theorem denom_pos (a : ℚ): denom a > 0 := prerat.denom_pos (reduce a) definition rat_has_add [instance] [priority rat.prio] : has_add rat := has_add.mk rat.add definition rat_has_mul [instance] [priority rat.prio] : has_mul rat := has_mul.mk rat.mul definition rat_has_neg [instance] [priority rat.prio] : has_neg rat := has_neg.mk rat.neg definition rat_has_inv [instance] [priority rat.prio] : has_inv rat := has_inv.mk rat.inv protected definition sub [reducible] (a b : ℚ) : rat := a + (-b) definition rat_has_sub [instance] [priority rat.prio] : has_sub rat := has_sub.mk rat.sub lemma sub.def (a b : ℚ) : a - b = a + (-b) := rfl /- properties -/ theorem of_int_add (a b : ℤ) : of_int (a + b) = of_int a + of_int b := quot.sound (prerat.of_int_add a b) theorem of_int_mul (a b : ℤ) : of_int (a * b) = of_int a * of_int b := quot.sound (prerat.of_int_mul a b) theorem of_int_neg (a : ℤ) : of_int (-a) = -(of_int a) := quot.sound (prerat.of_int_neg a) theorem of_int_sub (a b : ℤ) : of_int (a - b) = of_int a - of_int b := calc of_int (a - b) = of_int a + of_int (-b) : of_int_add ... = of_int a - of_int b : {of_int_neg b} theorem of_int.inj {a b : ℤ} (H : of_int a = of_int b) : a = b := prerat.of_int.inj (quot.exact H) theorem eq_of_of_int_eq_of_int {a b : ℤ} (H : of_int a = of_int b) : a = b := of_int.inj H theorem of_int_eq_of_int_iff (a b : ℤ) : of_int a = of_int b ↔ a = b := iff.intro eq_of_of_int_eq_of_int !congr_arg theorem of_nat_eq (a : ℕ) : of_nat a = of_int (int.of_nat a) := rfl open nat theorem of_nat_add (a b : ℕ) : of_nat (a + b) = of_nat a + of_nat b := by rewrite [of_nat_eq, int.of_nat_add, rat.of_int_add] theorem of_nat_mul (a b : ℕ) : of_nat (a * b) = of_nat a * of_nat b := by rewrite [of_nat_eq, int.of_nat_mul, rat.of_int_mul] theorem of_nat_sub {a b : ℕ} (H : a ≥ b) : of_nat (a - b) = of_nat a - of_nat b := begin rewrite of_nat_eq, rewrite [int.of_nat_sub H], rewrite [rat.of_int_sub] end theorem of_nat.inj {a b : ℕ} (H : of_nat a = of_nat b) : a = b := int.of_nat.inj (of_int.inj H) theorem eq_of_of_nat_eq_of_nat {a b : ℕ} (H : of_nat a = of_nat b) : a = b := of_nat.inj H theorem of_nat_eq_of_nat_iff (a b : ℕ) : of_nat a = of_nat b ↔ a = b := iff.intro of_nat.inj !congr_arg protected theorem add_comm (a b : ℚ) : a + b = b + a := quot.induction_on₂ a b (take u v, quot.sound !prerat.add.comm) protected theorem add_assoc (a b c : ℚ) : a + b + c = a + (b + c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.add.assoc) protected theorem add_zero (a : ℚ) : a + 0 = a := quot.induction_on a (take u, quot.sound !prerat.add_zero) protected theorem zero_add (a : ℚ) : 0 + a = a := !rat.add_comm ▸ !rat.add_zero protected theorem add_left_inv (a : ℚ) : -a + a = 0 := quot.induction_on a (take u, quot.sound !prerat.add_left_inv) protected theorem mul_comm (a b : ℚ) : a * b = b * a := quot.induction_on₂ a b (take u v, quot.sound !prerat.mul_comm) protected theorem mul_assoc (a b c : ℚ) : a * b * c = a * (b * c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul_assoc) protected theorem mul_one (a : ℚ) : a * 1 = a := quot.induction_on a (take u, quot.sound !prerat.mul_one) protected theorem one_mul (a : ℚ) : 1 * a = a := !rat.mul_comm ▸ !rat.mul_one protected theorem left_distrib (a b c : ℚ) : a * (b + c) = a * b + a * c := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul_left_distrib) protected theorem right_distrib (a b c : ℚ) : (a + b) * c = a * c + b * c := by rewrite [rat.mul_comm, rat.left_distrib, *rat.mul_comm c] protected theorem mul_inv_cancel {a : ℚ} : a ≠ 0 → a * a⁻¹ = 1 := quot.induction_on a (take u, assume H, quot.sound (!prerat.mul_inv_cancel (assume H1, H (quot.sound H1)))) protected theorem inv_mul_cancel {a : ℚ} (H : a ≠ 0) : a⁻¹ * a = 1 := !rat.mul_comm ▸ rat.mul_inv_cancel H protected theorem zero_ne_one : (0 : ℚ) ≠ 1 := assume H, prerat.zero_not_equiv_one (quot.exact H) definition has_decidable_eq [instance] : decidable_eq ℚ := take a b, quot.rec_on_subsingleton₂ a b (take u v, if H : prerat.num u * prerat.denom v = prerat.num v * prerat.denom u then decidable.inl (quot.sound H) else decidable.inr (assume H1, H (quot.exact H1))) protected theorem inv_zero : inv 0 = (0 : ℚ) := quot.sound (prerat.inv_zero' ▸ !prerat.equiv.refl) theorem quot_reduce (a : ℚ) : ⟦reduce a⟧ = a := quot.induction_on a (take u, quot.sound !prerat.reduce_equiv) section local attribute rat [reducible] theorem mul_denom (a : ℚ) : a * denom a = num a := have H : ⟦reduce a⟧ * of_int (denom a) = of_int (num a), from quot.sound (!prerat.mul_denom_equiv), quot_reduce a ▸ H end theorem coprime_num_denom (a : ℚ) : coprime (num a) (denom a) := decidable.by_cases (suppose a = 0, by substvars) (quot.induction_on a (take u H, have H' : prerat.num u ≠ 0, from take H'', H (quot.sound (prerat.equiv_zero_of_num_eq_zero H'')), begin cases u with un ud udpos, rewrite [▸*, ↑num, ↑denom, ↑reduce, ↑prerat.reduce, if_neg H', ▸*], have gcd un ud ≠ 0, from ne_of_gt (!gcd_pos_of_ne_zero_left H'), apply coprime_div_gcd_div_gcd this end)) protected definition discrete_field [trans_instance] : discrete_field rat := ⦃discrete_field, add := rat.add, add_assoc := rat.add_assoc, zero := 0, zero_add := rat.zero_add, add_zero := rat.add_zero, neg := rat.neg, add_left_inv := rat.add_left_inv, add_comm := rat.add_comm, mul := rat.mul, mul_assoc := rat.mul_assoc, one := 1, one_mul := rat.one_mul, mul_one := rat.mul_one, left_distrib := rat.left_distrib, right_distrib := rat.right_distrib, mul_comm := rat.mul_comm, mul_inv_cancel := @rat.mul_inv_cancel, inv_mul_cancel := @rat.inv_mul_cancel, zero_ne_one := rat.zero_ne_one, inv_zero := rat.inv_zero, has_decidable_eq := has_decidable_eq⦄ definition rat_has_div [instance] [priority rat.prio] : has_div rat := has_div.mk has_div.div definition rat_has_pow_nat [instance] [priority rat.prio] : has_pow_nat rat := has_pow_nat.mk has_pow_nat.pow_nat theorem eq_num_div_denom (a : ℚ) : a = num a / denom a := have H : of_int (denom a) ≠ 0, from assume H', ne_of_gt (denom_pos a) (of_int.inj H'), iff.mpr (!eq_div_iff_mul_eq H) (mul_denom a) theorem of_int_div {a b : ℤ} (H : b ∣ a) : of_int (a / b) = of_int a / of_int b := decidable.by_cases (assume bz : b = 0, by rewrite [bz, int.div_zero, of_int_zero, div_zero]) (assume bnz : b ≠ 0, have bnz' : of_int b ≠ 0, from assume oibz, bnz (of_int.inj oibz), have H' : of_int (a / b) * of_int b = of_int a, from dvd.elim H (take c, assume Hc : a = b * c, by rewrite [Hc, !int.mul_div_cancel_left bnz, mul.comm]), iff.mpr (!eq_div_iff_mul_eq bnz') H') theorem of_nat_div {a b : ℕ} (H : b ∣ a) : of_nat (a / b) = of_nat a / of_nat b := have H' : (int.of_nat b ∣ int.of_nat a), by rewrite [int.of_nat_dvd_of_nat_iff]; exact H, by rewrite [of_nat_eq, int.of_nat_div, of_int_div H'] theorem of_int_pow (a : ℤ) (n : ℕ) : of_int (a^n) = (of_int a)^n := begin induction n with n ih, apply eq.refl, rewrite [pow_succ, pow_succ, of_int_mul, ih] end theorem of_nat_pow (a : ℕ) (n : ℕ) : of_nat (a^n) = (of_nat a)^n := by rewrite [of_nat_eq, int.of_nat_pow, of_int_pow] end rat
d006f7b7c3c2290d50c8592edf0e5da50d9c50e2
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/my_tac_class.lean
f6d5b2b21b5deae9e87408aa20cdc97bd19e177f
[ "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
1,761
lean
meta def mytac := state_t nat tactic meta instance : monad mytac := state_t.monad _ _ meta instance : monad.has_monad_lift tactic mytac := monad.monad_transformer_lift (state_t nat) tactic meta instance (α : Type) : has_coe (tactic α) (mytac α) := ⟨monad.monad_lift⟩ namespace mytac meta def step {α : Type} (t : mytac α) : mytac unit := t >> return () meta def istep {α : Type} (line0 col0 line col : nat) (t : mytac α) : mytac unit := λ v s, result.cases_on (@scope_trace _ line col (λ_, t v s)) (λ ⟨a, v⟩ new_s, result.success ((), v) new_s) (λ opt_msg_thunk e new_s, match opt_msg_thunk with | some msg_thunk := let msg := λ _ : unit, msg_thunk () ++ format.line ++ to_fmt "value: " ++ to_fmt v ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in interaction_monad.result.exception (some msg) (some ⟨line, col⟩) new_s | none := interaction_monad.silent_fail new_s end) meta def execute (tac : mytac unit) : tactic unit := tac 0 >> return () meta def save_info (p : pos) : mytac unit := do v ← state_t.read, s ← tactic.read, tactic.save_info_thunk p (λ _, to_fmt "Custom state: " ++ to_fmt v ++ format.line ++ tactic_state.to_format s) namespace interactive meta def intros : mytac unit := tactic.intros >> return () meta def constructor : mytac unit := tactic.constructor meta def trace (s : string) : mytac unit := tactic.trace s meta def assumption : mytac unit := tactic.assumption meta def inc : mytac unit := do v ← state_t.read, state_t.write (v+1) end interactive end mytac example (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, inc, trace "test", constructor, inc, assumption, assumption end
3a67472c2cdccc6e44f44d2bf9539655c61f0e80
1901b51268d21ec7361af7d3534abd9a8fa5cf52
/src/graph_theory/path.lean
0849062bf616dba97b3dcdfd4c5511f8d2e63700
[]
no_license
vbeffara/lean
b9ea4107deeaca6f4da98e5de029b62e4861ab40
0004b1d502ac3f4ccd213dbd23589d4c4f9fece8
refs/heads/main
1,652,050,034,756
1,651,610,858,000
1,651,610,858,000
225,244,535
6
1
null
null
null
null
UTF-8
Lean
false
false
2,695
lean
import tactic import combinatorics.simple_graph.connectivity import graph_theory.basic graph_theory.pushforward open relation relation.refl_trans_gen namespace simple_graph variables {V V' : Type*} {G G₁ G₂ : simple_graph V} {G' : simple_graph V'} {u v x y z : V} variables {e : G.dart} {p : walk G x y} {p' : walk G y z} {p'' : walk G z u} variables {h : G.adj y z} {h' : G.adj u x} {h'' : G.adj z v} namespace walk infixr ` :: ` := cons infix ` ++ ` := append lemma point_of_size_0 : p.length = 0 → x = y := by { intro h, cases p, refl, contradiction } lemma mem_edges (h : e ∈ darts p) : e.fst ∈ p.support ∧ e.snd ∈ p.support := ⟨p.dart_fst_mem_support_of_mem_darts h, p.dart_snd_mem_support_of_mem_darts h⟩ lemma mem_of_edges (h : 0 < p.length) : u ∈ p.support ↔ ∃ e ∈ darts p, u ∈ dart.edge e := begin induction p with u u v w h p ih, { simp only [length_nil, nat.not_lt_zero] at h, contradiction }, { clear h, cases nat.eq_zero_or_pos (length p), { cases p, simp only [darts, dart.edge, support_cons, support_nil, list.mem_cons_iff, list.mem_singleton, sym2.mem_iff, exists_prop, exists_eq_left], simp only [length_cons, nat.succ_ne_zero] at h_1, contradiction }, { specialize ih h_1, clear h_1, simp only [dart.edge, sym2.mem_iff] at ih, split, { simp only [darts, dart.edge, support_cons, list.mem_cons_iff, sym2.mem_iff, exists_prop], intro h1, cases h1, { subst h1, use ⟨(u,v),h⟩, simp only [eq_self_iff_true, and_self, true_or, sym2.mem_iff] }, { obtain ⟨e,h2,h3⟩ := ih.mp h1, exact ⟨e, or.inr h2, h3⟩ } }, { simp only [darts, dart.edge, list.mem_cons_iff, sym2.mem_iff, support_cons, forall_exists_index, and_imp, forall_eq_or_imp], exact ⟨(λ h, or.cases_on h or.inl (λ h, by { subst h, exact or.inr (start_mem_support _) })), (λ e he h1, or.inr (ih.mpr ⟨e,he,h1⟩))⟩ } } } end lemma nodup_concat : (append p p').support.nodup ↔ p.support.nodup ∧ p'.support.nodup ∧ (∀ u, u ∈ p.support → u ∈ p'.support → u = y) := begin induction p with a a b c h q ih, { simp }, { simp only [cons_append, support_cons, list.nodup_cons, mem_support_append_iff, list.mem_cons_iff, forall_eq_or_imp], push_neg, split, { rintros ⟨⟨h1,h2⟩,h3⟩, replace ih := ih.mp h3, refine ⟨⟨h1,ih.1⟩,ih.2.1,_,λ u h4 h5, _⟩, intro, contradiction, exact ih.2.2 u h4 h5 }, { rintros ⟨⟨h1,h2⟩,h3,h4,h5⟩, refine ⟨⟨h1,_⟩,_⟩, intro h5, apply h1, rw h4 h5, exact end_mem_support _, refine ih.mpr ⟨h2,h3,_⟩, intros u hu h'u, exact h5 u hu h'u } } end end walk end simple_graph
ed451509c5cecdadb0cc987a732f1a80c475cbf7
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/separation.lean
2aed1b4eabd8e16979dd8ef92c41c11e01b4182e
[ "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
21,825
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 Separation properties of topological spaces. -/ import topology.subset_properties open set filter open_locale topological_space filter local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem exists_open_singleton_of_open_finset [t0_space α] (s : finset α) (sne : s.nonempty) (hso : is_open (↑s : set α)) : ∃ x ∈ s, is_open ({x} : set α):= begin induction s using finset.strong_induction_on with s ihs, by_cases hs : set.subsingleton (↑s : set α), { rcases sne with ⟨x, hx⟩, refine ⟨x, hx, _⟩, have : (↑s : set α) = {x}, from hs.eq_singleton_of_mem hx, rwa this at hso }, { dunfold set.subsingleton at hs, push_neg at hs, rcases hs with ⟨x, hx, y, hy, hxy⟩, rcases t0_space.t0 x y hxy with ⟨U, hU, hxyU⟩, wlog H : x ∈ U ∧ y ∉ U := hxyU using [x y, y x], obtain ⟨z, hzs, hz⟩ : ∃ z ∈ s.filter (λ z, z ∈ U), is_open ({z} : set α), { refine ihs _ (finset.filter_ssubset.2 ⟨y, hy, H.2⟩) ⟨x, finset.mem_filter.2 ⟨hx, H.1⟩⟩ _, rw [finset.coe_filter], exact is_open_inter hso hU }, exact ⟨z, (finset.mem_filter.1 hzs).1, hz⟩ } end theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := begin refine ha.elim (λ x, _), have : is_open (↑(finset.univ : finset α) : set α), { simp }, rcases exists_open_singleton_of_open_finset _ ⟨x, finset.mem_univ x⟩ this with ⟨x, _, hx⟩, exact ⟨x, hx⟩ end instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) := ⟨λ x y hxy, let ⟨U, hU, hxyU⟩ := t0_space.t0 (x:α) y ((not_congr subtype.ext_iff_val).1 hxy) in ⟨(coe : subtype p → α) ⁻¹' U, is_open_induced hU, hxyU⟩⟩ /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} := compl_singleton_eq x ▸ is_open_compl_iff.2 (t1_space.t1 x) instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} : t1_space (subtype p) := ⟨λ ⟨x, hx⟩, is_closed_induced_iff.2 $ ⟨{x}, is_closed_singleton, set.ext $ λ y, by simp [subtype.ext_iff_val]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨{z | z ≠ y}, is_open_ne, or.inl ⟨h, not_not_intro rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := is_closed_singleton.closure_eq /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, (ext_iff.1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in absurd huv $ (inf_ne_bot_iff.1 h (mem_nhds_sets hu hx) (mem_nhds_sets hv hy)).ne_empty lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, ne_bot (𝓝 x ⊓ 𝓝 y) → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot, assume h, ⟨assume x y xy, have 𝓝 x ⊓ 𝓝 y = ⊥ := classical.by_contradiction (mt h xy), let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ 𝓝 x → f ≤ 𝓝 y → x = y := t2_iff_nhds.trans ⟨assume h f x y u fx fy, h $ u.1.mono (le_inf fx fy), assume h x y xy, let ⟨f, hf, uf⟩ := @@exists_ultrafilter _ xy in h f uf (le_trans hf inf_le_left) (le_trans hf inf_le_right)⟩ lemma is_closed_diagonal [t2_space α] : is_closed (diagonal α) := is_closed_iff_cluster_pt.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_ne_bot $ assume : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ 𝓝 a₁ at ht₁, change t₂ ∈ 𝓝 a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) := begin split, { introI h, exact is_closed_diagonal }, { intro h, constructor, intros x y hxy, have : (x, y) ∈ (diagonal α)ᶜ, by rwa [mem_compl_iff], obtain ⟨t, t_sub, t_op, xyt⟩ : ∃ t ⊆ (diagonal α)ᶜ, is_open t ∧ (x, y) ∈ t := is_open_iff_forall_mem_open.mp h _ this, rcases is_open_prod_iff.mp t_op x y xyt with ⟨U, V, U_op, V_op, xU, yV, H⟩, use [U, V, U_op, V_op, xU, yV], have := subset.trans H t_sub, rw eq_empty_iff_forall_not_mem, rintros z ⟨zU, zV⟩, have : ¬ (z, z) ∈ diagonal α := this (mk_mem_prod zU zV), exact this rfl }, end @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique' [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : ne_bot l) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb section lim variables [t2_space α] {f : filter α} /-! ### Properties of `Lim` and `lim` In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas are useful without a `nonempty α` instance. -/ lemma Lim_eq {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : @Lim _ _ ⟨a⟩ f = a := tendsto_nhds_unique (Lim_spec ⟨a, h⟩) h lemma filter.tendsto.lim_eq {a : α} {f : filter β} {g : β → α} (h : tendsto g f (𝓝 a)) [ne_bot f] : @lim _ _ _ ⟨a⟩ f g = a := Lim_eq h lemma continuous.lim_eq [topological_space β] {f : β → α} (h : continuous f) (a : β) : @lim _ _ _ ⟨f a⟩ (𝓝 a) f = f a := (h.tendsto a).lim_eq @[simp] lemma Lim_nhds (a : α) : @Lim _ _ ⟨a⟩ (𝓝 a) = a := Lim_eq (le_refl _) @[simp] lemma lim_nhds_id (a : α) : @lim _ _ _ ⟨a⟩ (𝓝 a) id = a := Lim_nhds a @[simp] lemma Lim_nhds_within {a : α} {s : set α} (h : a ∈ closure s) : @Lim _ _ ⟨a⟩ (𝓝[s] a) = a := by haveI : ne_bot (𝓝[s] a) := mem_closure_iff_cluster_pt.1 h; exact Lim_eq inf_le_left @[simp] lemma lim_nhds_within_id {a : α} {s : set α} (h : a ∈ closure s) : @lim _ _ _ ⟨a⟩ (𝓝[s] a) id = a := Lim_nhds_within h end lim @[priority 100] -- see Note [lower instance priority] instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } private lemma separated_by_f {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : tα ≤ tβ.induced f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst inf_le_left h₁) (λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩ instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (infi_le _ i) hi⟩ variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ {p:α×α | p.1 = p.2}ᶜ ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma is_compact.is_closed [t2_space α] {s : set α} (hs : is_compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : is_compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ sᶜ, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma is_compact.inter [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∩ t) := hs.inter_right $ ht.is_closed /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ lemma is_compact.binary_compact_cover [t2_space α] {K U V : set α} (hK : is_compact K) (hU : is_open U) (hV : is_open V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : set α, is_compact K₁ ∧ is_compact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := begin rcases compact_compact_separated (compact_diff hK hU) (compact_diff hK hV) (by rwa [diff_inter_diff, diff_eq_empty]) with ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩, refine ⟨_, _, compact_diff hK h1O₁, compact_diff hK h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO, diff_empty]⟩ end section open finset function /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ lemma is_compact.finite_compact_cover [t2_space α] {s : set α} (hs : is_compact s) {ι} (t : finset ι) (U : ι → set α) (hU : ∀ i ∈ t, is_open (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → set α, (∀ i, is_compact (K i)) ∧ (∀i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := begin classical, induction t using finset.induction with x t hx ih generalizing U hU s hs hsC, { refine ⟨λ _, ∅, λ i, compact_empty, λ i, empty_subset _, _⟩, simpa only [subset_empty_iff, finset.not_mem_empty, Union_neg, Union_empty, not_false_iff] using hsC }, simp only [finset.bUnion_insert] at hsC, simp only [finset.mem_insert] at hU, have hU' : ∀ i ∈ t, is_open (U i) := λ i hi, hU i (or.inr hi), rcases hs.binary_compact_cover (hU x (or.inl rfl)) (is_open_bUnion hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩, rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩, refine ⟨update K x K₁, _, _, _⟩, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h1K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h1K] }}, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h2K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h2K] }}, { simp only [bUnion_insert_update _ hx, hK, h3K] } end end lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ is_compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : wᶜ ∈ 𝓝 x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k \ w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) /-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/ lemma exists_open_with_compact_closure [locally_compact_space α] [t2_space α] (x : α) : ∃ (U : set α), is_open U ∧ x ∈ U ∧ is_compact (closure U) := begin rcases locally_compact_space.local_compact_nhds x set.univ filter.univ_mem_sets with ⟨K, h1K, _, h2K⟩, rw [mem_nhds_sets_iff] at h1K, rcases h1K with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h2t, h3t, compact_of_is_closed_subset h2K is_closed_closure $ closure_minimal h1t $ h2K.is_closed⟩ end /-- In a locally compact T₂ space, every compact set is contained in the interior of a compact set. -/ lemma exists_compact_superset [locally_compact_space α] [t2_space α] {K : set α} (hK : is_compact K) : ∃ (K' : set α), is_compact K' ∧ K ⊆ interior K' := begin choose U hU using λ x : K, exists_open_with_compact_closure (x : α), rcases hK.elim_finite_subcover U (λ x, (hU x).1) (λ x hx, ⟨_, ⟨⟨x, hx⟩, rfl⟩, (hU ⟨x, hx⟩).2.1⟩) with ⟨s, hs⟩, refine ⟨⋃ (i : K) (H : i ∈ s), closure (U i), _, _⟩, exact (finite_mem_finset s).compact_bUnion (λ x hx, (hU x).2.2), refine subset.trans hs _, rw subset_interior_iff_subset_of_open, exact bUnion_subset_bUnion_right (λ x hx, subset_closure), exact is_open_bUnion (λ x hx, (hU x).1) end end separation section regularity /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝[t] a = ⊥) lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃t∈(𝓝 a), t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ s'ᶜ ⊆ t ∧ 𝓝[t] a = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨tᶜ, mem_sets_of_eq_bot $ by rwa [compl_compl], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ lemma closed_nhds_basis [regular_space α] (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_closed s) id := ⟨λ t, ⟨λ t_in, let ⟨s, s_in, h_st, h⟩ := nhds_is_closed t_in in ⟨s, ⟨s_in, h⟩, h_st⟩, λ ⟨s, ⟨s_in, hs⟩, hst⟩, mem_sets_of_superset s_in hst⟩⟩ instance subtype.regular_space [regular_space α] {p : α → Prop} : regular_space (subtype p) := ⟨begin intros s a hs ha, rcases is_closed_induced_iff.1 hs with ⟨s, hs', rfl⟩, rcases regular_space.regular hs' ha with ⟨t, ht, hst, hat⟩, refine ⟨coe ⁻¹' t, is_open_induced ht, preimage_mono hst, _⟩, rw [nhds_within, nhds_induced, ← comap_principal, ← comap_inf, ← nhds_within, hat, comap_bot] end⟩ variable (α) @[priority 100] -- see Note [lower instance priority] instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ variable {α} lemma disjoint_nested_nhds [regular_space α] {x y : α} (h : x ≠ y) : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := begin rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩, rcases nhds_is_closed (mem_nhds_sets U₁_op x_in) with ⟨V₁, V₁_in, h₁, V₁_closed⟩, rcases nhds_is_closed (mem_nhds_sets U₂_op y_in) with ⟨V₂, V₂_in, h₂, V₂_closed⟩, use [U₁, V₁, mem_sets_of_superset V₁_in h₁, V₁_in, U₂, V₂, mem_sets_of_superset V₂_in h₂, V₂_in], tauto end end regularity section normality /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) theorem normal_separation [normal_space α] (s t : set α) (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 @[priority 100] -- see Note [lower instance priority] instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated hs.compact ht.compact st.eq_bot end end normality
72223fb33fa9d61ec7aa6ef778d117dad1301e3a
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/rateval.lean
1133b32c66f03805dacbed3c4a3be61701a9833e
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
89
lean
import data.rat open nat int rat attribute rat.of_int [coercion] eval (8 * 6⁻¹) + 1
01554f48aeb4e14f463fcf91b27eccbab58c881c
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/real/nnreal.lean
90da56c94e5614f735a77a903cd1e3daf8ed5f0e
[ "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
25,502
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import algebra.linear_ordered_comm_group_with_zero import data.finset.lattice import data.real.basic noncomputable theory open_locale classical big_operators /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : nnreal) : n.val = n := rfl instance : can_lift ℝ nnreal := { coe := coe, cond := λ r, r ≥ 0, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y := not_iff_not_of_iff $ nnreal.eq_iff protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r := le_max_left r 0 lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := subtype.ext_iff_val.symm @[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast instance : comm_semiring ℝ≥0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero, add_comm, add_left_comm] } end /-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/ def to_real_hom : ℝ≥0 →+* ℝ := ⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩ @[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl instance : comm_group_with_zero ℝ≥0 := { exists_pair_ne := ⟨0, 1, assume h, zero_ne_one $ nnreal.eq_iff.2 h⟩, inv_zero := nnreal.eq $ show (0⁻¹ : ℝ) = 0, from inv_zero, mul_inv_cancel := assume x h, nnreal.eq $ mul_inv_cancel $ ne_iff.2 h, .. (by apply_instance : has_inv ℝ≥0), .. (_ : comm_semiring ℝ≥0), .. (_ : semiring ℝ≥0) } @[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := to_real_hom.map_pow r n @[norm_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := to_real_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := to_real_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := to_real_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := to_real_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = ∑ a in s, (f a : ℝ) := to_real_hom.map_sum _ _ @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) := to_real_hom.map_prod _ _ @[norm_cast] lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n •ℕ r) = n •ℕ (r:ℝ) := to_real_hom.to_add_monoid_hom.map_nsmul _ _ @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := to_real_hom.map_nat_cast n instance : decidable_linear_order ℝ≥0 := decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective @[norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma of_real_mono : monotone nnreal.of_real := λ x y h, max_le_max h (le_refl 0) @[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r := nnreal.eq $ max_eq_left r.2 /-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion nnreal.of_real coe := galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono le_coe_of_real (λ _, of_real_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order } instance : canonically_ordered_add_monoid ℝ≥0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.decidable_linear_order } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring } instance : linear_ordered_comm_group_with_zero ℝ≥0 := { mul_le_mul_left := assume a b h c, mul_le_mul (le_refl c) h (zero_le a) (zero_le c), zero_le_one := zero_le 1, .. nnreal.linear_ordered_semiring, .. nnreal.comm_group_with_zero } instance : canonically_ordered_comm_semiring ℝ≥0 := { .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring, .. (show no_zero_divisors ℝ≥0, by apply_instance), .. nnreal.comm_group_with_zero } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : has_Sup ℝ≥0 := ⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Sup_empty] }, rcases h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝ≥0 := ⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝ≥0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order, .. nnreal.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (n •ℕ y : nnreal), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end @[simp, norm_cast] lemma coe_max (x y : nnreal) : ((max x y : nnreal) : ℝ) = max (x : ℝ) (y : ℝ) := by { delta max, split_ifs; refl } @[simp, norm_cast] lemma coe_min (x y : nnreal) : ((min x y : nnreal) : ℝ) = min (x : ℝ) (y : ℝ) := by { delta min, split_ifs; refl } section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_one : nnreal.of_real 1 = 1 := by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) : nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p := nnreal.of_real_mono h lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp] lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha] lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] }, { rw [of_real_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact mul_left_cancel' (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, have := max_eq_left (mul_nonneg hp hq), simpa [nnreal.of_real, hp, hq, max_eq_left] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] } end @[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := mul_ne_zero h₁ h₂ end mul section sub lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h, sub_sub_cancel, nnreal.of_real_coe] lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) : (∑ i in s, f i) / b = ∑ i in s, (f i / b) := by simp only [nnreal.div_def, finset.sum_mul] @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := inv_eq_zero @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := mul_pos hr (inv_pos.2 hp) @[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one @[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one] protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev' _ _ protected lemma inv_pow {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n := nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm } @[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 := mul_inv_cancel h lemma div_self_le (r : ℝ≥0) : r / r ≤ 1 := if h : r = 0 then by simp [h] else by rw [div_self h] @[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r := by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one] @[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p := by rw [mul_comm, div_mul_cancel _ h] @[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq (inv_inv' _) @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm] lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r := @div_le_iff ℝ _ a r b $ zero_lt_iff_ne_zero.2 hr lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa [div_def] using half_lt_self zero_ne_one.symm lemma div_lt_iff {a b c : ℝ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c := begin rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul], exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc) end lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] theorem div_pow {a b : ℝ≥0} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := div_pow _ _ _ @[field_simps] lemma mul_div_assoc' (a b c : ℝ≥0) : a * (b / c) = (a * b) / c := by rw [div_def, div_def, mul_assoc] @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma inv_eq_one_div (a : ℝ≥0) : a⁻¹ = 1/a := by rw [div_def, one_mul] @[field_simps] lemma div_mul_eq_mul_div (a b c : ℝ≥0) : (a / b) * c = (a * c) / b := by { rw [div_def, div_def], ac_refl } @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma one_div_eq_inv (a : ℝ≥0) : 1 / a = a⁻¹ := one_mul a⁻¹ lemma one_div_div (a b : ℝ≥0) : 1 / (a / b) = b / a := by { rw ← nnreal.eq_iff, simp [one_div_div] } lemma div_eq_mul_one_div (a b : ℝ≥0) : a / b = a * (1 / b) := by rw [div_def, div_def, one_mul] @[field_simps] lemma div_div_eq_mul_div (a b c : ℝ≥0) : a / (b / c) = (a * c) / b := by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] } @[field_simps] lemma div_div_eq_div_mul (a b c : ℝ≥0) : (a / b) / c = a / (b * c) := by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] } @[field_simps] lemma div_eq_div_iff {a b c d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := div_eq_div_iff hb hd @[field_simps] lemma div_eq_iff {a b c : ℝ≥0} (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff {a b c : ℝ≥0} (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb end inv section pow theorem pow_eq_zero {a : ℝ≥0} {n : ℕ} (h : a^n = 0) : a = 0 := begin rw ← nnreal.eq_iff, rw [← nnreal.eq_iff, coe_pow] at h, exact pow_eq_zero h end @[field_simps] theorem pow_ne_zero {a : ℝ≥0} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h end pow end nnreal
62bf1288772994edaa133bb30e93786dfc65db39
0b34fcbb56406e6ace0afd1986262e6f1d37047f
/Lean/tutorial.lean
98692f5ff789f226d64205ae2fb56bf4c17e6f54
[]
no_license
DragonLi/exercise
4315eeb557a8e8d6105f9eeb795a09c03453d0eb
a5de48643c8df04f6f79ca746efb9f969c10eb8c
refs/heads/master
1,626,276,318,220
1,615,186,706,000
1,615,186,706,000
18,544,224
0
0
null
null
null
null
UTF-8
Lean
false
false
1,500
lean
/- basic induction principle rec rec_on constructor.inj constructor.eq -/ /- basic proof tatic axiom <-> constant (postulate) assume <-> lambda show , from <-> term with anotated type have,from <-> let in suffices from <-> beta reduction: (lambda subgoal -> global goal) subgoal -/ variables p q : Prop example (h : p ∨ q) : q ∨ p := h.elim (assume hp : p, show q ∨ p, from or.intro_right q hp) (assume hq : q, show q ∨ p, from or.intro_left p hq) example : p ∨ q -> q ∨ p | (or.inl hp) := or.inr hp | (or.inr hq) := or.inl hq example (hp : p) (hnp : ¬p) : q := false.elim (hnp hp) example (hp : p) (hnp : ¬p) : q := absurd hp hnp #check @true.rec theorem and_swap : p ∧ q ↔ q ∧ p := iff.intro (assume h : p ∧ q, show q ∧ p, from and.intro (and.right h) (and.left h)) (assume h : q ∧ p, show p ∧ q, from and.intro (and.right h) (and.left h)) #check and_swap p q -- p ∧ q ↔ q ∧ p theorem and_swap1 : p ∧ q ↔ q ∧ p := ⟨ assume h, ⟨h.right, h.left⟩, λ h, ⟨h.right, h.left⟩ ⟩ example (h : p ∧ q) : q ∧ p := (and_swap p q).mp h example (h : p ∧ q) : q ∧ p := have hp : p, from and.left h, have hq : q, from and.right h, show q ∧ p, from and.intro hq hp section open classical #check em p example (h : ¬¬p) : p := by_cases (assume h1 : p, h1) (assume h1 : ¬p, absurd h1 h) theorem dne {p : Prop} (h : ¬¬p) : p := or.elim (em p) (assume hp : p, hp) (assume hnp : ¬p, absurd hnp h) end
ca13018a2ea95fb6bffa7493631e06461f93899c
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/aevb/aevb_correct.lean
126748c984c6342047b18023c9095b8bd7da05b1
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
1,463
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Proof of the end-to-end correctness theorem for the variational autoencoder: that backpropagation on AEVB samples correct gradients for the naive variational autoencoder we started with. -/ import .util .graph .prog .grads_correct .transformations ..prove_model_ok ..backprop_correct set_option profiler true namespace certigrad namespace aevb open graph list tactic certigrad.tactic #print "proving aevb_backprop_correct_for_naive_aevb..." theorem aevb_backprop_correct_for_naive_aevb (a : arch) (ws : weights a) (x_data : T [a^.n_in, a^.n_x]) : let g₀ : graph := naive_aevb a x_data, g_aevb : graph := reparam (integrate_kl g₀), fdict : env := mk_input_dict ws x_data g₀ in ∀ (tgt : reference) (idx : ℕ) (H_at_idx : at_idx g₀^.targets idx tgt), ∇ (λ θ₀, E (graph.to_dist (λ m, ⟦sum_costs m g₀^.costs⟧) (env.insert tgt θ₀ fdict) g₀^.nodes) dvec.head) (env.get tgt fdict) = E (graph.to_dist (λ m, backprop g_aevb^.costs g_aevb^.nodes m g_aevb^.targets) fdict g_aevb^.nodes) (λ dict, dvec.get tgt.2 dict idx) := begin whnf_target, intros tgt idx H_at_idx, simp only [@aevb_transformations_sound a ws x_data tgt idx H_at_idx], apply backprop_correct_on_aevb, rw [naive_aevb_as_graph] at H_at_idx, rw [naive_aevb_as_graph], exact H_at_idx end end aevb end certigrad
ea8751e257527a9206251b5008aa4559cc39e48a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/group/action.lean
4844a0f4c931b31cd4bfb5f9c52cf58fa81670bc
[ "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
8,778
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.group.measurable_equiv import measure_theory.measure.regular import dynamics.ergodic.measure_preserving import dynamics.minimal /-! # Measures invariant under group actions A measure `μ : measure α` is said to be *invariant* under an action of a group `G` if scalar multiplication by `c : G` is a measure preserving map for all `c`. In this file we define a typeclass for measures invariant under action of an (additive or multiplicative) group and prove some basic properties of such measures. -/ open_locale ennreal nnreal pointwise topological_space open measure_theory measure_theory.measure set function namespace measure_theory variables {G M α : Type*} /-- A measure `μ : measure α` is invariant under an additive action of `M` on `α` if for any measurable set `s : set α` and `c : M`, the measure of its preimage under `λ x, c +ᵥ x` is equal to the measure of `s`. -/ class vadd_invariant_measure (M α : Type*) [has_vadd M α] {_ : measurable_space α} (μ : measure α) : Prop := (measure_preimage_vadd [] : ∀ (c : M) ⦃s : set α⦄, measurable_set s → μ ((λ x, c +ᵥ x) ⁻¹' s) = μ s) /-- A measure `μ : measure α` is invariant under a multiplicative action of `M` on `α` if for any measurable set `s : set α` and `c : M`, the measure of its preimage under `λ x, c • x` is equal to the measure of `s`. -/ @[to_additive] class smul_invariant_measure (M α : Type*) [has_smul M α] {_ : measurable_space α} (μ : measure α) : Prop := (measure_preimage_smul [] : ∀ (c : M) ⦃s : set α⦄, measurable_set s → μ ((λ x, c • x) ⁻¹' s) = μ s) namespace smul_invariant_measure @[to_additive] instance zero [measurable_space α] [has_smul M α] : smul_invariant_measure M α 0 := ⟨λ _ _ _, rfl⟩ variables [has_smul M α] {m : measurable_space α} {μ ν : measure α} @[to_additive] instance add [smul_invariant_measure M α μ] [smul_invariant_measure M α ν] : smul_invariant_measure M α (μ + ν) := ⟨λ c s hs, show _ + _ = _ + _, from congr_arg2 (+) (measure_preimage_smul μ c hs) (measure_preimage_smul ν c hs)⟩ @[to_additive] instance smul [smul_invariant_measure M α μ] (c : ℝ≥0∞) : smul_invariant_measure M α (c • μ) := ⟨λ a s hs, show c • _ = c • _, from congr_arg ((•) c) (measure_preimage_smul μ a hs)⟩ @[to_additive] instance smul_nnreal [smul_invariant_measure M α μ] (c : ℝ≥0) : smul_invariant_measure M α (c • μ) := smul_invariant_measure.smul c end smul_invariant_measure section has_measurable_smul variables {m : measurable_space α} [measurable_space M] [has_smul M α] [has_measurable_smul M α] (c : M) (μ : measure α) [smul_invariant_measure M α μ] @[simp, to_additive] lemma measure_preserving_smul : measure_preserving ((•) c) μ μ := { measurable := measurable_const_smul c, map_eq := begin ext1 s hs, rw map_apply (measurable_const_smul c) hs, exact smul_invariant_measure.measure_preimage_smul μ c hs, end } @[simp, to_additive] lemma map_smul : map ((•) c) μ = μ := (measure_preserving_smul c μ).map_eq end has_measurable_smul variables (G) {m : measurable_space α} [group G] [mul_action G α] [measurable_space G] [has_measurable_smul G α] (c : G) (μ : measure α) /-- Equivalent definitions of a measure invariant under a multiplicative action of a group. - 0: `smul_invariant_measure G α μ`; - 1: for every `c : G` and a measurable set `s`, the measure of the preimage of `s` under scalar multiplication by `c` is equal to the measure of `s`; - 2: for every `c : G` and a measurable set `s`, the measure of the image `c • s` of `s` under scalar multiplication by `c` is equal to the measure of `s`; - 3, 4: properties 2, 3 for any set, including non-measurable ones; - 5: for any `c : G`, scalar multiplication by `c` maps `μ` to `μ`; - 6: for any `c : G`, scalar multiplication by `c` is a measure preserving map. -/ @[to_additive] lemma smul_invariant_measure_tfae : tfae [smul_invariant_measure G α μ, ∀ (c : G) s, measurable_set s → μ (((•) c) ⁻¹' s) = μ s, ∀ (c : G) s, measurable_set s → μ (c • s) = μ s, ∀ (c : G) s, μ (((•) c) ⁻¹' s) = μ s, ∀ (c : G) s, μ (c • s) = μ s, ∀ c : G, measure.map ((•) c) μ = μ, ∀ c : G, measure_preserving ((•) c) μ μ] := begin tfae_have : 1 ↔ 2, from ⟨λ h, h.1, λ h, ⟨h⟩⟩, tfae_have : 1 → 6, { introsI h c, exact (measure_preserving_smul c μ).map_eq, }, tfae_have : 6 → 7, from λ H c, ⟨measurable_const_smul c, H c⟩, tfae_have : 7 → 4, from λ H c, (H c).measure_preimage_emb (measurable_embedding_const_smul c), tfae_have : 4 → 5, from λ H c s, by { rw [← preimage_smul_inv], apply H }, tfae_have : 5 → 3, from λ H c s hs, H c s, tfae_have : 3 → 2, { intros H c s hs, rw preimage_smul, exact H c⁻¹ s hs }, tfae_finish end /-- Equivalent definitions of a measure invariant under an additive action of a group. - 0: `vadd_invariant_measure G α μ`; - 1: for every `c : G` and a measurable set `s`, the measure of the preimage of `s` under vector addition `(+ᵥ) c` is equal to the measure of `s`; - 2: for every `c : G` and a measurable set `s`, the measure of the image `c +ᵥ s` of `s` under vector addition `(+ᵥ) c` is equal to the measure of `s`; - 3, 4: properties 2, 3 for any set, including non-measurable ones; - 5: for any `c : G`, vector addition of `c` maps `μ` to `μ`; - 6: for any `c : G`, vector addition of `c` is a measure preserving map. -/ add_decl_doc vadd_invariant_measure_tfae variables {G} [smul_invariant_measure G α μ] @[simp, to_additive] lemma measure_preimage_smul (s : set α) : μ ((•) c ⁻¹' s) = μ s := ((smul_invariant_measure_tfae G μ).out 0 3).mp ‹_› c s @[simp, to_additive] lemma measure_smul (s : set α) : μ (c • s) = μ s := ((smul_invariant_measure_tfae G μ).out 0 4).mp ‹_› c s variable {μ} @[to_additive] lemma null_measurable_set.smul {s} (hs : null_measurable_set s μ) (c : G) : null_measurable_set (c • s) μ := by simpa only [← preimage_smul_inv] using hs.preimage (measure_preserving_smul _ _).quasi_measure_preserving section is_minimal variables (G) [topological_space α] [has_continuous_const_smul G α] [mul_action.is_minimal G α] {K U : set α} /-- If measure `μ` is invariant under a group action and is nonzero on a compact set `K`, then it is positive on any nonempty open set. In case of a regular measure, one can assume `μ ≠ 0` instead of `μ K ≠ 0`, see `measure_theory.measure_is_open_pos_of_smul_invariant_of_ne_zero`. -/ @[to_additive] lemma measure_is_open_pos_of_smul_invariant_of_compact_ne_zero (hK : is_compact K) (hμK : μ K ≠ 0) (hU : is_open U) (hne : U.nonempty) : 0 < μ U := let ⟨t, ht⟩ := hK.exists_finite_cover_smul G hU hne in pos_iff_ne_zero.2 $ λ hμU, hμK $ measure_mono_null ht $ (measure_bUnion_null_iff t.countable_to_set).2 $ λ _ _, by rwa measure_smul /-- If measure `μ` is invariant under an additive group action and is nonzero on a compact set `K`, then it is positive on any nonempty open set. In case of a regular measure, one can assume `μ ≠ 0` instead of `μ K ≠ 0`, see `measure_theory.measure_is_open_pos_of_vadd_invariant_of_ne_zero`. -/ add_decl_doc measure_is_open_pos_of_vadd_invariant_of_compact_ne_zero @[to_additive] lemma is_locally_finite_measure_of_smul_invariant (hU : is_open U) (hne : U.nonempty) (hμU : μ U ≠ ∞) : is_locally_finite_measure μ := ⟨λ x, let ⟨g, hg⟩ := hU.exists_smul_mem G x hne in ⟨(•) g ⁻¹' U, (hU.preimage (continuous_id.const_smul _)).mem_nhds hg, ne.lt_top $ by rwa [measure_preimage_smul]⟩⟩ variables [measure.regular μ] @[to_additive] lemma measure_is_open_pos_of_smul_invariant_of_ne_zero (hμ : μ ≠ 0) (hU : is_open U) (hne : U.nonempty) : 0 < μ U := let ⟨K, hK, hμK⟩ := regular.exists_compact_not_null.mpr hμ in measure_is_open_pos_of_smul_invariant_of_compact_ne_zero G hK hμK hU hne @[to_additive] lemma measure_pos_iff_nonempty_of_smul_invariant (hμ : μ ≠ 0) (hU : is_open U) : 0 < μ U ↔ U.nonempty := ⟨λ h, nonempty_of_measure_ne_zero h.ne', measure_is_open_pos_of_smul_invariant_of_ne_zero G hμ hU⟩ include G @[to_additive] lemma measure_eq_zero_iff_eq_empty_of_smul_invariant (hμ : μ ≠ 0) (hU : is_open U) : μ U = 0 ↔ U = ∅ := by rw [← not_iff_not, ← ne.def, ← pos_iff_ne_zero, measure_pos_iff_nonempty_of_smul_invariant G hμ hU, ← ne_empty_iff_nonempty] end is_minimal end measure_theory
26d7344f1430063d2196b15f23fa865bf12053db
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/theories/group_theory/finsubg.lean
04b98106990fe18ebc384e115bb0251ef1395e5f
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
20,500
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ -- develop the concept of finite subgroups based on finsets so that the properties -- can be used directly without translating from the set based theory first import data algebra.group .subgroup open function finset -- ⁻¹ in eq.ops conflicts with group ⁻¹ open eq.ops namespace group_theory open ops section subg -- we should be able to prove properties using finsets directly variables {G : Type} [group G] variable [decidable_eq G] definition finset_mul_closed_on [reducible] (H : finset G) : Prop := ∀ x y : G, x ∈ H → y ∈ H → x * y ∈ H definition finset_has_inv (H : finset G) : Prop := ∀ a : G, a ∈ H → a⁻¹ ∈ H structure is_finsubg [class] (H : finset G) : Type := (has_one : 1 ∈ H) (mul_closed : finset_mul_closed_on H) (has_inv : finset_has_inv H) definition univ_is_finsubg [instance] [finG : fintype G] : is_finsubg (@finset.univ G _) := is_finsubg.mk !mem_univ (λ x y Px Py, !mem_univ) (λ a Pa, !mem_univ) definition one_is_finsubg [instance] : is_finsubg ('{(1:G)}) := is_finsubg.mk !mem_singleton (λ x y Px Py, by rewrite [eq_of_mem_singleton Px, eq_of_mem_singleton Py, one_mul]; apply mem_singleton) (λ x Px, by rewrite [eq_of_mem_singleton Px, one_inv]; apply mem_singleton) lemma finsubg_has_one (H : finset G) [h : is_finsubg H] : 1 ∈ H := @is_finsubg.has_one G _ _ H h lemma finsubg_mul_closed (H : finset G) [h : is_finsubg H] {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := @is_finsubg.mul_closed G _ _ H h x y lemma finsubg_has_inv (H : finset G) [h : is_finsubg H] {a : G} : a ∈ H → a⁻¹ ∈ H := @is_finsubg.has_inv G _ _ H h a definition finsubg_to_subg [instance] {H : finset G} [h : is_finsubg H] : is_subgroup (ts H) := is_subgroup.mk (mem_eq_mem_to_set H 1 ▸ finsubg_has_one H) (take x y, begin repeat rewrite -mem_eq_mem_to_set, apply finsubg_mul_closed H end) (take a, begin repeat rewrite -mem_eq_mem_to_set, apply finsubg_has_inv H end) open nat lemma finsubg_eq_singleton_one_of_card_one {H : finset G} [h : is_finsubg H] : card H = 1 → H = '{1} := assume Pcard, eq.symm (eq_of_card_eq_of_subset (by rewrite [Pcard]) (subset_of_forall take g, by rewrite [mem_singleton_iff]; intro Pg; rewrite Pg; exact finsubg_has_one H)) end subg section fin_lcoset open set variables {A : Type} [decidable_eq A] [group A] definition fin_lcoset (H : finset A) (a : A) := finset.image (lmul_by a) H definition fin_rcoset (H : finset A) (a : A) : finset A := image (rmul_by a) H definition fin_lcosets (H G : finset A) := image (fin_lcoset H) G definition fin_inv : finset A → finset A := image inv variable {H : finset A} lemma lmul_rmul {a b : A} : (lmul_by a) ∘ (rmul_by b) = (rmul_by b) ∘ (lmul_by a) := funext take c, calc a*(c*b) = (a*c)*b : mul.assoc lemma fin_lrcoset_comm {a b : A} : fin_lcoset (fin_rcoset H b) a = fin_rcoset (fin_lcoset H a) b := by esimp [fin_lcoset, fin_rcoset]; rewrite [-*image_compose, lmul_rmul] lemma inv_mem_fin_inv {a : A} : a ∈ H → a⁻¹ ∈ fin_inv H := assume Pin, mem_image Pin rfl lemma fin_lcoset_eq (a : A) : ts (fin_lcoset H a) = a ∘> (ts H) := calc ts (fin_lcoset H a) = coset.l a (ts H) : to_set_image ... = a ∘> (ts H) : glcoset_eq_lcoset lemma fin_lcoset_id : fin_lcoset H 1 = H := by rewrite [eq_eq_to_set_eq, fin_lcoset_eq, glcoset_id] lemma fin_lcoset_compose (a b : A) : fin_lcoset (fin_lcoset H b) a = fin_lcoset H (a*b) := to_set.inj (by rewrite [*fin_lcoset_eq, glcoset_compose]) lemma fin_lcoset_inv (a : A) : fin_lcoset (fin_lcoset H a) a⁻¹ = H := to_set.inj (by rewrite [*fin_lcoset_eq, glcoset_inv]) lemma fin_lcoset_card (a : A) : card (fin_lcoset H a) = card H := card_image_eq_of_inj_on (lmul_inj_on a (ts H)) lemma fin_lcosets_card_eq {G : finset A} : ∀ gH, gH ∈ fin_lcosets H G → card gH = card H := take gH, assume Pcosets, obtain g Pg, from exists_of_mem_image Pcosets, and.right Pg ▸ fin_lcoset_card g variable [is_finsubgH : is_finsubg H] include is_finsubgH lemma fin_lcoset_same (x a : A) : x ∈ (fin_lcoset H a) = (fin_lcoset H x = fin_lcoset H a) := begin rewrite mem_eq_mem_to_set, rewrite [eq_eq_to_set_eq, *(fin_lcoset_eq x), fin_lcoset_eq a], exact (subg_lcoset_same x a) end lemma fin_mem_lcoset (g : A) : g ∈ fin_lcoset H g := have P : g ∈ g ∘> ts H, from and.left (subg_in_coset_refl g), assert P1 : g ∈ ts (fin_lcoset H g), from eq.symm (fin_lcoset_eq g) ▸ P, eq.symm (mem_eq_mem_to_set _ g) ▸ P1 lemma fin_lcoset_subset {S : finset A} (Psub : S ⊆ H) : ∀ x, x ∈ H → fin_lcoset S x ⊆ H := assert Psubs : set.subset (ts S) (ts H), from subset_eq_to_set_subset S H ▸ Psub, take x, assume Pxs : x ∈ ts H, assert Pcoset : set.subset (x ∘> ts S) (ts H), from subg_lcoset_subset_subg Psubs x Pxs, by rewrite [subset_eq_to_set_subset, fin_lcoset_eq x]; exact Pcoset lemma finsubg_lcoset_id {a : A} : a ∈ H → fin_lcoset H a = H := by rewrite [eq_eq_to_set_eq, fin_lcoset_eq, mem_eq_mem_to_set]; apply subgroup_lcoset_id lemma finsubg_inv_lcoset_eq_rcoset {a : A} : fin_inv (fin_lcoset H a) = fin_rcoset H a⁻¹ := begin esimp [fin_inv, fin_lcoset, fin_rcoset], rewrite [-image_compose], apply ext, intro b, rewrite [*mem_image_iff, ↑compose, ↑lmul_by, ↑rmul_by], apply iff.intro, intro Pl, cases Pl with h Ph, cases Ph with Pin Peq, existsi h⁻¹, apply and.intro, exact finsubg_has_inv H Pin, rewrite [-mul_inv, Peq], intro Pr, cases Pr with h Ph, cases Ph with Pin Peq, existsi h⁻¹, apply and.intro, exact finsubg_has_inv H Pin, rewrite [mul_inv, inv_inv, Peq], end lemma finsubg_conj_closed {g h : A} : g ∈ H → h ∈ H → g ∘c h ∈ H := assume Pgin Phin, finsubg_mul_closed H (finsubg_mul_closed H Pgin Phin) (finsubg_has_inv H Pgin) variable {G : finset A} variable [is_finsubgG : is_finsubg G] include is_finsubgG open finset.partition definition fin_lcoset_partition_subg (Psub : H ⊆ G) := partition.mk G (fin_lcoset H) fin_lcoset_same (restriction_imp_union (fin_lcoset H) fin_lcoset_same (fin_lcoset_subset Psub)) open nat theorem lagrange_theorem (Psub : H ⊆ G) : card G = card (fin_lcosets H G) * card H := calc card G = finset.Sum (fin_lcosets H G) card : class_equation (fin_lcoset_partition_subg Psub) ... = finset.Sum (fin_lcosets H G) (λ x, card H) : finset.Sum_ext (take g P, fin_lcosets_card_eq g P) ... = card (fin_lcosets H G) * card H : Sum_const_eq_card_mul end fin_lcoset section open fintype list subtype lemma dinj_tag {A : Type} (P : A → Prop) : dinj P tag := take a₁ a₂ Pa₁ Pa₂ Pteq, subtype.no_confusion Pteq (λ Pe Pqe, Pe) open nat lemma card_pos {A : Type} [ambientA : group A] [finA : fintype A] : 0 < card A := length_pos_of_mem (mem_univ 1) end section lcoset_fintype open fintype list subtype variables {A : Type} [group A] [fintype A] [decidable_eq A] variables G H : finset A definition is_fin_lcoset [reducible] (S : finset A) : Prop := ∃ g, g ∈ G ∧ fin_lcoset H g = S definition to_list : list A := list.filter (λ g, g ∈ G) (elems A) definition list_lcosets : list (finset A) := erase_dup (map (fin_lcoset H) (to_list G)) definition lcoset_type [reducible] : Type := {S : finset A | is_fin_lcoset G H S} definition all_lcosets : list (lcoset_type G H) := dmap (is_fin_lcoset G H) tag (list_lcosets G H) variables {G H} [finsubgG : is_finsubg G] include finsubgG lemma self_is_lcoset : is_fin_lcoset G H H := exists.intro 1 (and.intro !finsubg_has_one fin_lcoset_id) lemma lcoset_subset_of_subset (J : lcoset_type G H) : H ⊆ G → elt_of J ⊆ G := assume Psub, obtain j Pjin Pj, from has_property J, by rewrite [-Pj]; apply fin_lcoset_subset Psub; exact Pjin variables (G H) definition lcoset_one : lcoset_type G H := tag H self_is_lcoset variables {G H} definition lcoset_lmul {g : A} (Pgin : g ∈ G) (S : lcoset_type G H) : lcoset_type G H := tag (fin_lcoset (elt_of S) g) (obtain f Pfin Pf, from has_property S, exists.intro (g*f) (by apply and.intro; exact finsubg_mul_closed G Pgin Pfin; rewrite [-Pf, -fin_lcoset_compose])) definition lcoset_mul (S₁ S₂ : lcoset_type G H): finset A := Union (elt_of S₁) (fin_lcoset (elt_of S₂)) lemma mul_mem_lcoset_mul (J K : lcoset_type G H) {g h} : g ∈ elt_of J → h ∈ elt_of K → g*h ∈ lcoset_mul J K := assume Pg, begin rewrite [↑lcoset_mul, mem_Union_iff, ↑fin_lcoset], intro Ph, existsi g, apply and.intro, exact Pg, rewrite [mem_image_iff, ↑lmul_by], existsi h, exact and.intro Ph rfl end lemma is_lcoset_of_mem_list_lcosets {S : finset A} : S ∈ list_lcosets G H → is_fin_lcoset G H S := assume Pin, obtain g Pgin Pg, from exists_of_mem_map (mem_of_mem_erase_dup Pin), exists.intro g (and.intro (of_mem_filter Pgin) Pg) lemma mem_list_lcosets_of_is_lcoset {S : finset A} : is_fin_lcoset G H S → S ∈ list_lcosets G H := assume Plcoset, obtain g Pgin Pg, from Plcoset, Pg ▸ mem_erase_dup (mem_map _ (mem_filter_of_mem (complete g) Pgin)) lemma fin_lcosets_eq : fin_lcosets H G = to_finset_of_nodup (list_lcosets G H) !nodup_erase_dup := ext (take S, iff.intro (λ Pimg, mem_list_lcosets_of_is_lcoset (exists_of_mem_image Pimg)) (λ Pl, obtain g Pg, from is_lcoset_of_mem_list_lcosets Pl, iff.elim_right !mem_image_iff (is_lcoset_of_mem_list_lcosets Pl))) lemma length_all_lcosets : length (all_lcosets G H) = card (fin_lcosets H G) := eq.trans (show length (all_lcosets G H) = length (list_lcosets G H), from assert Pmap : map elt_of (all_lcosets G H) = list_lcosets G H, from map_dmap_of_inv_of_pos (λ S P, rfl) (λ S, is_lcoset_of_mem_list_lcosets), by rewrite[-Pmap, length_map]) (by rewrite fin_lcosets_eq) lemma lcoset_lmul_compose {f g : A} (Pf : f ∈ G) (Pg : g ∈ G) (S : lcoset_type G H) : lcoset_lmul Pf (lcoset_lmul Pg S) = lcoset_lmul (finsubg_mul_closed G Pf Pg) S := subtype.eq !fin_lcoset_compose lemma lcoset_lmul_one (S : lcoset_type G H) : lcoset_lmul !finsubg_has_one S = S := subtype.eq fin_lcoset_id lemma lcoset_lmul_inv {g : A} {Pg : g ∈ G} (S : lcoset_type G H) : lcoset_lmul (finsubg_has_inv G Pg) (lcoset_lmul Pg S) = S := subtype.eq (to_set.inj begin esimp [lcoset_lmul], rewrite [fin_lcoset_compose, mul.left_inv, fin_lcoset_eq, glcoset_id] end) lemma lcoset_lmul_inj {g : A} {Pg : g ∈ G}: @injective (lcoset_type G H) _ (lcoset_lmul Pg) := injective_of_has_left_inverse (exists.intro (lcoset_lmul (finsubg_has_inv G Pg)) lcoset_lmul_inv) lemma card_elt_of_lcoset_type (S : lcoset_type G H) : card (elt_of S) = card H := obtain f Pfin Pf, from has_property S, Pf ▸ fin_lcoset_card f definition lcoset_fintype [instance] : fintype (lcoset_type G H) := fintype.mk (all_lcosets G H) (dmap_nodup_of_dinj (dinj_tag (is_fin_lcoset G H)) !nodup_erase_dup) (take s, subtype.destruct s (take S, assume PS, mem_dmap PS (mem_list_lcosets_of_is_lcoset PS))) lemma card_lcoset_type : card (lcoset_type G H) = card (fin_lcosets H G) := length_all_lcosets open nat variable [finsubgH : is_finsubg H] include finsubgH theorem lagrange_theorem' (Psub : H ⊆ G) : card G = card (lcoset_type G H) * card H := calc card G = card (fin_lcosets H G) * card H : lagrange_theorem Psub ... = card (lcoset_type G H) * card H : card_lcoset_type lemma lcoset_disjoint {S₁ S₂ : lcoset_type G H} : S₁ ≠ S₂ → elt_of S₁ ∩ elt_of S₂ = ∅ := obtain f₁ Pfin₁ Pf₁, from has_property S₁, obtain f₂ Pfin₂ Pf₂, from has_property S₂, assume Pne, inter_eq_empty_of_disjoint (disjoint.intro take g, begin rewrite [-Pf₁, -Pf₂, *fin_lcoset_same], intro Pgf₁, rewrite [Pgf₁, Pf₁, Pf₂], intro Peq, exact absurd (subtype.eq Peq) Pne end ) lemma card_Union_lcosets (lcs : finset (lcoset_type G H)) : card (Union lcs elt_of) = card lcs * card H := calc card (Union lcs elt_of) = ∑ lc ∈ lcs, card (elt_of lc) : card_Union_of_disjoint lcs elt_of (λ (S₁ S₂ : lcoset_type G H) P₁ P₂ Pne, lcoset_disjoint Pne) ... = ∑ lc ∈ lcs, card H : Sum_ext (take lc P, card_elt_of_lcoset_type _) ... = card lcs * card H : Sum_const_eq_card_mul lemma exists_of_lcoset_type (J : lcoset_type G H) : ∃ j, j ∈ elt_of J ∧ fin_lcoset H j = elt_of J := obtain j Pjin Pj, from has_property J, exists.intro j (and.intro (Pj ▸ !fin_mem_lcoset) Pj) lemma lcoset_not_empty (J : lcoset_type G H) : elt_of J ≠ ∅ := obtain j Pjin Pj, from has_property J, assume Pempty, absurd (by rewrite [-Pempty, -Pj]; apply fin_mem_lcoset) (not_mem_empty j) end lcoset_fintype section normalizer open subtype variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G] include ambientG deceqG finG variable H : finset G definition normalizer : finset G := {g ∈ univ | ∀ h, h ∈ H → g ∘c h ∈ H} variable {H} variable [finsubgH : is_finsubg H] include finsubgH lemma subset_normalizer : H ⊆ normalizer H := subset_of_forall take g, assume PginH, mem_sep_of_mem !mem_univ (take h, assume PhinH, finsubg_conj_closed PginH PhinH) lemma normalizer_has_one : 1 ∈ normalizer H := mem_of_subset_of_mem subset_normalizer (finsubg_has_one H) lemma normalizer_mul_closed : finset_mul_closed_on (normalizer H) := take f g, assume Pfin Pgin, mem_sep_of_mem !mem_univ take h, assume Phin, begin rewrite [-conj_compose], apply of_mem_sep Pfin, apply of_mem_sep Pgin, exact Phin end lemma conj_eq_of_mem_normalizer {g : G} : g ∈ normalizer H → image (conj_by g) H = H := assume Pgin, eq_of_card_eq_of_subset (card_image_eq_of_inj_on (take h j, assume P1 P2, !conj_inj)) (subset_of_forall take h, assume Phin, obtain j Pjin Pj, from exists_of_mem_image Phin, begin substvars, apply of_mem_sep Pgin, exact Pjin end) lemma normalizer_has_inv : finset_has_inv (normalizer H) := take g, assume Pgin, mem_sep_of_mem !mem_univ take h, begin rewrite [-(conj_eq_of_mem_normalizer Pgin) at {1}, mem_image_iff], intro Pex, cases Pex with k Pk, rewrite [-(and.right Pk), conj_compose, mul.left_inv, conj_id], exact and.left Pk end definition normalizer_is_finsubg [instance] : is_finsubg (normalizer H) := is_finsubg.mk normalizer_has_one normalizer_mul_closed normalizer_has_inv lemma lcoset_subset_normalizer (J : lcoset_type (normalizer H) H) : elt_of J ⊆ normalizer H := lcoset_subset_of_subset J subset_normalizer lemma lcoset_subset_normalizer_of_mem {g : G} : g ∈ normalizer H → fin_lcoset H g ⊆ normalizer H := assume Pgin, fin_lcoset_subset subset_normalizer g Pgin lemma lrcoset_same_of_mem_normalizer {g : G} : g ∈ normalizer H → fin_lcoset H g = fin_rcoset H g := assume Pg, ext take h, iff.intro (assume Pl, obtain j Pjin Pj, from exists_of_mem_image Pl, mem_image (of_mem_sep Pg j Pjin) (calc g*j*g⁻¹*g = g*j : inv_mul_cancel_right ... = h : Pj)) (assume Pr, obtain j Pjin Pj, from exists_of_mem_image Pr, mem_image (of_mem_sep (finsubg_has_inv (normalizer H) Pg) j Pjin) (calc g*(g⁻¹*j*g⁻¹⁻¹) = g*(g⁻¹*j*g) : inv_inv ... = g*(g⁻¹*(j*g)) : mul.assoc ... = j*g : mul_inv_cancel_left ... = h : Pj)) lemma lcoset_mul_eq_lcoset (J K : lcoset_type (normalizer H) H) {g : G} : g ∈ elt_of J → (lcoset_mul J K) = fin_lcoset (elt_of K) g := assume Pgin, obtain j Pjin Pj, from has_property J, obtain k Pkin Pk, from has_property K, Union_const (lcoset_not_empty J) begin rewrite [-Pk], intro h Phin, assert Phinn : h ∈ normalizer H, apply mem_of_subset_of_mem (lcoset_subset_normalizer_of_mem Pjin), rewrite Pj, assumption, revert Phin Pgin, rewrite [-Pj, *fin_lcoset_same], intro Pheq Pgeq, rewrite [*(lrcoset_same_of_mem_normalizer Pkin), *fin_lrcoset_comm, Pheq, Pgeq] end lemma lcoset_mul_is_lcoset (J K : lcoset_type (normalizer H) H) : is_fin_lcoset (normalizer H) H (lcoset_mul J K) := obtain j Pjin Pj, from has_property J, obtain k Pkin Pk, from has_property K, exists.intro (j*k) (and.intro (finsubg_mul_closed _ Pjin Pkin) begin rewrite [lcoset_mul_eq_lcoset J K (Pj ▸ fin_mem_lcoset j), -fin_lcoset_compose, Pk] end) lemma lcoset_inv_is_lcoset (J : lcoset_type (normalizer H) H) : is_fin_lcoset (normalizer H) H (fin_inv (elt_of J)) := obtain j Pjin Pj, from has_property J, exists.intro j⁻¹ begin rewrite [-Pj, finsubg_inv_lcoset_eq_rcoset], apply and.intro, apply normalizer_has_inv, assumption, apply lrcoset_same_of_mem_normalizer, apply normalizer_has_inv, assumption end definition fin_coset_mul (J K : lcoset_type (normalizer H) H) : lcoset_type (normalizer H) H := tag (lcoset_mul J K) (lcoset_mul_is_lcoset J K) definition fin_coset_inv (J : lcoset_type (normalizer H) H) : lcoset_type (normalizer H) H := tag (fin_inv (elt_of J)) (lcoset_inv_is_lcoset J) definition fin_coset_one : lcoset_type (normalizer H) H := tag H self_is_lcoset local infix `^` := fin_coset_mul lemma fin_coset_mul_eq_lcoset (J K : lcoset_type (normalizer H) H) {g : G} : g ∈ (elt_of J) → elt_of (J ^ K) = fin_lcoset (elt_of K) g := assume Pgin, lcoset_mul_eq_lcoset J K Pgin lemma fin_coset_mul_assoc (J K L : lcoset_type (normalizer H) H) : J ^ K ^ L = J ^ (K ^ L) := obtain j Pjin Pj, from exists_of_lcoset_type J, obtain k Pkin Pk, from exists_of_lcoset_type K, assert Pjk : j*k ∈ elt_of (J ^ K), from mul_mem_lcoset_mul J K Pjin Pkin, obtain l Plin Pl, from has_property L, subtype.eq (begin rewrite [fin_coset_mul_eq_lcoset (J ^ K) _ Pjk, fin_coset_mul_eq_lcoset J _ Pjin, fin_coset_mul_eq_lcoset K _ Pkin, -Pl, *fin_lcoset_compose] end) lemma fin_coset_mul_one (J : lcoset_type (normalizer H) H) : J ^ fin_coset_one = J := obtain j Pjin Pj, from exists_of_lcoset_type J, subtype.eq begin rewrite [↑fin_coset_one, fin_coset_mul_eq_lcoset _ _ Pjin, -Pj] end lemma fin_coset_one_mul (J : lcoset_type (normalizer H) H) : fin_coset_one ^ J = J := subtype.eq begin rewrite [↑fin_coset_one, fin_coset_mul_eq_lcoset _ _ (finsubg_has_one H), fin_lcoset_id] end lemma fin_coset_left_inv (J : lcoset_type (normalizer H) H) : (fin_coset_inv J) ^ J = fin_coset_one := obtain j Pjin Pj, from exists_of_lcoset_type J, assert Pjinv : j⁻¹ ∈ elt_of (fin_coset_inv J), from inv_mem_fin_inv Pjin, subtype.eq begin rewrite [↑fin_coset_one, fin_coset_mul_eq_lcoset _ _ Pjinv, -Pj, fin_lcoset_inv] end variable (H) definition fin_coset_group [instance] : group (lcoset_type (normalizer H) H) := group.mk fin_coset_mul fin_coset_mul_assoc fin_coset_one fin_coset_one_mul fin_coset_mul_one fin_coset_inv fin_coset_left_inv variables {H} (Hc : finset (lcoset_type (normalizer H) H)) definition fin_coset_Union : finset G := Union Hc elt_of variables {Hc} [finsubgHc : is_finsubg Hc] include finsubgHc lemma mem_normalizer_of_mem_fcU {j : G} : j ∈ fin_coset_Union Hc → j ∈ normalizer H := assume Pjin, obtain J PJ PjJ, from iff.elim_left !mem_Union_iff Pjin, mem_of_subset_of_mem !lcoset_subset_normalizer PjJ lemma fcU_has_one : (1:G) ∈ fin_coset_Union Hc := iff.elim_right (mem_Union_iff Hc elt_of (1:G)) (exists.intro 1 (and.intro (finsubg_has_one Hc) (finsubg_has_one H))) lemma fcU_has_inv : finset_has_inv (fin_coset_Union Hc) := take j, assume Pjin, obtain J PJ PjJ, from iff.elim_left !mem_Union_iff Pjin, have PJinv : J⁻¹ ∈ Hc, from finsubg_has_inv Hc PJ, have Pjinv : j⁻¹ ∈ elt_of J⁻¹, from inv_mem_fin_inv PjJ, iff.elim_right !mem_Union_iff (exists.intro J⁻¹ (and.intro PJinv Pjinv)) lemma fcU_mul_closed : finset_mul_closed_on (fin_coset_Union Hc) := take j k, assume Pjin Pkin, obtain J PJ PjJ, from iff.elim_left !mem_Union_iff Pjin, obtain K PK PkK, from iff.elim_left !mem_Union_iff Pkin, assert Pjk : j*k ∈ elt_of (J*K), from mul_mem_lcoset_mul J K PjJ PkK, iff.elim_right !mem_Union_iff (exists.intro (J*K) (and.intro (finsubg_mul_closed Hc PJ PK) Pjk)) definition fcU_is_finsubg [instance] : is_finsubg (fin_coset_Union Hc) := is_finsubg.mk fcU_has_one fcU_mul_closed fcU_has_inv end normalizer end group_theory
51b8fa566b01a18f53281919cc95958cfb7d0f56
abbfc359cee49d3c5258b2bbedc2b4d306ec3bdf
/src/data/serial/instances.lean
9f062a4cc13674b6ae023f86229a94710c9bd9f4
[]
no_license
cipher1024/serialean
565b17241ba7edc4ee564bf0ae175dd15b06a28c
47881e4a6bc0a62cd68520564610b75f8a4fef2c
refs/heads/master
1,585,117,575,599
1,535,783,976,000
1,535,783,976,000
143,501,396
0
0
null
null
null
null
UTF-8
Lean
false
false
4,515
lean
import data.serial.basic universes u v open ulift variables {α : Type u} {β : Type v} def prod.mk' : ulift.{v} α → ulift.{u} β → (α × β) | ⟨ x ⟩ ⟨ y ⟩ := (x,y) open serializer serial instance : serial2 prod.{u v} := of_serializer₂ (λ α β, by introsI; exact prod.mk' <$> ser_field' prod.fst <*> ser_field'.{v u} prod.snd) begin intros, apply there_and_back_again_seq, apply there_and_back_again_map, cases w, refl end def sum.inl' : ulift.{v} α → (α ⊕ β) | ⟨ x ⟩ := sum.inl x def sum.inr' : ulift.{u} β → (α ⊕ β) | ⟨ x ⟩ := sum.inr x def sum.encode [serial.{u} α] [serial.{v} β] : α ⊕ β → put_m.{max u v} | (sum.inl x) := write_word 1 >> encode (up.{v} x) | (sum.inr x) := write_word 2 >> encode (up.{u} x) def sum.decode [serial.{u} α] [serial.{v} β] : get_m (α ⊕ β) := select_tag [ (1,sum.inl' <$> decode _), (2,sum.inr' <$> decode _) ] instance {α β} [serial.{u} α] [serial.{v} β] : serial (α ⊕ β) := { encode := sum.encode, decode := sum.decode, correctness := by { rintro ⟨w⟩; simp [sum.encode,sum.decode,map_read_write,*], refl, rw read_write_tag_miss, simp [map_read_write], refl, intro h, cases h, } } def word_sz : ℕ := unsigned_sz / 2 def nat.encode : ℕ → put_m | n := let r := n / word_sz, w := n % word_sz in have h : 2 * w + 1 < unsigned_sz, by { apply @lt_of_lt_of_le _ _ _ (2 * (w + 1)), simp [mul_add], norm_num, transitivity 2 * word_sz, { apply mul_le_mul, refl, { apply nat.succ_le_of_lt, apply nat.mod_lt, norm_num [word_sz,unsigned_sz,nat.succ_eq_add_one] }, apply nat.zero_le, apply nat.zero_le, }, { rw mul_comm, apply nat.div_mul_le_self } }, if Hr : 1 ≤ r then have h : 2 * w < unsigned_sz, by { transitivity; [skip, assumption], apply nat.lt_succ_self } , have h'' : word_sz > 0, by norm_num [word_sz,unsigned_sz,nat.succ_eq_add_one], have h' : r < n, by { apply nat.div_lt_self, rw [nat.le_div_iff_mul_le,one_mul] at Hr, apply lt_of_lt_of_le h'' Hr, assumption, norm_num [word_sz,unsigned_sz,nat.succ_eq_add_one] }, do write_word ⟨2 * w, h⟩, nat.encode r else write_word ⟨2 * w + 1, h⟩ def nat.decode_aux (coef : ℕ × ℕ) (w : unsigned) : get_m (ℕ ⊕ (ℕ × ℕ)) := let b := w.val % 2, w' := w.val / 2, c := coef.1, coef' := (c * word_sz, c * w' + coef.2) in if b = 0 then pure (sum.inr coef') else pure (sum.inl coef'.2) def nat.decode : get_m ℕ := get_m.loop nat.decode_aux pure (1,0) instance : serial ℕ := { encode := nat.encode, decode := nat.decode, correctness := begin intro, dsimp [nat.decode], suffices : get_m.loop nat.decode_aux pure (1, 0) -<< nat.encode w = pure (1 * w + 0), { simp * }, generalize : 0 = k, generalize : 1 = x, induction w using nat.strong_induction_on generalizing x k, rw [nat.encode], dsimp, split_ifs, { simp [nat.decode_aux], rw w_a, simp, congr, rw [nat.mul_div_right,mul_assoc,← nat.left_distrib x,add_comm,nat.mod_add_div], norm_num, apply nat.div_lt_self, { by_contradiction, revert h, apply not_lt_of_le, replace a := le_antisymm (le_of_not_lt a) (nat.zero_le _), subst w_n, norm_num [word_sz], }, norm_num [word_sz,unsigned_sz,nat.succ_eq_add_one], }, { simp [nat.decode_aux], rw if_neg, simp, simp [pure,read_write], congr, rw nat.add_mul_div_left, norm_num, replace h := le_antisymm (le_of_not_lt h) (nat.zero_le _), have := nat.mod_add_div w_n word_sz, simp [h] at this, exact this, { norm_num }, { norm_num } } end } def list.encode {α : Type u} [serial α] (xs : list α) : put_m.{u} := encode (up.{u} xs.length) >> xs.mmap encode >> pure punit.star def list.decode {α : Type u} [serial α] : get_m.{u} (list α) := do n ← decode _, (list.iota $ down.{u} n).mmap $ λ _, decode α instance : serial1 list.{u} := { encode := @list.encode, decode := @list.decode, correctness := begin introsI, simp [list.encode,list.decode,seq_left_eq,(>>)], simp [bind_assoc,encode_decode_bind], induction w, { simp [nat.add_one,list.iota,mmap], refl }, { simp [nat.add_one,list.iota,mmap,encode_decode_bind] with functor_norm, rw read_write_mono_left w_ih, refl, } end } instance {p : Prop} [decidable p] : serial (plift p) := { encode := λ w, pure punit.star, decode := if h : p then pure ⟨ h ⟩ else get_m.fail, correctness := by { rintros ⟨ h ⟩, rw dif_pos h, refl } }
6b874e72d181a82db955ff9c835023b106f5e849
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/measure_theory/decomposition.lean
f5cbd94e7eb155d362748dfbdffd25e85f671609
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
8,719
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Hahn decomposition theorem TODO: * introduce finite measures (into nnreal) * show general for signed measures (into ℝ) -/ import measure_theory.measure_space local attribute [instance, priority 0] classical.prop_decidable namespace measure_theory open set lattice filter variables {α : Type*} [measurable_space α] {μ ν : measure α} -- suddenly this is necessary?! private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) : γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d := by linarith lemma hahn_decomposition (hμ : μ univ < ⊤) (hν : ν univ < ⊤) : ∃s, is_measurable s ∧ (∀t, is_measurable t → t ⊆ s → ν t ≤ μ t) ∧ (∀t, is_measurable t → t ⊆ - s → μ t ≤ ν t) := begin let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal, let c : set ℝ := d '' {s | is_measurable s }, let γ : ℝ := Sup c, have hμ : ∀s, μ s < ⊤ := assume s, lt_of_le_of_lt (measure_mono $ subset_univ _) hμ, have hν : ∀s, ν s < ⊤ := assume s, lt_of_le_of_lt (measure_mono $ subset_univ _) hν, have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ennreal) = μ s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hμ _), have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ennreal) = ν s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hν _), have d_empty : d ∅ = 0, { simp [d], rw [measure_empty, measure_empty], simp }, have d_split : ∀s t, is_measurable s → is_measurable t → d s = d (s \ t) + d (s ∩ t), { assume s t hs ht, simp only [d], rw [measure_eq_inter_diff hs ht, measure_eq_inter_diff hs ht, ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _), nnreal.coe_add, nnreal.coe_add], simp only [sub_eq_add_neg, neg_add], ac_refl }, have d_Union : ∀(s : ℕ → set α), (∀n, is_measurable (s n)) → monotone s → tendsto (λn, d (s n)) at_top (nhds (d (⋃n, s n))), { assume s hs hm, refine tendsto_sub _ _; refine (nnreal.tendsto_coe.2 $ (tendsto_measure_Union hs hm).comp $ ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ⊤ _), exact hμ _, exact hν _ }, have d_Inter : ∀(s : ℕ → set α), (∀n, is_measurable (s n)) → (∀n m, n ≤ m → s m ⊆ s n) → tendsto (λn, d (s n)) at_top (nhds (d (⋂n, s n))), { assume s hs hm, refine tendsto_sub _ _; refine (nnreal.tendsto_coe.2 $ (tendsto_measure_Inter hs hm _).comp $ ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ⊤ _), exact ⟨0, hμ _⟩, exact hμ _, exact ⟨0, hν _⟩, exact hν _ }, have bdd_c : bdd_above c, { use (μ univ).to_nnreal, rintros r ⟨s, hs, rfl⟩, refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _, rw [← nnreal.coe_le, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ], exact measure_mono (subset_univ _) }, have c_nonempty : c ≠ ∅ := ne_empty_of_mem (mem_image_of_mem _ is_measurable.empty), have d_le_γ : ∀s, is_measurable s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩, have : ∀n:ℕ, ∃s : set α, is_measurable s ∧ γ - (1/2)^n < d s, { assume n, have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n), rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩, exact ⟨s, hs, hlt⟩ }, rcases classical.axiom_of_choice this with ⟨e, he⟩, change ℕ → set α at e, have he₁ : ∀n, is_measurable (e n) := assume n, (he n).1, have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2, let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e, have hf : ∀n m, is_measurable (f n m), { assume n m, simp only [f, finset.inf_eq_infi], exact is_measurable.bInter (countable_encodable _) (assume i _, he₁ _) }, have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c, { assume a b c d hab hcd, dsimp only [f], rw [finset.inf_eq_infi, finset.inf_eq_infi], refine bInter_subset_bInter_left _, simp, rintros j ⟨hbj, hjc⟩, exact ⟨le_trans hab hbj, lt_of_lt_of_le hjc $ add_le_add_right hcd 1⟩ }, have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1), { assume n m hnm, have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm), simp only [f], rw [finset.Ico.succ_top this, finset.inf_insert, set.inter_comm], refl }, have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n), { assume n m h, refine nat.le_induction _ _ n h, { have := he₂ m, simp only [f], rw [finset.Ico.succ_singleton, finset.inf_singleton], exact aux this }, { assume n (hmn : m ≤ n) ih, have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)), { calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤ γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) : begin refine add_le_add_left (add_le_add_left _ _) γ, simp only [pow_add, pow_one, le_sub_iff_add_le], linarith end ... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) : by simp only [sub_eq_add_neg]; ac_refl ... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih ... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) : by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc] ... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) : begin rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)), union_diff_left, union_inter_cancel_left], ac_refl, exact (he₁ _).union (hf _ _), exact (he₁ _) end ... ≤ γ + d (f m (n + 1)) : add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ }, exact (add_le_add_iff_left γ).1 this } }, let s := ⋃ m, ⋂n, f m n, have γ_le_d_s : γ ≤ d s, { have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (nhds γ), { suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (nhds (γ - 2 * 0)), { simpa }, exact (tendsto_sub tendsto_const_nhds $ tendsto_mul tendsto_const_nhds $ tendsto_pow_at_top_nhds_0_of_lt_1 (le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) }, have hd : tendsto (λm, d (⋂n, f m n)) at_top (nhds (d (⋃ m, ⋂ n, f m n))), { refine d_Union _ _ _, { assume n, exact is_measurable.Inter (assume m, hf _ _) }, { exact assume n m hnm, subset_Inter (assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } }, refine le_of_tendsto_of_tendsto (@at_top_ne_bot ℕ _ _) hγ hd (univ_mem_sets' $ assume m, _), change γ - 2 * (1 / 2) ^ m ≤ d (⋂ (n : ℕ), f m n), have : tendsto (λn, d (f m n)) at_top (nhds (d (⋂ n, f m n))), { refine d_Inter _ _ _, { assume n, exact hf _ _ }, { assume n m hnm, exact f_subset_f (le_refl _) hnm } }, refine ge_of_tendsto (@at_top_ne_bot ℕ _ _) this (mem_at_top_sets.2 ⟨m, assume n hmn, _⟩), change γ - 2 * (1 / 2) ^ m ≤ d (f m n), refine le_trans _ (le_d_f _ _ hmn), exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) }, have hs : is_measurable s := is_measurable.Union (assume n, is_measurable.Inter (assume m, hf _ _)), refine ⟨s, hs, _, _⟩, { assume t ht hts, have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $ calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s ... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts] ... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, nnreal.coe_le], simpa only [d, le_sub_iff_add_le, zero_add] using this }, { assume t ht hts, have : d t ≤ 0, exact ((add_le_add_iff_left γ).1 $ calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _) ... = d (s ∪ t) : begin rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right, diff_eq_self.2], exact assume a ⟨hat, has⟩, hts hat has end ... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, nnreal.coe_le], simpa only [d, sub_le_iff_le_add, zero_add] using this } end end measure_theory
27696955228f204d8a80826e05ba41574e4659d7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/lint/frontend.lean
0611d0e1648b4ed684f2589e20b8c9a614841da8
[ "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
16,286
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, Robert Y. Lewis, Gabriel Ebner -/ import meta.rb_map import tactic.lint.basic /-! # Linter frontend and commands This file defines the linter commands which spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) For a list of default / non-default linters, see the "Linting Commands" user command doc entry. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output if all checks pass. A silent lint will fail if any test fails. You can append a `+` to any command (e.g. `#lint_mathlib+`) to run a verbose lint that reports the result of each linter, including the successes. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ open tactic expr native setup_tactic_parser /-- Verbosity for the linter output. * `low`: only print failing checks, print nothing on success. * `medium`: only print failing checks, print confirmation on success. * `high`: print output of every check. -/ @[derive [decidable_eq, inhabited]] inductive lint_verbosity | low | medium | high /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ meta def get_checks (slow : bool) (extra : list name) (use_only : bool) : tactic (list (name × linter)) := do default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters, let default := if slow then default else default.filter (λ l, l.2.is_fast), list.append default <$> get_linters extra /-- `lint_core all_decls non_auto_decls checks` applies the linters `checks` to the list of declarations. If `auto_decls` is false for a linter (default) the linter is applied to `non_auto_decls`. If `auto_decls` is true, then it is applied to `all_decls`. The resulting list has one element for each linter, containing the linter as well as a map from declaration name to warning. -/ meta def lint_core (all_decls non_auto_decls : list declaration) (checks : list (name × linter)) : tactic (list (name × linter × rb_map name string)) := do checks.mmap $ λ ⟨linter_name, linter⟩, do let test_decls := if linter.auto_decls then all_decls else non_auto_decls, test_decls ← test_decls.mfilter (λ decl, should_be_linted linter_name decl.to_name), s ← read, let results := test_decls.map_async_chunked $ λ decl, prod.mk decl.to_name $ match linter.test decl s with | result.success w _ := w | result.exception msg _ _ := some $ "LINTER FAILED:\n" ++ msg.elim "(no message)" (λ msg, to_string $ msg ()) end, let results := results.foldl (λ (results : rb_map name string) warning, match warning with | (decl_name, some w) := results.insert decl_name w | (_, none) := results end) mk_rb_map, pure (linter_name, linter, results) /-- Sorts a map with declaration keys as names by line number. -/ meta def sort_results {α} (e : environment) (results : rb_map name α) : list (name × α) := list.reverse $ rb_lmap.values $ rb_lmap.of_list $ results.fold [] $ λ decl linter_warning results, (((e.decl_pos decl).get_or_else ⟨0,0⟩).line, (decl, linter_warning)) :: results /-- Formats a linter warning as `#check` command with comment. -/ meta def print_warning (decl_name : name) (warning : string) : format := "#check @" ++ to_fmt decl_name ++ " /- " ++ warning ++ " -/" private def workflow_command_replacements : char → string | '%' := "%25" | '\n' := "%0A" | c := to_string c /-- Escape characters that may not be used in a workflow commands, following https://github.com/actions/toolkit/blob/7257597d731b34d14090db516d9ea53439300e98/packages/core/src/command.ts#L92-L105 -/ def escape_workflow_command (s : string) : string := "".intercalate $ s.to_list.map workflow_command_replacements /-- Prints a workflow command to emit an error understood by github in an actions workflow. This enables CI to tag the parts of the file where linting failed with annotations, and makes it easier for mathlib contributors to see what needs fixing. See https://docs.github.com/en/actions/learn-github-actions/workflow-commands-for-github-actions#setting-an-error-message -/ meta def print_workflow_command (env : environment) (linter_name decl_name : name) (warning : string) : option string := do po ← env.decl_pos decl_name, ol ← env.decl_olean decl_name, return $ sformat!"\n::error file={ol},line={po.line},col={po.column},title=" ++ sformat!"Warning from {linter_name} linter::" ++ sformat!"{escape_workflow_command $ to_string decl_name} - {escape_workflow_command warning}" /-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/ meta def print_warnings (env : environment) (emit_workflow_commands : bool) (linter_name : name) (results : rb_map name string) : format := format.intercalate format.line $ (sort_results env results).map $ λ ⟨decl_name, warning⟩, let form := print_warning decl_name warning in if emit_workflow_commands then form ++ (print_workflow_command env linter_name decl_name warning).get_or_else "" else form /-- Formats a map of linter warnings grouped by filename with `-- filename` comments. The first `drop_fn_chars` characters are stripped from the filename. -/ meta def grouped_by_filename (e : environment) (results : rb_map name string) (drop_fn_chars := 0) (formatter: rb_map name string → format) : format := let results := results.fold (rb_map.mk string (rb_map name string)) $ λ decl_name linter_warning results, let fn := (e.decl_olean decl_name).get_or_else "" in results.insert fn (((results.find fn).get_or_else mk_rb_map).insert decl_name linter_warning) in let l := results.to_list.reverse.map (λ ⟨fn, results⟩, ("-- " ++ fn.popn drop_fn_chars ++ "\n" ++ formatter results : format)) in format.intercalate "\n\n" l ++ "\n" /-- Formats the linter results as Lean code with comments and `#check` commands. -/ meta def format_linter_results (env : environment) (results : list (name × linter × rb_map name string)) (decls non_auto_decls : list declaration) (group_by_filename : option ℕ) (where_desc : string) (slow : bool) (verbose : lint_verbosity) (num_linters : ℕ) -- whether to include codes understood by github to create file annotations (emit_workflow_commands : bool := ff) : format := do let formatted_results := results.map $ λ ⟨linter_name, linter, results⟩, let report_str : format := to_fmt "/- The `" ++ to_fmt linter_name ++ "` linter reports: -/\n" in if ¬ results.empty then let warnings := match group_by_filename with | none := print_warnings env emit_workflow_commands linter_name results | some dropped := grouped_by_filename env results dropped (print_warnings env emit_workflow_commands linter_name) end in report_str ++ "/- " ++ linter.errors_found ++ " -/\n" ++ warnings ++ "\n" else if verbose = lint_verbosity.high then "/- OK: " ++ linter.no_errors_found ++ " -/" else format.nil, let s := format.intercalate "\n" (formatted_results.filter (λ f, ¬ f.is_nil)), let s := if verbose = lint_verbosity.low then s else format!("/- Checking {non_auto_decls.length} declarations (plus " ++ "{decls.length - non_auto_decls.length} automatically generated ones) {where_desc} " ++ "with {num_linters} linters -/\n\n") ++ s, let s := if slow then s else s ++ "/- (slow tests skipped) -/\n", s /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `group_by_filename` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. Returns a `name_set` containing the names of all declarations that fail any check in `check`, and a `format` object describing the failures. -/ meta def lint_aux (decls : list declaration) (group_by_filename : option ℕ) (where_desc : string) (slow : bool) (verbose : lint_verbosity) (checks : list (name × linter)) : tactic (name_set × format) := do e ← get_env, let non_auto_decls := decls.filter (λ d, ¬ d.is_auto_or_internal e), results ← lint_core decls non_auto_decls checks, let s := format_linter_results e results decls non_auto_decls group_by_filename where_desc slow verbose checks.length, let ns := name_set.of_list (do (_,_,rs) ← results, rs.keys), pure (ns, s) /-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/ meta def lint (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.filter (λ d, e.in_current_file d.to_name), lint_aux l none "in the current file" slow verbose checks /-- Returns the declarations in the folder `proj_folder`. -/ meta def lint_project_decls (proj_folder : string) : tactic (list declaration) := do e ← get_env, pure $ e.filter $ λ d, e.is_prefix_of_file proj_folder d.to_name /-- Returns the linter message by running the linter on all declarations in project `proj_name` in folder `proj_folder`. It also returns a `name_set` containing all declarations that fail. To add a linter command for your own project, write ``` open lean.parser lean tactic interactive @[user_command] meta def lint_my_project_cmd (_ : parse $ tk "#lint_my_project") : parser unit := do str ← get_project_dir n k, lint_cmd_aux (@lint_project str "my project") ``` Here `n` is the name of any declaration in the project (like `` `lint_my_project_cmd`` and `k` is the number of characters in the filename of `n` *after* the `src/` directory (so e.g. the number of characters in `tactic/lint/frontend.lean`). Warning: the linter will not work in the file where `n` is declared. -/ meta def lint_project (proj_folder proj_name : string) (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, decls ← lint_project_decls proj_folder, lint_aux decls proj_folder.length ("in " ++ proj_name ++ " (only in imported files)") slow verbose checks /-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/ meta def lint_all (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.get_decls, lint_aux l (some 0) "in all imported files (including this one)" slow verbose checks /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ meta def parse_lint_additions : parser (bool × list name) := prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident*) /-- Parses a "-" or "+", returning `lint_verbosity.low` or `lint_verbosity.high` respectively, or returns `none`. -/ meta def parse_verbosity : parser (option lint_verbosity) := tk "-" >> return lint_verbosity.low <|> tk "+" >> return lint_verbosity.high <|> return none /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ meta def lint_cmd_aux (scope : bool → lint_verbosity → list name → bool → tactic (name_set × format)) : parser unit := do verbosity ← parse_verbosity, fast_only ← optional (tk "*"), -- allow either order of *- verbosity ← if verbosity.is_some then return verbosity else parse_verbosity, let verbosity := verbosity.get_or_else lint_verbosity.medium, (use_only, extra) ← parse_lint_additions, (failed, s) ← scope fast_only.is_none verbosity extra use_only, when (¬ s.is_nil) $ trace s, when (verbosity = lint_verbosity.low ∧ ¬ failed.empty) $ fail "Linting did not succeed", when (verbosity = lint_verbosity.medium ∧ failed.empty) $ trace "/- All linting checks passed! -/" /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output if all checks pass. `#lint+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit := lint_cmd_aux @lint /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output if all checks pass. `lint_mathlib+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit := do str ← get_mathlib_dir, lint_cmd_aux (@lint_project str "mathlib") /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output if all checks pass. `lint_all+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit := lint_cmd_aux @lint_all /-- The command `#list_linters` prints a list of all available linters. -/ @[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit := do env ← get_env, let ns := env.decl_filter_map $ λ dcl, if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none, trace "Available linters:\n linters marked with (*) are in the default lint set\n", ns.mmap' $ λ n, do b ← has_attribute' `linter n, trace $ n.pop_prefix.to_string ++ if b then " (*)" else "" /-- Invoking the hole command `lint` ("Find common mistakes in current file") will print text that indicates mistakes made in the file above the command. It is equivalent to copying and pasting the output of `#lint`. On large files, it may take some time before the output appears. -/ @[hole_command] meta def lint_hole_cmd : hole_command := { name := "Lint", descr := "Lint: Find common mistakes in current file.", action := λ es, do (_, s) ← lint, return [(s.to_string,"")] } add_tactic_doc { name := "Lint", category := doc_category.hole_cmd, decl_names := [`lint_hole_cmd], tags := ["linting"] }
1042e290d1dd2079aa2ec5aee57e99b48c9f0ab3
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/LeftShelf.lean
3fb9b4787f37038380bf9f40df17829f9a4889b3
[]
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
5,894
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 LeftShelf structure LeftShelf (A : Type) : Type := (linv : (A → (A → A))) (leftDistributive : (∀ {x y z : A} , (linv x (linv y z)) = (linv (linv x y) (linv x z)))) open LeftShelf structure Sig (AS : Type) : Type := (linvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftDistributiveP : (∀ {xP yP zP : (Prod A A)} , (linvP xP (linvP yP zP)) = (linvP (linvP xP yP) (linvP xP zP)))) structure Hom {A1 : Type} {A2 : Type} (Le1 : (LeftShelf A1)) (Le2 : (LeftShelf A2)) : Type := (hom : (A1 → A2)) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Le1) x1 x2)) = ((linv Le2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Le1 : (LeftShelf A1)) (Le2 : (LeftShelf A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Le1) x1 x2) ((linv Le2) y1 y2)))))) inductive LeftShelfTerm : Type | linvL : (LeftShelfTerm → (LeftShelfTerm → LeftShelfTerm)) open LeftShelfTerm inductive ClLeftShelfTerm (A : Type) : Type | sing : (A → ClLeftShelfTerm) | linvCl : (ClLeftShelfTerm → (ClLeftShelfTerm → ClLeftShelfTerm)) open ClLeftShelfTerm inductive OpLeftShelfTerm (n : ℕ) : Type | v : ((fin n) → OpLeftShelfTerm) | linvOL : (OpLeftShelfTerm → (OpLeftShelfTerm → OpLeftShelfTerm)) open OpLeftShelfTerm inductive OpLeftShelfTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpLeftShelfTerm2) | sing2 : (A → OpLeftShelfTerm2) | linvOL2 : (OpLeftShelfTerm2 → (OpLeftShelfTerm2 → OpLeftShelfTerm2)) open OpLeftShelfTerm2 def simplifyCl {A : Type} : ((ClLeftShelfTerm A) → (ClLeftShelfTerm A)) | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpLeftShelfTerm n) → (OpLeftShelfTerm n)) | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpLeftShelfTerm2 n A) → (OpLeftShelfTerm2 n A)) | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((LeftShelf A) → (LeftShelfTerm → A)) | Le (linvL x1 x2) := ((linv Le) (evalB Le x1) (evalB Le x2)) def evalCl {A : Type} : ((LeftShelf A) → ((ClLeftShelfTerm A) → A)) | Le (sing x1) := x1 | Le (linvCl x1 x2) := ((linv Le) (evalCl Le x1) (evalCl Le x2)) def evalOpB {A : Type} {n : ℕ} : ((LeftShelf A) → ((vector A n) → ((OpLeftShelfTerm n) → A))) | Le vars (v x1) := (nth vars x1) | Le vars (linvOL x1 x2) := ((linv Le) (evalOpB Le vars x1) (evalOpB Le vars x2)) def evalOp {A : Type} {n : ℕ} : ((LeftShelf A) → ((vector A n) → ((OpLeftShelfTerm2 n A) → A))) | Le vars (v2 x1) := (nth vars x1) | Le vars (sing2 x1) := x1 | Le vars (linvOL2 x1 x2) := ((linv Le) (evalOp Le vars x1) (evalOp Le vars x2)) def inductionB {P : (LeftShelfTerm → Type)} : ((∀ (x1 x2 : LeftShelfTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → (∀ (x : LeftShelfTerm) , (P x))) | plinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl x1) (inductionB plinvl x2)) def inductionCl {A : Type} {P : ((ClLeftShelfTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClLeftShelfTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → (∀ (x : (ClLeftShelfTerm A)) , (P x)))) | psing plinvcl (sing x1) := (psing x1) | psing plinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl x1) (inductionCl psing plinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpLeftShelfTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpLeftShelfTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → (∀ (x : (OpLeftShelfTerm n)) , (P x)))) | pv plinvol (v x1) := (pv x1) | pv plinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol x1) (inductionOpB pv plinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpLeftShelfTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpLeftShelfTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → (∀ (x : (OpLeftShelfTerm2 n A)) , (P x))))) | pv2 psing2 plinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 plinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 plinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 x1) (inductionOp pv2 psing2 plinvol2 x2)) def stageB : (LeftShelfTerm → (Staged LeftShelfTerm)) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClLeftShelfTerm A) → (Staged (ClLeftShelfTerm A))) | (sing x1) := (Now (sing x1)) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpLeftShelfTerm n) → (Staged (OpLeftShelfTerm n))) | (v x1) := (const (code (v x1))) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpLeftShelfTerm2 n A) → (Staged (OpLeftShelfTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (linvT : ((Repr A) → ((Repr A) → (Repr A)))) end LeftShelf
97910c671d22e80313b06199b4397155e113723d
fe84e287c662151bb313504482b218a503b972f3
/src/algebra/biadditive.lean
167454b08d9c49972e6116d0551f5ef67492cfe7
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
2,739
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This file defines a typeclass for biadditive maps, i.e. maps `m : α → β → γ` (where α, β and γ are commutative additive monoids) such that `m a b` is an additive function of `a` and also an additive function of `b`. In other words, `m` should be bilinear over `ℕ`. -/ import algebra.group algebra.big_operators algebra.module variables {ι : Type*} {α : Type*} {β : Type*} {γ : Type*} variables [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] class is_biadditive (m : α → β → γ) : Prop := (zero_mul' : ∀ b, m 0 b = 0) (add_mul' : ∀ a₁ a₂ b, m (a₁ + a₂) b = m a₁ b + m a₂ b) (mul_zero' : ∀ a, m a 0 = 0) (mul_add' : ∀ a b₁ b₂, m a (b₁ + b₂) = m a b₁ + m a b₂) namespace is_biadditive variables (m : α → β → γ) [is_biadditive m] def zero_mul (b : β) : m 0 b = 0 := @is_biadditive.zero_mul' α β γ _ _ _ m _ b def mul_zero (a : α) : m a 0 = 0 := @is_biadditive.mul_zero' α β γ _ _ _ m _ a def add_mul (a₁ a₂ : α) (b : β) : m (a₁ + a₂) b = m a₁ b + m a₂ b := @is_biadditive.add_mul' α β γ _ _ _ m _ a₁ a₂ b def mul_add (a : α) (b₁ b₂ : β) : m a (b₁ + b₂) = m a b₁ + m a b₂ := @is_biadditive.mul_add' α β γ _ _ _ m _ a b₁ b₂ def hom_right (a : α) : β →+ γ := { to_fun := m a, map_zero' := is_biadditive.mul_zero' a, map_add' := is_biadditive.mul_add' a } def hom_left (b : β) : α →+ γ := { to_fun := λ a, m a b, map_zero' := is_biadditive.zero_mul' b, map_add' := λ a₁ a₂, is_biadditive.add_mul' a₁ a₂ b } lemma sum_mul (s : finset ι) (a : ι → α) (b : β) : m (s.sum a) b = s.sum (λ x, m (a x) b) := (hom_left m b).map_sum a s lemma mul_sum (s : finset ι) (a : α) (b : ι → β) : m a (s.sum b) = s.sum (λ x, m a (b x)) := (hom_right m a).map_sum b s end is_biadditive namespace semiring variables (R : Type*) [semiring R] instance : is_biadditive ((*) : R → R → R) := { zero_mul' := λ b, by {rw[_root_.zero_mul]}, mul_zero' := λ b, by {rw[_root_.mul_zero]}, add_mul' := λ a₁ a₂ b, by {rw[_root_.add_mul]}, mul_add' := λ a b₁ b₂, by {rw[_root_.mul_add]}, } end semiring namespace semimodule variables (R : Type*) [semiring R] variables (M : Type*) [add_comm_monoid M] [module R M] instance : is_biadditive ((•) : R → M → M) := { zero_mul' := λ b, by {rw[_root_.zero_smul]}, mul_zero' := λ b, by {rw[_root_.smul_zero]}, add_mul' := λ a₁ a₂ b, by {rw[_root_.add_smul]}, mul_add' := λ a b₁ b₂, by {rw[_root_.smul_add]}, } end semimodule
d36e9ef16a848f450032d4eb1be5334d2383b7c2
a25cc44b447f2fbde61e4b848318762eb892f2bf
/src/fin_extra.lean
85b32e9eabdfe87975d60be8bd58f74f2f446f5d
[]
no_license
NeilStrickland/itloc
20f9b9bcaa4d5840f7f32e84108174b294d84b1a
5b13b5b418766d10926b983eb3dd2ac42abf63d8
refs/heads/master
1,592,747,030,159
1,578,138,004,000
1,578,138,004,000
197,470,135
2
0
null
null
null
null
UTF-8
Lean
false
false
8,544
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Recall that (fin n) is the type of pairs ⟨i,h⟩, where i is a natural number and h is a proof that i < n. In this file we prove some additional facts about these types, which might perhaps be added to the standard library at some point. -/ import data.list data.fintype namespace fin open fin finset def pred_alt {n : ℕ} {i : ℕ} (h : i.succ < n.succ) : fin n := ⟨i,nat.lt_of_succ_lt_succ h⟩ /- The successor function (fin n) → (fin (n + 1)) is injective -/ lemma succ_inj : ∀ {n : ℕ} (i j : fin n) (h : i.succ = j.succ), i = j | n ⟨i_val,_⟩ ⟨j_val,_⟩ h := begin let h0 := @congr_arg (fin n.succ) ℕ _ _ (@fin.val n.succ) h, dsimp[fin.succ] at h0, apply fin.eq_of_veq, exact nat.succ_inj h0, end /- Zero is not a successor -/ lemma zero_ne_succ : ∀ {n : ℕ} {i : fin n}, (0 : fin n.succ) ≠ i.succ | n ⟨i_val,_⟩ := λ e, nat.no_confusion (congr_arg fin.val e) /- Zero is less than any successor -/ lemma zero_lt_succ : ∀ {n : ℕ} {i : fin n}, (0 : fin n.succ) < i.succ | n ⟨i_val,_⟩ := nat.zero_lt_succ i_val /- The successor map preserves order -/ lemma succ_le_succ {n : ℕ} {i j : fin n} (h : i ≤ j) : i.succ ≤ j.succ := by {cases i,cases j,dsimp[has_le.le,fin.le],apply nat.succ_le_succ h,} /- The successor map preserves strict order -/ lemma succ_lt_succ {n : ℕ} {i j : fin n} (h : i < j) : i.succ < j.succ := by {cases i,cases j,dsimp[has_lt.lt,fin.lt],apply nat.succ_lt_succ h,} /- The successor map reflects order -/ lemma le_of_succ_le_succ {n : ℕ} {i j : fin n} (h : i.succ ≤ j.succ) : i ≤ j := by {cases i,cases j,dsimp[has_le.le,fin.le],apply nat.le_of_succ_le_succ h,} /- The successor map reflects strict order -/ lemma lt_of_succ_lt_succ {n : ℕ} {i j : fin n} (h : i.succ < j.succ) : i < j := by {cases i,cases j,dsimp[has_lt.lt,fin.lt],apply nat.lt_of_succ_lt_succ h,} /- Nothing is less than zero -/ lemma not_lt_zero {n : ℕ} (i : fin n.succ) : ¬ i < 0 := by {cases i,dsimp[has_lt.lt,fin.lt],exact nat.not_lt_zero i_val,} /- This function produces a list of all the elements of (fin n) -/ def elems_list : ∀ (n : ℕ), list (fin n) | 0 := @list.nil _ | (n + 1) := list.cons 0 ((elems_list n).map fin.succ) /-The number of elements of (fin n) is n -/ lemma elems_list_length : ∀ (n : ℕ), (elems_list n).length = n | 0 := rfl | (n + 1) := congr_arg nat.succ ((list.length_map fin.succ (elems_list n)).trans (elems_list_length n)) /- The list of elements has no duplicates -/ def elems_list_nodup : ∀ (n : ℕ), list.nodup (elems_list n) | 0 := @list.pairwise.nil _ ne | (n + 1) := begin let old_list := (elems_list n).map fin.succ, have old_nodup : list.nodup old_list := list.nodup_map fin.succ_inj (elems_list_nodup n), have not_mem_old : ∀ k ∈ old_list, (0 : fin n.succ) ≠ k := begin intros k k_in_old zero_eq_k, let h1 := (list.mem_map.mp k_in_old), exact exists.elim h1 (λ k0 h2,zero_ne_succ (zero_eq_k.trans h2.right.symm)), end, exact list.pairwise.cons (not_mem_old) (old_nodup) end /- Every element occurs in our list of elements -/ def elems_list_complete {n : ℕ} (k : fin n) : k ∈ (elems_list n) := begin induction n with n0 ih, {exact fin.elim0 k,}, {dsimp[elems_list], rw[list.mem_cons_eq], cases k, cases k_val with k0_val, {left,apply fin.eq_of_veq,refl,}, {have k0_is_lt : k0_val < n0 := nat.lt_of_succ_lt_succ k_is_lt, let k0 : fin n0 := ⟨k0_val,k0_is_lt⟩, have h0 : k0.succ = ⟨k0_val.succ,k_is_lt⟩ := by {apply fin.eq_of_veq,refl,}, right, apply list.mem_map.mpr, existsi k0, exact ⟨ih k0,h0⟩, } } end /- Convert our list of elements to a set -/ def elems_finset (n : ℕ) : finset (fin n) := { val := elems_list n, nodup := elems_list_nodup n } /- Every element is in our set of elements -/ def elems_finset_complete {n : ℕ} (k : fin n) : k ∈ (elems_finset n) := elems_list_complete k /- This function returns the least element of (fin n) satisfying a given predicate p. For this to work, we need a decision procedure for p (given as an implicit typeclass argument) and also a proof that at least one element of (fin n) satisfies p. Moreover, we return the least element k packaged together with proofs of its properties. Thus, if this function returns x, then x.val is the relevant value of k, and x.property.left is a proof of (p k), and x.property.right is a proof that k is minimal with respect to this. -/ def least_element {n : ℕ} (p : fin n → Prop) [d : decidable_pred p] (e : ∃ k, p k) : {k : fin n // p k ∧ ∀ j, p j → k ≤ j} := begin tactic.unfreeze_local_instances, induction n with n0 ih, {exfalso, cases e with i _,exact fin.elim0 i,}, { by_cases pz : (p 0), {exact ⟨0, pz, λ j _,fin.zero_le j⟩}, {let p0 : fin n0 → Prop := λ k0, p k0.succ, let d0 : decidable_pred p0 := λ k0, d k0.succ, have e0 : ∃ k0, p0 k0 := begin rcases e with ⟨⟨k_val,k_is_lt⟩,p_k⟩, rcases k_val with _ | k0_val, {contradiction}, {have k0_is_lt : k0_val < n0 := nat.lt_of_succ_lt_succ k_is_lt, let k0 : fin n0 := ⟨k0_val,k0_is_lt⟩, existsi k0,assumption } end, rcases (@ih p0 d0 e0) with ⟨k0,p0_k0,k0_min⟩, let k := fin.succ k0, have p_k : p k := p0_k0, have k_min : ∀ j, p j → k ≤ j := begin intro j, cases j,rcases j_val with _ | j0_val; simp[has_le.le,fin.le], {intro pz0, exact false.elim (pz pz0),}, {have j0_is_lt : j0_val < n0 := nat.lt_of_succ_lt_succ j_is_lt, let j0 : fin n0 := ⟨j0_val,j0_is_lt⟩, intro p0_j0, exact nat.succ_le_succ (k0_min j0 p0_j0), } end, exact ⟨k,p_k,k_min⟩ } } end /- This is essentially the same as the previous function, but formulated in terms of a finite subset of (fin n) rather than a predicate. -/ def finset_least_element {n : ℕ} (s : finset (fin n)) (e : s ≠ ∅ ) : {k : fin n // k ∈ s ∧ ∀ j, j ∈ s → k ≤ j} := least_element (λ k,k ∈ s) (exists_mem_of_ne_empty e) /- We now have a similar function for finding the largest element of a finite subset of (fin n). For technical reasons we have found it more convenient to do this directly with finite sets rather than predicates. -/ def finset_largest_element {n : ℕ} (s : finset (fin n)) (e : s ≠ ∅) : {k : fin n // k ∈ s ∧ ∀ j, j ∈ s → j ≤ k} := begin tactic.unfreeze_local_instances, induction n with n0 ih, {exfalso, cases (exists_mem_of_ne_empty e) with i _, exact fin.elim0 i,}, {let s0 := univ.filter (λ i0 : fin n0, i0.succ ∈ s), by_cases e0 : s0 ≠ ∅, {rcases (ih s0 e0) with ⟨⟨k0_val,k0_is_lt⟩,⟨k0_in_s0,k0_max⟩⟩, let k0 : fin n0 := ⟨k0_val,k0_is_lt⟩, let k := k0.succ, let k_in_s : k ∈ s := (mem_filter.mp k0_in_s0).right, let k_max : ∀ j, j ∈ s → j ≤ k := begin intros j j_in_s, cases j, cases j_val with j0_val, {exact fin.zero_le k,}, {have j0_is_lt : j0_val < n0 := nat.lt_of_succ_lt_succ j_is_lt, let j0 : fin n0 := ⟨j0_val,j0_is_lt⟩, have j0_in_s0 : j0 ∈ s0 := mem_filter.mpr ⟨mem_univ j0,j_in_s⟩, dsimp[has_le.le,fin.le,k,fin.succ], exact nat.succ_le_succ (k0_max j0 j0_in_s0), } end, exact ⟨k,⟨k_in_s,k_max⟩⟩, },{ let z : fin n0.succ := 0, have zero_in_s : z ∈ s := begin let h : ∀ k, k ∈ s → z ∈ s := begin intro k,cases k,cases k_val with k0_val, {intro z_in_s,exact z_in_s,}, {intro k_in_s,exfalso, have k0_is_lt : k0_val < n0 := nat.lt_of_succ_lt_succ k_is_lt, let k0 : fin n0 := ⟨k0_val,k0_is_lt⟩, exact e0 (ne_empty_of_mem (mem_filter.mpr ⟨mem_univ k0,k_in_s⟩)), } end, exact exists.elim (exists_mem_of_ne_empty e) h, end, have zero_max : ∀ j, j ∈ s → j ≤ z := begin intros j j_in_s, cases j, cases j_val with j0_val, {exact fin.zero_le z}, {exfalso, have j0_is_lt : j0_val < n0 := nat.lt_of_succ_lt_succ j_is_lt, let j0 : fin n0 := ⟨j0_val,j0_is_lt⟩, have j0_in_s0 : j0 ∈ s0 := mem_filter.mpr ⟨mem_univ j0,j_in_s⟩, exact e0 (ne_empty_of_mem j0_in_s0), } end, exact ⟨z,zero_in_s,zero_max⟩, } } end end fin
3a3b4bf76001a7ce1bb3c84692a10f3ae9e8d36d
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/finbug2.lean
31c3a323325b67386e5a96329fc3c8cf2d860aca
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
962
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.fin Author: Leonardo de Moura Finite ordinals. -/ open nat inductive fin : nat → Type := | fz : Π n, fin (succ n) | fs : Π {n}, fin n → fin (succ n) namespace fin definition to_nat : Π {n}, fin n → nat | @to_nat (succ n) (fz n) := zero | @to_nat (succ n) (fs f) := succ (@to_nat n f) definition lift : Π {n : nat}, fin n → Π (m : nat), fin (add m n) | @lift (succ n) (fz n) m := fz (add m n) | @lift (succ n) (@fs n f) m := fs (@lift n f m) theorem to_nat_lift : ∀ {n : nat} (f : fin n) (m : nat), to_nat f = to_nat (lift f m) | to_nat_lift (fz n) m := rfl | to_nat_lift (@fs n f) m := calc to_nat (fs f) = (to_nat f) + 1 : rfl ... = (to_nat (lift f m)) + 1 : to_nat_lift f ... = to_nat (lift (fs f) m) : rfl end fin
ad6482c7bfc6d59de5531c42b6e18910ef22e4d7
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/run_tactic1.lean
28ce9885da4bad368cc0dc1426305ed192e37770
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
731
lean
open tactic run_command tactic.trace "hello world" run_command do N ← to_expr `(nat), v ← to_expr `(10), add_decl (declaration.defn `val10 [] N v reducibility_hints.opaque tt) vm_eval val10 example : val10 = 10 := rfl meta definition mk_defs : nat → command | 0 := skip | (n+1) := do N ← to_expr `(nat), v ← to_expr (quote n), add_decl (declaration.defn (name.append_after `val n) [] N v reducibility_hints.opaque tt), mk_defs n run_command mk_defs 10 example : val_1 = 1 := rfl example : val_2 = 2 := rfl example : val_3 = 3 := rfl example : val_4 = 4 := rfl example : val_5 = 5 := rfl example : val_6 = 6 := rfl example : val_7 = 7 := rfl example : val_8 = 8 := rfl example : val_9 = 9 := rfl
90cd2b007f424a15a887101acb9207e325db196f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/valuation/tfae.lean
098191586542844552348d7fc7ceb396eaab3988
[ "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,402
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 ring_theory.ideal.cotangent import ring_theory.dedekind_domain.basic import ring_theory.valuation.valuation_ring import ring_theory.nakayama /-! # Equivalent conditions for DVR In `discrete_valuation_ring.tfae`, we show that the following are equivalent for a noetherian local domain `(R, m, k)`: - `R` is a discrete valuation ring - `R` is a valuation ring - `R` is a dedekind domain - `R` is integrally closed with a unique prime ideal - `m` is principal - `dimₖ m/m² = 1` - Every nonzero ideal is a power of `m`. -/ variables (R : Type*) [comm_ring R] (K : Type*) [field K] [algebra R K] [is_fraction_ring R K] open_locale discrete_valuation open local_ring open_locale big_operators lemma exists_maximal_ideal_pow_eq_of_principal [is_noetherian_ring R] [local_ring R] [is_domain R] (h : ¬ is_field R) (h' : (maximal_ideal R).is_principal) (I : ideal R) (hI : I ≠ ⊥) : ∃ n : ℕ, I = (maximal_ideal R) ^ n := begin classical, unfreezingI { obtain ⟨x, hx : _ = ideal.span _⟩ := h' }, by_cases hI' : I = ⊤, { use 0, rw [pow_zero, hI', ideal.one_eq_top] }, have H : ∀ r : R, ¬ (is_unit r) ↔ x ∣ r := λ r, (set_like.ext_iff.mp hx r).trans ideal.mem_span_singleton, have : x ≠ 0, { rintro rfl, apply ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h, simp [hx] }, have hx' := discrete_valuation_ring.irreducible_of_span_eq_maximal_ideal x this hx, have H' : ∀ r : R, r ≠ 0 → r ∈ nonunits R → ∃ (n : ℕ), associated (x ^ n) r, { intros r hr₁ hr₂, obtain ⟨f, hf₁, rfl, hf₂⟩ := (wf_dvd_monoid.not_unit_iff_exists_factors_eq r hr₁).mp hr₂, have : ∀ b ∈ f, associated x b, { intros b hb, exact irreducible.associated_of_dvd hx' (hf₁ b hb) ((H b).mp (hf₁ b hb).1) }, clear hr₁ hr₂ hf₁, induction f using multiset.induction with fa fs fh, { exact (hf₂ rfl).elim }, rcases eq_or_ne fs ∅ with rfl|hf', { use 1, rw [pow_one, multiset.prod_cons, multiset.empty_eq_zero, multiset.prod_zero, mul_one], exact this _ (multiset.mem_cons_self _ _) }, { obtain ⟨n, hn⟩ := fh hf' (λ b hb, this _ (multiset.mem_cons_of_mem hb)), use n + 1, rw [pow_add, multiset.prod_cons, mul_comm, pow_one], exact associated.mul_mul (this _ (multiset.mem_cons_self _ _)) hn } }, have : ∃ n : ℕ, x ^ n ∈ I, { obtain ⟨r, hr₁, hr₂⟩ : ∃ r : R, r ∈ I ∧ r ≠ 0, { by_contra h, push_neg at h, apply hI, rw eq_bot_iff, exact h }, obtain ⟨n, u, rfl⟩ := H' r hr₂ (le_maximal_ideal hI' hr₁), use n, rwa [← I.unit_mul_mem_iff_mem u.is_unit, mul_comm] }, use nat.find this, apply le_antisymm, { change ∀ s ∈ I, s ∈ _, by_contra hI'', push_neg at hI'', obtain ⟨s, hs₁, hs₂⟩ := hI'', apply hs₂, by_cases hs₃ : s = 0, { rw hs₃, exact zero_mem _ }, obtain ⟨n, u, rfl⟩ := H' s hs₃ (le_maximal_ideal hI' hs₁), rw [mul_comm, ideal.unit_mul_mem_iff_mem _ u.is_unit] at ⊢ hs₁, apply ideal.pow_le_pow (nat.find_min' this hs₁), apply ideal.pow_mem_pow, exact (H _).mpr (dvd_refl _) }, { rw [hx, ideal.span_singleton_pow, ideal.span_le, set.singleton_subset_iff], exact nat.find_spec this } end lemma maximal_ideal_is_principal_of_is_dedekind_domain [local_ring R] [is_domain R] [is_dedekind_domain R] : (maximal_ideal R).is_principal := begin classical, by_cases ne_bot : maximal_ideal R = ⊥, { rw ne_bot, apply_instance }, obtain ⟨a, ha₁, ha₂⟩ : ∃ a ∈ maximal_ideal R, a ≠ (0 : R), { by_contra h', push_neg at h', apply ne_bot, rwa eq_bot_iff }, have hle : ideal.span {a} ≤ maximal_ideal R, { rwa [ideal.span_le, set.singleton_subset_iff] }, have : (ideal.span {a}).radical = maximal_ideal R, { rw ideal.radical_eq_Inf, apply le_antisymm, { exact Inf_le ⟨hle, infer_instance⟩ }, { refine le_Inf (λ I hI, (eq_maximal_ideal $ is_dedekind_domain.dimension_le_one _ (λ e, ha₂ _) hI.2).ge), rw [← ideal.span_singleton_eq_bot, eq_bot_iff, ← e], exact hI.1 } }, have : ∃ n, maximal_ideal R ^ n ≤ ideal.span {a}, { rw ← this, apply ideal.exists_radical_pow_le_of_fg, exact is_noetherian.noetherian _ }, cases hn : nat.find this, { have := nat.find_spec this, rw [hn, pow_zero, ideal.one_eq_top] at this, exact (ideal.is_maximal.ne_top infer_instance (eq_top_iff.mpr $ this.trans hle)).elim }, obtain ⟨b, hb₁, hb₂⟩ : ∃ b ∈ maximal_ideal R ^ n, ¬ b ∈ ideal.span {a}, { by_contra h', push_neg at h', rw nat.find_eq_iff at hn, exact hn.2 n n.lt_succ_self (λ x hx, not_not.mp (h' x hx)) }, have hb₃ : ∀ m ∈ maximal_ideal R, ∃ k : R, k * a = b * m, { intros m hm, rw ← ideal.mem_span_singleton', apply nat.find_spec this, rw [hn, pow_succ'], exact ideal.mul_mem_mul hb₁ hm }, have hb₄ : b ≠ 0, { rintro rfl, apply hb₂, exact zero_mem _ }, let K := fraction_ring R, let x : K := algebra_map R K b / algebra_map R K a, let M := submodule.map (algebra.of_id R K).to_linear_map (maximal_ideal R), have ha₃ : algebra_map R K a ≠ 0 := is_fraction_ring.to_map_eq_zero_iff.not.mpr ha₂, by_cases hx : ∀ y ∈ M, x * y ∈ M, { have := is_integral_of_smul_mem_submodule M _ _ x hx, { obtain ⟨y, e⟩ := is_integrally_closed.algebra_map_eq_of_integral this, refine (hb₂ (ideal.mem_span_singleton'.mpr ⟨y, _⟩)).elim, apply is_fraction_ring.injective R K, rw [map_mul, e, div_mul_cancel _ ha₃] }, { rw submodule.ne_bot_iff, refine ⟨_, ⟨a, ha₁, rfl⟩, _⟩, exact is_fraction_ring.to_map_eq_zero_iff.not.mpr ha₂ }, { apply submodule.fg.map, exact is_noetherian.noetherian _ } }, { have : (M.map (distrib_mul_action.to_linear_map R K x)).comap (algebra.of_id R K).to_linear_map = ⊤, { by_contra h, apply hx, rintros m' ⟨m, hm, (rfl : algebra_map R K m = m')⟩, obtain ⟨k, hk⟩ := hb₃ m hm, have hk' : x * algebra_map R K m = algebra_map R K k, { rw [← mul_div_right_comm, ← map_mul, ← hk, map_mul, mul_div_cancel _ ha₃] }, exact ⟨k, le_maximal_ideal h ⟨_, ⟨_, hm, rfl⟩, hk'⟩, hk'.symm⟩ }, obtain ⟨y, hy₁, hy₂⟩ : ∃ y ∈ maximal_ideal R, b * y = a, { rw [ideal.eq_top_iff_one, submodule.mem_comap] at this, obtain ⟨_, ⟨y, hy, rfl⟩, hy' : x * algebra_map R K y = algebra_map R K 1⟩ := this, rw [map_one, ← mul_div_right_comm, div_eq_one_iff_eq ha₃, ← map_mul] at hy', exact ⟨y, hy, is_fraction_ring.injective R K hy'⟩ }, refine ⟨⟨y, _⟩⟩, apply le_antisymm, { intros m hm, obtain ⟨k, hk⟩ := hb₃ m hm, rw [← hy₂, mul_comm, mul_assoc] at hk, rw [← mul_left_cancel₀ hb₄ hk, mul_comm], exact ideal.mem_span_singleton'.mpr ⟨_, rfl⟩ }, { rwa [submodule.span_le, set.singleton_subset_iff] } } end lemma discrete_valuation_ring.tfae [is_noetherian_ring R] [local_ring R] [is_domain R] (h : ¬ is_field R) : tfae [discrete_valuation_ring R, valuation_ring R, is_dedekind_domain R, is_integrally_closed R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ P.is_prime, (maximal_ideal R).is_principal, finite_dimensional.finrank (residue_field R) (cotangent_space R) = 1, ∀ I ≠ ⊥, ∃ n : ℕ, I = (maximal_ideal R) ^ n] := begin have ne_bot := ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h, classical, rw finrank_eq_one_iff', tfae_have : 1 → 2, { introI _, apply_instance }, tfae_have : 2 → 1, { introI _, haveI := is_bezout.to_gcd_domain R, haveI : unique_factorization_monoid R := ufm_of_gcd_of_wf_dvd_monoid, apply discrete_valuation_ring.of_ufd_of_unique_irreducible, { obtain ⟨x, hx₁, hx₂⟩ := ring.exists_not_is_unit_of_not_is_field h, obtain ⟨p, hp₁, hp₂⟩ := wf_dvd_monoid.exists_irreducible_factor hx₂ hx₁, exact ⟨p, hp₁⟩ }, { exact valuation_ring.unique_irreducible } }, tfae_have : 1 → 4, { introI H, exact ⟨infer_instance, ((discrete_valuation_ring.iff_pid_with_one_nonzero_prime R).mp H).2⟩ }, tfae_have : 4 → 3, { rintros ⟨h₁, h₂⟩, exact ⟨infer_instance, λ I hI hI', unique_of_exists_unique h₂ ⟨ne_bot, infer_instance⟩ ⟨hI, hI'⟩ ▸ maximal_ideal.is_maximal R, h₁⟩ }, tfae_have : 3 → 5, { introI h, exact maximal_ideal_is_principal_of_is_dedekind_domain R }, tfae_have : 5 → 6, { rintro ⟨x, hx⟩, have : x ∈ maximal_ideal R := by { rw hx, exact submodule.subset_span (set.mem_singleton x) }, let x' : maximal_ideal R := ⟨x, this⟩, use submodule.quotient.mk x', split, { intro e, rw submodule.quotient.mk_eq_zero at e, apply ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h, apply submodule.eq_bot_of_le_smul_of_le_jacobson_bot (maximal_ideal R), { exact ⟨{x}, (finset.coe_singleton x).symm ▸ hx.symm⟩ }, { conv_lhs { rw hx }, rw submodule.mem_smul_top_iff at e, rwa [submodule.span_le, set.singleton_subset_iff] }, { rw local_ring.jacobson_eq_maximal_ideal (⊥ : ideal R) bot_ne_top, exact le_refl _ } }, { refine λ w, quotient.induction_on' w $ λ y, _, obtain ⟨y, hy⟩ := y, rw [hx, submodule.mem_span_singleton] at hy, obtain ⟨a, rfl⟩ := hy, exact ⟨ideal.quotient.mk _ a, rfl⟩ } }, tfae_have : 6 → 5, { rintro ⟨x, hx, hx'⟩, induction x using quotient.induction_on', use x, apply le_antisymm, swap, { rw [submodule.span_le, set.singleton_subset_iff], exact x.prop }, have h₁ : (ideal.span {x} : ideal R) ⊔ maximal_ideal R ≤ ideal.span {x} ⊔ (maximal_ideal R) • (maximal_ideal R), { refine sup_le le_sup_left _, rintros m hm, obtain ⟨c, hc⟩ := hx' (submodule.quotient.mk ⟨m, hm⟩), induction c using quotient.induction_on', rw ← sub_sub_cancel (c * x) m, apply sub_mem _ _, { apply_instance }, { refine ideal.mem_sup_left (ideal.mem_span_singleton'.mpr ⟨c, rfl⟩) }, { have := (submodule.quotient.eq _).mp hc, rw [submodule.mem_smul_top_iff] at this, exact ideal.mem_sup_right this } }, have h₂ : maximal_ideal R ≤ (⊥ : ideal R).jacobson, { rw local_ring.jacobson_eq_maximal_ideal, exacts [le_refl _, bot_ne_top] }, have := submodule.smul_sup_eq_smul_sup_of_le_smul_of_le_jacobson (is_noetherian.noetherian _) h₂ h₁, rw [submodule.bot_smul, sup_bot_eq] at this, rw [← sup_eq_left, eq_comm], exact le_sup_left.antisymm (h₁.trans $ le_of_eq this) }, tfae_have : 5 → 7, { exact exists_maximal_ideal_pow_eq_of_principal R h }, tfae_have : 7 → 2, { rw valuation_ring.iff_ideal_total, intro H, constructor, intros I J, by_cases hI : I = ⊥, { subst hI, left, exact bot_le }, by_cases hJ : J = ⊥, { subst hJ, right, exact bot_le }, obtain ⟨n, rfl⟩ := H I hI, obtain ⟨m, rfl⟩ := H J hJ, cases le_total m n with h' h', { left, exact ideal.pow_le_pow h' }, { right, exact ideal.pow_le_pow h' } }, tfae_finish, end
47d22d2e0fd967dda36085a0815480eb5fa259f9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/computability/partrec_code.lean
bd552ff740022e3d294f03d8074f68aed170c3eb
[ "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
43,410
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import computability.partrec /-! # Gödel Numbering for Partial Recursive Functions. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `nat.partrec.code`, an inductive datatype describing code for partial recursive functions on ℕ. It defines an encoding for these codes, and proves that the constructors are primitive recursive with respect to the encoding. It also defines the evalution of these codes as partial functions using `pfun`, and proves that a function is partially recursive (as defined by `nat.partrec`) if and only if it is the evaluation of some code. ## Main Definitions * `nat.partrec.code`: Inductive datatype for partial recursive codes. * `nat.partrec.code.encode_code`: A (computable) encoding of codes as natural numbers. * `nat.partrec.code.of_nat_code`: The inverse of this encoding. * `nat.partrec.code.eval`: The interpretation of a `nat.partrec.code` as a partial function. ## Main Results * `nat.partrec.code.rec_prim`: Recursion on `nat.partrec.code` is primitive recursive. * `nat.partrec.code.rec_computable`: Recursion on `nat.partrec.code` is computable. * `nat.partrec.code.smn`: The $S_n^m$ theorem. * `nat.partrec.code.exists_code`: Partial recursiveness is equivalent to being the eval of a code. * `nat.partrec.code.evaln_prim`: `evaln` is primitive recursive. * `nat.partrec.code.fixed_point`: Roger's fixed point theorem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrec₂.unpaired'.2 $ begin refine partrec.map ((@partrec₂.unpaired' (λ (a b : ℕ), nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.to₂, have := rfind (partrec₂.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrec₂.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).to₂), simp at this, exact this end /-- Code for partial recursive functions from ℕ to ℕ. See `nat.partrec.code.eval` for the interpretation of these constructors. -/ inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) instance : inhabited code := ⟨zero⟩ /-- Returns a code for the constant function outputting a particular natural. -/ protected def const : ℕ → code | 0 := zero | (n+1) := comp succ (const n) theorem const_inj : Π {n₁ n₂}, nat.partrec.code.const n₁ = nat.partrec.code.const n₂ → n₁ = n₂ | 0 0 h := by simp | (n₁+1) (n₂+1) h := by { dsimp [nat.partrec.code.const] at h, injection h with h₁ h₂, simp only [const_inj h₂] } /-- A code for the identity function. -/ protected def id : code := pair left right /-- Given a code `c` taking a pair as input, returns a code using `n` as the first argument to `c`. -/ def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) /-- An encoding of a `nat.partrec.code` as a ℕ. -/ def encode_code : code → ℕ | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 /-- A decoder for `nat.partrec.code.encode_code`, taking any ℕ to the `nat.partrec.code` it represents. -/ def of_nat_code : ℕ → code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end /-- Proof that `nat.partrec.code.of_nat_code` is the inverse of `nat.partrec.code.encode_code`-/ private theorem encode_of_nat_code : ∀ n, encode_code (of_nat_code n) = n | 0 := by simp [of_nat_code, encode_code] | 1 := by simp [of_nat_code, encode_code] | 2 := by simp [of_nat_code, encode_code] | 3 := by simp [of_nat_code, encode_code] | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, λ c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.left_le_mkpair _ _) this, lt_of_le_of_lt (nat.right_le_mkpair _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code] end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code], end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_rfl), end section open primrec theorem pair_prim : primrec₂ pair := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem comp_prim : primrec₂ comp := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem prec_prim : primrec₂ prec := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (λ a, F a (c a) : α → σ) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end /-- Recursion on `nat.partrec.code` is primitive recursive. -/ theorem rec_prim {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec (λ a : α × code × code × σ × σ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : α → code → code → σ → σ → σ} (hco : primrec (λ a : α × code × code × σ × σ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : α → code → code → σ → σ → σ} (hpc : primrec (λ a : α × code × code × σ × σ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : α → code → σ → σ} (hrf : primrec (λ a : α × code × σ, rf a.1 a.2.1 a.2.2)) : let F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /-- Recursion on `nat.partrec.code` is computable. -/ theorem rec_computable {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (λ a, F a (c a)) := begin -- TODO(Mario): less copy-paste from previous proof intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have m₂ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : computable₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp computable.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end /-- The interpretation of a `nat.partrec.code` as a partial function. * `nat.partrec.code.zero`: The constant zero function. * `nat.partrec.code.succ`: The successor function. * `nat.partrec.code.left`: Left unpairing of a pair of ℕ (encoded by `nat.mkpair`) * `nat.partrec.code.right`: Right unpairing of a pair of ℕ (encoded by `nat.mkpair`) * `nat.partrec.code.pair`: Pairs the outputs of argument codes using `nat.mkpair`. * `nat.partrec.code.comp`: Composition of two argument codes. * `nat.partrec.code.prec`: Primitive recursion. Given an argument of the form `nat.mkpair a n`: * If `n = 0`, returns `eval cf a`. * If `n = succ k`, returns `eval cg (mkpair a (mkpair k (eval (prec cf cg) (mkpair a k))))` * `nat.partrec.code.rfind'`: Minimization. For `f` an argument of the form `nat.mkpair a m`, `rfind' f m` returns the least `a` such that `f a m = 0`, if one exists and `f b m` terminates for `b < a` -/ def eval : code → ℕ →. ℕ | zero := pure 0 | succ := nat.succ | left := ↑(λ n : ℕ, n.unpair.1) | right := ↑(λ n : ℕ, n.unpair.2) | (pair cf cg) := λ n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := λ n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (λ a n, n.elim (eval cf a) (λ y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) /-- Helper lemma for the evaluation of `prec` in the base case. -/ @[simp] lemma eval_prec_zero (cf cg : code) (a : ℕ) : eval (prec cf cg) (mkpair a 0) = eval cf a := by rw [eval, nat.unpaired, nat.unpair_mkpair, nat.elim_zero] /-- Helper lemma for the evaluation of `prec` in the recursive case. -/ lemma eval_prec_succ (cf cg : code) (a k : ℕ) : eval (prec cf cg) (mkpair a (nat.succ k)) = do ih <- eval (prec cf cg) (mkpair a k), eval cg (mkpair a (mkpair k ih)) := begin rw [eval, nat.unpaired, part.bind_eq_bind, nat.unpair_mkpair, nat.elim_succ], simp, end instance : has_mem (ℕ →. ℕ) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (code.const n) m = part.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = part.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, code.const, function.iterate_succ'] theorem curry_prim : primrec₂ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem curry_inj {c₁ c₂ n₁ n₂} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ := ⟨by injection h, by { injection h, injection h with h₁ h₂, injection h₂ with h₃ h₄, exact const_inj h₃ }⟩ /-- The $S_n^m$ theorem: There is a computable function, namely `nat.partrec.code.curry`, that takes a program and a ℕ `n`, and returns a new program using `n` as the first argument. -/ theorem smn : ∃ f : code → ℕ → code, computable₂ f ∧ ∀ c n x, eval (f c n) x = eval c (mkpair n x) := ⟨curry, primrec₂.to_comp curry_prim, eval_curry⟩ /-- A function is partial recursive if and only if there is a code implementing it. -/ theorem exists_code {f : ℕ →. ℕ} : nat.partrec f ↔ ∃ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, part.map_id'] }, end, λ h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ /-- A modified evaluation for the code which returns an `option ℕ` instead of a `part ℕ`. To avoid undecidability, `evaln` takes a parameter `k` and fails if it encounters a number ≥ k in the course of its execution. Other than this, the semantics are the same as in `nat.partrec.code.eval`. -/ def evaln : ∀ k : ℕ, code → ℕ → option ℕ | 0 _ := λ m, none | (k+1) zero := λ n, guard (n ≤ k) >> pure 0 | (k+1) succ := λ n, guard (n ≤ k) >> pure (nat.succ n) | (k+1) left := λ n, guard (n ≤ k) >> pure n.unpair.1 | (k+1) right := λ n, guard (n ≤ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := λ n, guard (n ≤ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := λ n, guard (n ≤ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := λ n, guard (n ≤ k) >> n.unpaired (λ a n, n.cases (evaln (k+1) cf a) $ λ y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := λ n, guard (n ≤ k) >> n.unpaired (λ a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : ∀ {o : option ℕ}, x ∈ guard (n ≤ k) >> o → n < k + 1, { cases c; rw [evaln] at h; exact this h }, simpa [(>>)] using nat.lt_succ_of_le end theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0 k₂ c n x hl h := by simp [evaln] at h; cases h | (k+1) (k₂+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ guard (n ≤ k) >> o₁ → x ∈ guard (n ≤ k₂) >> o₂, { simp [(>>)], introv h h₁ h₂ h₃, exact ⟨le_trans h₂ h, h₁ h₃⟩ }, simp at h ⊢, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊢; refine this hl' (λ h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊢, exact h.imp (λ a, and.imp (hf _ _) $ Exists.imp $ λ b, and.imp_left (hg _ _)) }, { -- comp cf cg simp at h ⊢, exact h.imp (λ a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact λ y h₁ h₂, ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ } }, { -- rfind' cf simp at h ⊢, refine h.imp (λ x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊢; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨y, ef, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine λ y h₁ h₂, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ h₂ } } }, { -- rfind' cf rcases h with ⟨m, h₁, h₂⟩, by_cases m0 : m = 0; simp [m0] at h₂, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, λ m, (nat.not_lt_zero _).elim⟩, by injection h₂ with h₂; simp [h₂]⟩ }, { have := evaln_sound h₂, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, refine ⟨ y+1, ⟨by simpa [add_comm, add_left_comm] using hy₁, λ i im, _⟩, by simp [add_comm, add_left_comm] ⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hy₂ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := ⟨λ h, begin rsuffices ⟨k, h⟩ : ∃ k, x ∈ evaln (k+1) c n, { exact ⟨k + 1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊢, iterate 4 { exact ⟨⟨_, le_rfl⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hk₁⟩, rcases hg hy with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, refine ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hk₁⟩, rcases hf hx with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = n₂, induction n₂ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hk₁⟩, rcases hg hx with ⟨k₂, hk₂⟩, refine ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_of_le_left $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hk₂⟩, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, suffices : ∃ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hy₂, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hy₂ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hk₁⟩, rcases IH m.succ (by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁) (λ i hi, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₂ (nat.succ_lt_succ hi)) with ⟨k₂, hk₂⟩, use (max k₁ k₂).succ, rw [zero_add] at hk₁, use (nat.le_succ_of_le $ le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁), use a, use evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂ } } end, λ ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option ℕ))) (p : ℕ × code) (n : ℕ) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (λ p:_×(_×_)×_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option ℕ))) : option (list (option ℕ)) := option.some $ let a := of_nat (ℕ × code) L.length, k := a.1, c := a.2 in (list.range k).map (λ n, k.cases none $ λ k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (λ cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (λ cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (λ cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (λ y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (λ cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (λ _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (ℕ × code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrec₂.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrec₂.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrec₂.mkpair.comp z $ primrec₂.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrec₂.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrec₂.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (λ b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_len_le, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end /-- The `nat.partrec.code.evaln` function is primitive recursive. -/ theorem evaln_prim : primrec (λ (a : (ℕ × code) × ℕ), evaln a.1.1 a.1.2 a.2) := have primrec₂ (λ (_:unit) (n : ℕ), let a := of_nat (ℕ × code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).to₂ $ λ _ p, begin simp [G], rw (_ : (of_nat (ℕ × code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (λ n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : ∀ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) → lup ((list.range (mkpair k (encode c))).map (λ n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.to₂).of_eq $ λ ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (λ k, evaln k c n) := part.ext $ λ x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrec₂ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq $ λ a, by simp [eval_eq_rfind_opt] /-- Roger's fixed-point theorem: Any total, computable `f` has a fixed point: That is, under the interpretation given by `nat.partrec.code.eval`, there is a code `c` such that `c` and `f c` have the same evaluation. -/ theorem fixed_point {f : code → code} (hf : computable f) : ∃ c : code, eval (f c) = eval c := let g (x y : ℕ) : part ℕ := eval (of_nat code x) x >>= λ b, eval (of_nat code b) y in have partrec₂ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).to₂, let ⟨cg, eg⟩ := exists_code.1 this in have eg' : ∀ a n, eval cg (mkpair a n) = part.map encode (g a n) := by simp [eg], let F (x : ℕ) : code := f (curry cg x) in have computable F := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, let ⟨cF, eF⟩ := exists_code.1 this in have eF' : eval cF (encode cF) = part.some (encode (F (encode cF))), by simp [eF], ⟨curry cg (encode cF), funext (λ n, show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n, by simp [eg', eF', part.map_id', g])⟩ theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ λ c e, funext $ λ n, by simp [e.symm, ef, part.map_id'] end end nat.partrec.code
1d0f1cbc07c2da2637eed606f0cee1a3470b5518
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Data/Nat/Div.lean
dea5a1cc5086b40426f36d75c9cf6fbe3a9afb45
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
4,126
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.WF import Init.Data.Nat.Basic namespace Nat private def divRecLemma {x y : Nat} : 0 < y ∧ y ≤ x → x - y < x := fun h => And.rec (fun ypos ylex => subLt (Nat.ltOfLtOfLe ypos ylex) ypos) h private def div.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (divRecLemma h) y + 1 else zero @[extern "lean_nat_div"] protected def div (a b : @& Nat) : Nat := WellFounded.fix ltWf div.F a b instance : HasDiv Nat := ⟨Nat.div⟩ private theorem divDefAux (x y : Nat) : x / y = if h : 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := congrFun (WellFounded.fixEq ltWf div.F x) y theorem divDef (x y : Nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := difEqIf (0 < y ∧ y ≤ x) ((x - y) / y + 1) 0 ▸ divDefAux x y private theorem div.induction.F.{u} (C : Nat → Nat → Sort u) (h₁ : ∀ x y, 0 < y ∧ y ≤ x → C (x - y) y → C x y) (h₂ : ∀ x y, ¬(0 < y ∧ y ≤ x) → C x y) (x : Nat) (f : ∀ (x₁ : Nat), x₁ < x → ∀ (y : Nat), C x₁ y) (y : Nat) : C x y := if h : 0 < y ∧ y ≤ x then h₁ x y h (f (x - y) (divRecLemma h) y) else h₂ x y h @[elabAsEliminator] theorem div.inductionOn.{u} {C : Nat → Nat → Sort u} (x y : Nat) (h₁ : ∀ x y, 0 < y ∧ y ≤ x → C (x - y) y → C x y) (h₂ : ∀ x y, ¬(0 < y ∧ y ≤ x) → C x y) : C x y := WellFounded.fix Nat.ltWf (div.induction.F C h₁ h₂) x y private def mod.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (divRecLemma h) y else x @[extern "lean_nat_mod"] protected def mod (a b : @& Nat) : Nat := WellFounded.fix ltWf mod.F a b instance : HasMod Nat := ⟨Nat.mod⟩ private theorem modDefAux (x y : Nat) : x % y = if h : 0 < y ∧ y ≤ x then (x - y) % y else x := congrFun (WellFounded.fixEq ltWf mod.F x) y theorem modDef (x y : Nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := difEqIf (0 < y ∧ y ≤ x) ((x - y) % y) x ▸ modDefAux x y @[elabAsEliminator] theorem mod.inductionOn.{u} {C : Nat → Nat → Sort u} (x y : Nat) (h₁ : ∀ x y, 0 < y ∧ y ≤ x → C (x - y) y → C x y) (h₂ : ∀ x y, ¬(0 < y ∧ y ≤ x) → C x y) : C x y := div.inductionOn x y h₁ h₂ theorem modZero (a : Nat) : a % 0 = a := suffices (if 0 < 0 ∧ 0 ≤ a then (a - 0) % 0 else a) = a from (modDef a 0).symm ▸ this; have h : ¬ (0 < 0 ∧ 0 ≤ a) from fun ⟨h₁, _⟩ => absurd h₁ (Nat.ltIrrefl _); ifNeg h theorem modEqOfLt {a b : Nat} (h : a < b) : a % b = a := suffices (if 0 < b ∧ b ≤ a then (a - b) % b else a) = a from (modDef a b).symm ▸ this; have h' : ¬(0 < b ∧ b ≤ a) from fun ⟨_, h₁⟩ => absurd h₁ (Nat.notLeOfGt h); ifNeg h' theorem modEqSubMod {a b : Nat} (h : a ≥ b) : a % b = (a - b) % b := Or.elim (eqZeroOrPos b) (fun h₁ => h₁.symm ▸ (Nat.subZero a).symm ▸ rfl) (fun h₁ => (modDef a b).symm ▸ ifPos ⟨h₁, h⟩) theorem modLt (x : Nat) {y : Nat} : y > 0 → x % y < y := mod.inductionOn x y (fun (x y) ⟨_, h₁⟩ (h₂ h₃) => have ih : (x - y) % y < y from h₂ h₃; have Heq : x % y = (x - y) % y from modEqSubMod h₁; Heq.symm ▸ ih) (fun x y h₁ h₂ => have h₁ : ¬ 0 < y ∨ ¬ y ≤ x from Iff.mp (Decidable.notAndIffOrNot _ _) h₁; Or.elim h₁ (fun h₁ => absurd h₂ h₁) (fun h₁ => have hgt : y > x from gtOfNotLe h₁; have Heq : x % y = x from modEqOfLt hgt; Heq.symm ▸ hgt)) theorem modLe (x y : Nat) : x % y ≤ x := Or.elim (Nat.ltOrGe x y) (fun (h₁ : x < y) => (modEqOfLt h₁).symm ▸ Nat.leRefl _) (fun (h₁ : x ≥ y) => Or.elim (eqZeroOrPos y) (fun (h₂ : y = 0) => h₂.symm ▸ (Nat.modZero x).symm ▸ Nat.leRefl _) (fun (h₂ : y > 0) => Nat.leTrans (Nat.leOfLt (Nat.modLt _ h₂)) h₁)) end Nat
732e4b2092a52e0bcf697b930b620d743ccb802b
9028d228ac200bbefe3a711342514dd4e4458bff
/src/group_theory/congruence.lean
c611da5e7d71ae75673c8fd89893d483683c38fb
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,926
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.group.pi import algebra.group.prod import data.equiv.mul_add import group_theory.submonoid.operations /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) /-- The equivalence relation underlying an additive congruence relation. -/ add_decl_doc add_con.to_setoid /-- The equivalence relation underlying a multiplicative congruence relation. -/ add_decl_doc con.to_setoid variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw [Sup_eq_con_gen, Sup_image], congr' with x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : {d // c ≤ d} ≃o (con c.quotient) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective (ker_lift f) ⟨ker_lift_injective f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end con
f96fb638560f10a30a859846ab52b4e14011c9c9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/metric_space/hausdorff_dimension.lean
598e1b875281e530d953530cc13a89a6476efe92
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,051
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 measure_theory.measure.hausdorff /-! # Hausdorff dimension The Hausdorff dimension of a set `X` in an (extended) metric space is the unique number `dimH s : ℝ≥0∞` such that for any `d : ℝ≥0` we have - `μH[d] s = 0` if `dimH s < d`, and - `μH[d] s = ∞` if `d < dimH s`. In this file we define `dimH s` to be the Hausdorff dimension of `s`, then prove some basic properties of Hausdorff dimension. ## Main definitions * `measure_theory.dimH`: the Hausdorff dimension of a set. For the Hausdorff dimension of the whole space we use `measure_theory.dimH (set.univ : set X)`. ## Main results ### Basic properties of Hausdorff dimension * `hausdorff_measure_of_lt_dimH`, `dimH_le_of_hausdorff_measure_ne_top`, `le_dimH_of_hausdorff_measure_eq_top`, `hausdorff_measure_of_dimH_lt`, `measure_zero_of_dimH_lt`, `le_dimH_of_hausdorff_measure_ne_zero`, `dimH_of_hausdorff_measure_ne_zero_ne_top`: various forms of the characteristic property of the Hausdorff dimension; * `dimH_union`: the Hausdorff dimension of the union of two sets is the maximum of their Hausdorff dimensions. * `dimH_Union`, `dimH_bUnion`, `dimH_sUnion`: the Hausdorff dimension of a countable union of sets is the supremum of their Hausdorff dimensions; * `dimH_empty`, `dimH_singleton`, `set.subsingleton.dimH_zero`, `set.countable.dimH_zero` : `dimH s = 0` whenever `s` is countable; ### (Pre)images under (anti)lipschitz and Hölder continuous maps * `holder_with.dimH_image_le` etc: if `f : X → Y` is Hölder continuous with exponent `r > 0`, then for any `s`, `dimH (f '' s) ≤ dimH s / r`. We prove versions of this statement for `holder_with`, `holder_on_with`, and locally Hölder maps, as well as for `set.image` and `set.range`. * `lipschitz_with.dimH_image_le` etc: Lipschitz continuous maps do not increase the Hausdorff dimension of sets. * for a map that is known to be both Lipschitz and antilipschitz (e.g., for an `isometry` or a `continuous_linear_equiv`) we also prove `dimH (f '' s) = dimH s`. ### Hausdorff measure in `ℝⁿ` * `real.dimH_of_nonempty_interior`: if `s` is a set in a finite dimensional real vector space `E` with nonempty interior, then the Hausdorff dimension of `s` is equal to the dimension of `E`. * `dense_compl_of_dimH_lt_finrank`: if `s` is a set in a finite dimensional real vector space `E` with Hausdorff dimension strictly less than the dimension of `E`, the `s` has a dense complement. * `times_cont_diff.dense_compl_range_of_finrank_lt_finrank`: the complement to the range of a `C¹` smooth map is dense provided that the dimension of the domain is strictly less than the dimension of the codomain. ## Notations We use the following notation localized in `measure_theory`. It is defined in `measure_theory.measure.hausdorff`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes * The definition of `dimH` explicitly uses `borel X` as a measurable space structure. This way we can formulate lemmas about Hausdorff dimension without assuming that the environment has a `[measurable_space X]` instance that is equal but possibly not defeq to `borel X`. Lemma `dimH_def` unfolds this definition using whatever `[measurable_space X]` instance we have in the environment (as long as it is equal to `borel X`). * The definition `dimH` is irreducible; use API lemmas or `dimH_def` instead. ## Tags Hausdorff measure, Hausdorff dimension, dimension -/ open_locale measure_theory ennreal nnreal topological_space open measure_theory measure_theory.measure set topological_space finite_dimensional filter variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] /-- Hausdorff dimension of a set in an (e)metric space. -/ @[irreducible] noncomputable def dimH (s : set X) : ℝ≥0∞ := by letI := borel X; exact ⨆ (d : ℝ≥0) (hd : @hausdorff_measure X _ _ ⟨rfl⟩ d s = ∞), d /-! ### Basic properties -/ section measurable variables [measurable_space X] [borel_space X] /-- Unfold the definition of `dimH` using `[measurable_space X] [borel_space X]` from the environment. -/ lemma dimH_def (s : set X) : dimH s = ⨆ (d : ℝ≥0) (hd : μH[d] s = ∞), d := begin unfreezingI { obtain rfl : ‹measurable_space X› = borel X := borel_space.measurable_eq }, rw dimH end lemma hausdorff_measure_of_lt_dimH {s : set X} {d : ℝ≥0} (h : ↑d < dimH s) : μH[d] s = ∞ := begin simp only [dimH_def, lt_supr_iff] at h, rcases h with ⟨d', hsd', hdd'⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hdd', exact top_unique (hsd' ▸ hausdorff_measure_mono hdd'.le _) end lemma dimH_le {s : set X} {d : ℝ≥0∞} (H : ∀ d' : ℝ≥0, μH[d'] s = ∞ → ↑d' ≤ d) : dimH s ≤ d := (dimH_def s).trans_le $ bsupr_le H lemma dimH_le_of_hausdorff_measure_ne_top {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ ∞) : dimH s ≤ d := le_of_not_lt $ mt hausdorff_measure_of_lt_dimH h lemma le_dimH_of_hausdorff_measure_eq_top {s : set X} {d : ℝ≥0} (h : μH[d] s = ∞) : ↑d ≤ dimH s := by { rw dimH_def, exact le_bsupr d h } lemma hausdorff_measure_of_dimH_lt {s : set X} {d : ℝ≥0} (h : dimH s < d) : μH[d] s = 0 := begin rw dimH_def at h, rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨d', hsd', hd'd⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hd'd, exact (hausdorff_measure_zero_or_top hd'd s).resolve_right (λ h, hsd'.not_le (le_bsupr d' h)) end lemma measure_zero_of_dimH_lt {μ : measure X} {d : ℝ≥0} (h : μ ≪ μH[d]) {s : set X} (hd : dimH s < d) : μ s = 0 := h $ hausdorff_measure_of_dimH_lt hd lemma le_dimH_of_hausdorff_measure_ne_zero {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ 0) : ↑d ≤ dimH s := le_of_not_lt $ mt hausdorff_measure_of_dimH_lt h lemma dimH_of_hausdorff_measure_ne_zero_ne_top {d : ℝ≥0} {s : set X} (h : μH[d] s ≠ 0) (h' : μH[d] s ≠ ∞) : dimH s = d := le_antisymm (dimH_le_of_hausdorff_measure_ne_top h') (le_dimH_of_hausdorff_measure_ne_zero h) end measurable @[mono] lemma dimH_mono {s t : set X} (h : s ⊆ t) : dimH s ≤ dimH t := begin letI := borel X, haveI : borel_space X := ⟨rfl⟩, exact dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top $ top_unique $ hd ▸ measure_mono h) end lemma dimH_subsingleton {s : set X} (h : s.subsingleton) : dimH s = 0 := by simp [dimH, h.measure_zero] alias dimH_subsingleton ← set.subsingleton.dimH_zero @[simp] lemma dimH_empty : dimH (∅ : set X) = 0 := subsingleton_empty.dimH_zero @[simp] lemma dimH_singleton (x : X) : dimH ({x} : set X) = 0 := subsingleton_singleton.dimH_zero @[simp] lemma dimH_Union [encodable ι] (s : ι → set X) : dimH (⋃ i, s i) = ⨆ i, dimH (s i) := begin letI := borel X, haveI : borel_space X := ⟨rfl⟩, refine le_antisymm (dimH_le $ λ d hd, _) (supr_le $ λ i, dimH_mono $ subset_Union _ _), contrapose! hd, have : ∀ i, μH[d] (s i) = 0, from λ i, hausdorff_measure_of_dimH_lt ((le_supr (λ i, dimH (s i)) i).trans_lt hd), rw measure_Union_null this, exact ennreal.zero_ne_top end @[simp] lemma dimH_bUnion {s : set ι} (hs : countable s) (t : ι → set X) : dimH (⋃ i ∈ s, t i) = ⨆ i ∈ s, dimH (t i) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union, dimH_Union, ← supr_subtype''] end @[simp] lemma dimH_sUnion {S : set (set X)} (hS : countable S) : dimH (⋃₀ S) = ⨆ s ∈ S, dimH s := by rw [sUnion_eq_bUnion, dimH_bUnion hS] @[simp] lemma dimH_union (s t : set X) : dimH (s ∪ t) = max (dimH s) (dimH t) := by rw [union_eq_Union, dimH_Union, supr_bool_eq, cond, cond, ennreal.sup_eq_max] lemma dimH_countable {s : set X} (hs : countable s) : dimH s = 0 := bUnion_of_singleton s ▸ by simp only [dimH_bUnion hs, dimH_singleton, ennreal.supr_zero_eq_zero] alias dimH_countable ← set.countable.dimH_zero lemma dimH_finite {s : set X} (hs : finite s) : dimH s = 0 := hs.countable.dimH_zero alias dimH_finite ← set.finite.dimH_zero @[simp] lemma dimH_coe_finset (s : finset X) : dimH (s : set X) = 0 := s.finite_to_set.dimH_zero alias dimH_coe_finset ← finset.dimH_zero /-! ### Hausdorff dimension as the supremum of local Hausdorff dimensions -/ section variables [second_countable_topology X] /-- If `r` is less than the Hausdorff dimension of a set `s` in an (extended) metric space with second countable topology, then there exists a point `x ∈ s` such that every neighborhood `t` of `x` within `s` has Hausdorff dimension greater than `r`. -/ lemma exists_mem_nhds_within_lt_dimH_of_lt_dimH {s : set X} {r : ℝ≥0∞} (h : r < dimH s) : ∃ x ∈ s, ∀ t ∈ 𝓝[s] x, r < dimH t := begin contrapose! h, choose! t htx htr using h, rcases countable_cover_nhds_within htx with ⟨S, hSs, hSc, hSU⟩, calc dimH s ≤ dimH (⋃ x ∈ S, t x) : dimH_mono hSU ... = ⨆ x ∈ S, dimH (t x) : dimH_bUnion hSc _ ... ≤ r : bsupr_le (λ x hx, htr x (hSs hx)) end /-- In an (extended) metric space with second countable topology, the Hausdorff dimension of a set `s` is the supremum over `x ∈ s` of the limit superiors of `dimH t` along `(𝓝[s] x).lift' powerset`. -/ lemma bsupr_limsup_dimH (s : set X) : (⨆ x ∈ s, limsup ((𝓝[s] x).lift' powerset) dimH) = dimH s := begin refine le_antisymm (bsupr_le $ λ x hx, _) _, { refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _), exact eventually_lift'_powerset.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ }, { refine le_of_forall_ge_of_dense (λ r hr, _), rcases exists_mem_nhds_within_lt_dimH_of_lt_dimH hr with ⟨x, hxs, hxr⟩, refine le_bsupr_of_le x hxs _, rw limsup_eq, refine le_Inf (λ b hb, _), rcases eventually_lift'_powerset.1 hb with ⟨t, htx, ht⟩, exact (hxr t htx).le.trans (ht t subset.rfl) } end /-- In an (extended) metric space with second countable topology, the Hausdorff dimension of a set `s` is the supremum over all `x` of the limit superiors of `dimH t` along `(𝓝[s] x).lift' powerset`. -/ lemma supr_limsup_dimH (s : set X) : (⨆ x, limsup ((𝓝[s] x).lift' powerset) dimH) = dimH s := begin refine le_antisymm (supr_le $ λ x, _) _, { refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _), exact eventually_lift'_powerset.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ }, { rw ← bsupr_limsup_dimH, exact bsupr_le_supr _ _ } end end /-! ### Hausdorff dimension and Hölder continuity -/ variables {C K r : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f` is a Hölder continuous map with exponent `r > 0`, then `dimH (f '' s) ≤ dimH s / r`. -/ lemma holder_on_with.dimH_image_le (h : holder_on_with C r f s) (hr : 0 < r) : dimH (f '' s) ≤ dimH s / r := begin letI := borel X, haveI : borel_space X := ⟨rfl⟩, letI := borel Y, haveI : borel_space Y := ⟨rfl⟩, refine dimH_le (λ d hd, _), have := h.hausdorff_measure_image_le hr d.coe_nonneg, rw [hd, ennreal.coe_rpow_of_nonneg _ d.coe_nonneg, top_le_iff] at this, have Hrd : μH[(r * d : ℝ≥0)] s = ⊤, { contrapose this, exact ennreal.mul_ne_top ennreal.coe_ne_top this }, rw [ennreal.le_div_iff_mul_le, mul_comm, ← ennreal.coe_mul], exacts [le_dimH_of_hausdorff_measure_eq_top Hrd, or.inl (mt ennreal.coe_eq_zero.1 hr.ne'), or.inl ennreal.coe_ne_top] end namespace holder_with /-- If `f : X → Y` is Hölder continuous with a positive exponent `r`, then the Hausdorff dimension of the image of a set `s` is at most `dimH s / r`. -/ lemma dimH_image_le (h : holder_with C r f) (hr : 0 < r) (s : set X) : dimH (f '' s) ≤ dimH s / r := (h.holder_on_with s).dimH_image_le hr /-- If `f` is a Hölder continuous map with exponent `r > 0`, then the Hausdorff dimension of its range is at most the Hausdorff dimension of its domain divided by `r`. -/ lemma dimH_range_le (h : holder_with C r f) (hr : 0 < r) : dimH (range f) ≤ dimH (univ : set X) / r := @image_univ _ _ f ▸ h.dimH_image_le hr univ end holder_with /-- If `s` is a set in a space `X` with second countable topology and `f : X → Y` is Hölder continuous in a neighborhood within `s` of every point `x ∈ s` with the same positive exponent `r` but possibly different coefficients, then the Hausdorff dimension of the image `f '' s` is at most the Hausdorff dimension of `s` divided by `r`. -/ lemma dimH_image_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y} (hr : 0 < r) {s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C r f t) : dimH (f '' s) ≤ dimH s / r := begin choose! C t htn hC using hf, rcases countable_cover_nhds_within htn with ⟨u, hus, huc, huU⟩, replace huU := inter_eq_self_of_subset_left huU, rw inter_bUnion at huU, rw [← huU, image_bUnion, dimH_bUnion huc, dimH_bUnion huc], simp only [ennreal.supr_div], exact bsupr_le_bsupr (λ x hx, ((hC x (hus hx)).mono (inter_subset_right _ _)).dimH_image_le hr) end /-- If `f : X → Y` is Hölder continuous in a neighborhood of every point `x : X` with the same positive exponent `r` but possibly different coefficients, then the Hausdorff dimension of the range of `f` is at most the Hausdorff dimension of `X` divided by `r`. -/ lemma dimH_range_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y} (hr : 0 < r) (hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), holder_on_with C r f s) : dimH (range f) ≤ dimH (univ : set X) / r := begin rw ← image_univ, refine dimH_image_le_of_locally_holder_on hr (λ x _, _), simpa only [exists_prop, nhds_within_univ] using hf x end /-! ### Hausdorff dimension and Lipschitz continuity -/ /-- If `f : X → Y` is Lipschitz continuous on `s`, then `dimH (f '' s) ≤ dimH s`. -/ lemma lipschitz_on_with.dimH_image_le (h : lipschitz_on_with K f s) : dimH (f '' s) ≤ dimH s := by simpa using h.holder_on_with.dimH_image_le zero_lt_one namespace lipschitz_with /-- If `f` is a Lipschitz continuous map, then `dimH (f '' s) ≤ dimH s`. -/ lemma dimH_image_le (h : lipschitz_with K f) (s : set X) : dimH (f '' s) ≤ dimH s := (h.lipschitz_on_with s).dimH_image_le /-- If `f` is a Lipschitz continuous map, then the Hausdorff dimension of its range is at most the Hausdorff dimension of its domain. -/ lemma dimH_range_le (h : lipschitz_with K f) : dimH (range f) ≤ dimH (univ : set X) := @image_univ _ _ f ▸ h.dimH_image_le univ end lipschitz_with /-- If `s` is a set in an extended metric space `X` with second countable topology and `f : X → Y` is Lipschitz in a neighborhood within `s` of every point `x ∈ s`, then the Hausdorff dimension of the image `f '' s` is at most the Hausdorff dimension of `s`. -/ lemma dimH_image_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y} {s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), lipschitz_on_with C f t) : dimH (f '' s) ≤ dimH s := begin have : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C 1 f t, by simpa only [holder_on_with_one] using hf, simpa only [ennreal.coe_one, ennreal.div_one] using dimH_image_le_of_locally_holder_on zero_lt_one this end /-- If `f : X → Y` is Lipschitz in a neighborhood of each point `x : X`, then the Hausdorff dimension of `range f` is at most the Hausdorff dimension of `X`. -/ lemma dimH_range_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y} (hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), lipschitz_on_with C f s) : dimH (range f) ≤ dimH (univ : set X) := begin rw ← image_univ, refine dimH_image_le_of_locally_lipschitz_on (λ x _, _), simpa only [exists_prop, nhds_within_univ] using hf x end namespace antilipschitz_with lemma dimH_preimage_le (hf : antilipschitz_with K f) (s : set Y) : dimH (f ⁻¹' s) ≤ dimH s := begin letI := borel X, haveI : borel_space X := ⟨rfl⟩, letI := borel Y, haveI : borel_space Y := ⟨rfl⟩, refine dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top _), have := hf.hausdorff_measure_preimage_le d.coe_nonneg s, rw [hd, top_le_iff] at this, contrapose! this, exact ennreal.mul_ne_top (by simp) this end lemma le_dimH_image (hf : antilipschitz_with K f) (s : set X) : dimH s ≤ dimH (f '' s) := calc dimH s ≤ dimH (f ⁻¹' (f '' s)) : dimH_mono (subset_preimage_image _ _) ... ≤ dimH (f '' s) : hf.dimH_preimage_le _ end antilipschitz_with /-! ### Isometries preserve Hausdorff dimension -/ lemma isometry.dimH_image (hf : isometry f) (s : set X) : dimH (f '' s) = dimH s := le_antisymm (hf.lipschitz.dimH_image_le _) (hf.antilipschitz.le_dimH_image _) namespace isometric @[simp] lemma dimH_image (e : X ≃ᵢ Y) (s : set X) : dimH (e '' s) = dimH s := e.isometry.dimH_image s @[simp] lemma dimH_preimage (e : X ≃ᵢ Y) (s : set Y) : dimH (e ⁻¹' s) = dimH s := by rw [← e.image_symm, e.symm.dimH_image] lemma dimH_univ (e : X ≃ᵢ Y) : dimH (univ : set X) = dimH (univ : set Y) := by rw [← e.dimH_preimage univ, preimage_univ] end isometric namespace continuous_linear_equiv variables {𝕜 E F : Type*} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] @[simp] lemma dimH_image (e : E ≃L[𝕜] F) (s : set E) : dimH (e '' s) = dimH s := le_antisymm (e.lipschitz.dimH_image_le s) $ by simpa only [e.symm_image_image] using e.symm.lipschitz.dimH_image_le (e '' s) @[simp] lemma dimH_preimage (e : E ≃L[𝕜] F) (s : set F) : dimH (e ⁻¹' s) = dimH s := by rw [← e.image_symm_eq_preimage, e.symm.dimH_image] lemma dimH_univ (e : E ≃L[𝕜] F) : dimH (univ : set E) = dimH (univ : set F) := by rw [← e.dimH_preimage, preimage_univ] end continuous_linear_equiv /-! ### Hausdorff dimension in a real vector space -/ namespace real variables {E : Type*} [fintype ι] [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] theorem dimH_ball_pi (x : ι → ℝ) {r : ℝ} (hr : 0 < r) : dimH (metric.ball x r) = fintype.card ι := begin casesI is_empty_or_nonempty ι, { rwa [dimH_subsingleton, eq_comm, nat.cast_eq_zero, fintype.card_eq_zero_iff], exact λ x _ y _, subsingleton.elim x y }, { rw ← ennreal.coe_nat, have : μH[fintype.card ι] (metric.ball x r) = ennreal.of_real ((2 * r) ^ fintype.card ι), by rw [hausdorff_measure_pi_real, real.volume_pi_ball _ hr], refine dimH_of_hausdorff_measure_ne_zero_ne_top _ _; rw [nnreal.coe_nat_cast, this], { simp [pow_pos (mul_pos zero_lt_two hr)] }, { exact ennreal.of_real_ne_top } } end theorem dimH_ball_pi_fin {n : ℕ} (x : fin n → ℝ) {r : ℝ} (hr : 0 < r) : dimH (metric.ball x r) = n := by rw [dimH_ball_pi x hr, fintype.card_fin] theorem dimH_univ_pi (ι : Type*) [fintype ι] : dimH (univ : set (ι → ℝ)) = fintype.card ι := by simp only [← metric.Union_ball_nat_succ (0 : ι → ℝ), dimH_Union, dimH_ball_pi _ (nat.cast_add_one_pos _), supr_const] theorem dimH_univ_pi_fin (n : ℕ) : dimH (univ : set (fin n → ℝ)) = n := by rw [dimH_univ_pi, fintype.card_fin] theorem dimH_of_mem_nhds {x : E} {s : set E} (h : s ∈ 𝓝 x) : dimH s = finrank ℝ E := begin have e : E ≃L[ℝ] (fin (finrank ℝ E) → ℝ), from continuous_linear_equiv.of_finrank_eq (finite_dimensional.finrank_fin_fun ℝ).symm, rw ← e.dimH_image, refine le_antisymm _ _, { exact (dimH_mono (subset_univ _)).trans_eq (dimH_univ_pi_fin _) }, { have : e '' s ∈ 𝓝 (e x), by { rw ← e.map_nhds_eq, exact image_mem_map h }, rcases metric.nhds_basis_ball.mem_iff.1 this with ⟨r, hr0, hr⟩, simpa only [dimH_ball_pi_fin (e x) hr0] using dimH_mono hr } end theorem dimH_of_nonempty_interior {s : set E} (h : (interior s).nonempty) : dimH s = finrank ℝ E := let ⟨x, hx⟩ := h in dimH_of_mem_nhds (mem_interior_iff_mem_nhds.1 hx) variable (E) theorem dimH_univ_eq_finrank : dimH (univ : set E) = finrank ℝ E := dimH_of_mem_nhds (@univ_mem _ (𝓝 0)) theorem dimH_univ : dimH (univ : set ℝ) = 1 := by rw [dimH_univ_eq_finrank ℝ, finite_dimensional.finrank_self, nat.cast_one] end real variables {E F : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] [normed_group F] [normed_space ℝ F] theorem dense_compl_of_dimH_lt_finrank {s : set E} (hs : dimH s < finrank ℝ E) : dense sᶜ := begin refine λ x, mem_closure_iff_nhds.2 (λ t ht, ne_empty_iff_nonempty.1 $ λ he, hs.not_le _), rw [← diff_eq, diff_eq_empty] at he, rw [← real.dimH_of_mem_nhds ht], exact dimH_mono he end /-! ### Hausdorff dimension and `C¹`-smooth maps `C¹`-smooth maps are locally Lipschitz continuous, hence they do not increase the Hausdorff dimension of sets. -/ /-- Let `f` be a function defined on a finite dimensional real normed space. If `f` is `C¹`-smooth on a convex set `s`, then the Hausdorff dimension of `f '' s` is less than or equal to the Hausdorff dimension of `s`. TODO: do we actually need `convex ℝ s`? -/ lemma times_cont_diff_on.dimH_image_le {f : E → F} {s t : set E} (hf : times_cont_diff_on ℝ 1 f s) (hc : convex ℝ s) (ht : t ⊆ s) : dimH (f '' t) ≤ dimH t := dimH_image_le_of_locally_lipschitz_on $ λ x hx, let ⟨C, u, hu, hf⟩ := (hf x (ht hx)).exists_lipschitz_on_with hc in ⟨C, u, nhds_within_mono _ ht hu, hf⟩ /-- The Hausdorff dimension of the range of a `C¹`-smooth function defined on a finite dimensional real normed space is at most the dimension of its domain as a vector space over `ℝ`. -/ lemma times_cont_diff.dimH_range_le {f : E → F} (h : times_cont_diff ℝ 1 f) : dimH (range f) ≤ finrank ℝ E := calc dimH (range f) = dimH (f '' univ) : by rw image_univ ... ≤ dimH (univ : set E) : h.times_cont_diff_on.dimH_image_le convex_univ subset.rfl ... = finrank ℝ E : real.dimH_univ_eq_finrank E /-- A particular case of Sard's Theorem. Let `f : E → F` be a map between finite dimensional real vector spaces. Suppose that `f` is `C¹` smooth on a convex set `s` of Hausdorff dimension strictly less than the dimension of `F`. Then the complement of the image `f '' s` is dense in `F`. -/ lemma times_cont_diff_on.dense_compl_image_of_dimH_lt_finrank [finite_dimensional ℝ F] {f : E → F} {s t : set E} (h : times_cont_diff_on ℝ 1 f s) (hc : convex ℝ s) (ht : t ⊆ s) (htF : dimH t < finrank ℝ F) : dense (f '' t)ᶜ := dense_compl_of_dimH_lt_finrank $ (h.dimH_image_le hc ht).trans_lt htF /-- A particular case of Sard's Theorem. If `f` is a `C¹` smooth map from a real vector space to a real vector space `F` of strictly larger dimension, then the complement of the range of `f` is dense in `F`. -/ lemma times_cont_diff.dense_compl_range_of_finrank_lt_finrank [finite_dimensional ℝ F] {f : E → F} (h : times_cont_diff ℝ 1 f) (hEF : finrank ℝ E < finrank ℝ F) : dense (range f)ᶜ := dense_compl_of_dimH_lt_finrank $ h.dimH_range_le.trans_lt $ ennreal.coe_nat_lt_coe_nat.2 hEF
f082c35c417332ece730f48233df32ec3dadac85
f57570f33b51ef0271f8c366142363d5ae8fff45
/src/lambda_calculus.lean
6af37f2d856adf49b436903a9815b8eea9ec69a7
[]
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
902
lean
import predicate_logic universe u open logic list section lambda parameters {sort : Type u} [decidable_eq sort] parameter {σ : @signature sort _} local notation `pre_term` := @pre_term sort _ σ local notation `var` := @tvariable sort _ σ inductive lambda_pre_term | base : pre_term → lambda_pre_term | lambda : var → lambda_pre_term → lambda_pre_term | app : lambda_pre_term → lambda_pre_term → lambda_pre_term def free_variables : lambda_pre_term → set var | (lambda_pre_term.base t) := pre_term.variables t | (lambda_pre_term.lambda x t) := free_variables t - {x} | (lambda_pre_term.app t₁ t₂) := free_variables t₁ ∪ free_variables t₂ def lambda.typing : lambda_pre_term → list sort | (lambda_pre_term.base t) := [typing t] | (lambda_pre_term.lambda ⟨s, _, _⟩ t) := s :: lambda.typing t | (lambda_pre_term.app t₁ t₂) := tail (lambda.typing t₁) end lambda
67fe132d43c24954bd762fbc9fcafe3ad9765637
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Data/HashMap.lean
4b2dfab2deaf51db5e7e492611ed1a863ca05241
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
9,288
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Data.AssocList namespace Lean def HashMapBucket (α : Type u) (β : Type v) := { b : Array (AssocList α β) // b.size.isPowerOfTwo } def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β := ⟨ data.val.uset i d h, by erw [Array.size_set]; apply data.property ⟩ structure HashMapImp (α : Type u) (β : Type v) where size : Nat buckets : HashMapBucket α β private def numBucketsForCapacity (capacity : Nat) : Nat := -- a "load factor" of 0.75 is the usual standard for hash maps capacity * 4 / 3 def mkHashMapImp {α : Type u} {β : Type v} (capacity := 8) : HashMapImp α β := { size := 0 buckets := ⟨mkArray (numBucketsForCapacity capacity).nextPowerOfTwo AssocList.nil, by simp; apply Nat.isPowerOfTwo_nextPowerOfTwo⟩ } namespace HashMapImp variable {α : Type u} {β : Type v} /- Remark: we use a C implementation because this function is performance critical. -/ @[extern "lean_data_hashmap_mk_idx"] private def mkIdx {sz : Nat} (hash : UInt64) (h : sz.isPowerOfTwo) : { u : USize // u.toNat < sz } := -- TODO: avoid `if` in the reference implementation let u := hash.toUSize &&& (sz.toUSize - 1) if h' : u.toNat < sz then ⟨u, h'⟩ else ⟨0, by simp [USize.toNat, OfNat.ofNat, USize.ofNat, Fin.ofNat']; rw [Nat.zero_mod]; apply Nat.pos_of_isPowerOfTwo h⟩ @[inline] def reinsertAux (hashFn : α → UInt64) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β := let ⟨i, h⟩ := mkIdx (hashFn a) data.property data.update i (AssocList.cons a b data.val[i]) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ := data.val.foldlM (init := d) fun d b => b.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ := foldBuckets m.buckets d f @[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (f : α → β → m PUnit) : m PUnit := data.val.forM fun b => b.forM f @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMapImp α β) : m PUnit := forBucketsM h.buckets f def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property buckets.val[i].findEntry? a def find? [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property buckets.val[i].find? a def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property buckets.val[i].contains a def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : AssocList α β := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx AssocList.nil let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target termination_by _ i source _ => source.size - i def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β := let bucketsNew : HashMapBucket α β := ⟨ mkArray (buckets.val.size * 2) AssocList.nil, by simp; apply Nat.mul2_isPowerOfTwo_of_isPowerOfTwo buckets.property ⟩ { size := size, buckets := moveEntries 0 buckets.val bucketsNew } @[inline] def insert [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β × Bool := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property let bkt := buckets.val[i] if bkt.contains a then (⟨size, buckets.update i (bkt.replace a b) h⟩, true) else let size' := size + 1 let buckets' := buckets.update i (AssocList.cons a b bkt) h if numBucketsForCapacity size' ≤ buckets.val.size then ({ size := size', buckets := buckets' }, false) else (expand size' buckets', false) def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property let bkt := buckets.val[i] if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where | mkWff : ∀ n, WellFormed (mkHashMapImp n) | insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b |>.1) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashMapImp def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := { m : HashMapImp α β // m.WellFormed } open Lean.HashMapImp def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (capacity := 8) : HashMap α β := ⟨ mkHashMapImp capacity, WellFormed.mkWff capacity ⟩ namespace HashMap instance [BEq α] [Hashable α] : Inhabited (HashMap α β) where default := mkHashMap instance [BEq α] [Hashable α] : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ @[inline] def empty [BEq α] [Hashable α] : HashMap α β := mkHashMap variable {α : Type u} {β : Type v} {_ : BEq α} {_ : Hashable α} def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β := match m with | ⟨ m, hw ⟩ => match h:m.insert a b with | (m', _) => ⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩ /-- Similar to `insert`, but also returns a Boolean flad indicating whether an existing entry has been replaced with `a -> b`. -/ def insert' (m : HashMap α β) (a : α) (b : β) : HashMap α β × Bool := match m with | ⟨ m, hw ⟩ => match h:m.insert a b with | (m', replaced) => (⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩, replaced) @[inline] def erase (m : HashMap α β) (a : α) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) := match m with | ⟨ m, _ ⟩ => m.findEntry? a @[inline] def find? (m : HashMap α β) (a : α) : Option β := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" instance : GetElem (HashMap α β) α (Option β) fun _ _ => True where getElem m k _ := m.find? k @[inline] def contains (m : HashMap α β) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMap α β) : m PUnit := match h with | ⟨ h, _ ⟩ => h.forM f @[inline] def size (m : HashMap α β) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashMap α β) : Bool := m.size = 0 def toList (m : HashMap α β) : List (α × β) := m.fold (init := []) fun r k v => (k, v)::r def toArray (m : HashMap α β) : Array (α × β) := m.fold (init := #[]) fun r k v => r.push (k, v) def numBuckets (m : HashMap α β) : Nat := m.val.buckets.val.size /-- Builds a `HashMap` from a list of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. -/ def ofList (l : List (α × β)) : HashMap α β := l.foldl (init := HashMap.empty) (fun m p => m.insert p.fst p.snd) /-- Variant of `ofList` which accepts a function that combines values of duplicated keys. -/ def ofListWith (l : List (α × β)) (f : β → β → β) : HashMap α β := l.foldl (init := HashMap.empty) (fun m p => match m.find? p.fst with | none => m.insert p.fst p.snd | some v => m.insert p.fst $ f v p.snd)
498ee60c76064e3b8ecd86848c3bb38d989d2717
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/analysis/topology.lean
60e14566cc3078a4b8266d07d8d7c37e0d64c876
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
8,235
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Computational realization of topological spaces (experimental). -/ import topology.bases import data.analysis.filter open set open filter (hiding realizer) open_locale topological_space /-- A `ctop α σ` is a realization of a topology (basis) on `α`, represented by a type `σ` together with operations for the top element and the intersection operation. -/ structure ctop (α σ : Type*) := (f : σ → set α) (top : α → σ) (top_mem : ∀ x : α, x ∈ f (top x)) (inter : Π a b (x : α), x ∈ f a ∩ f b → σ) (inter_mem : ∀ a b x h, x ∈ f (inter a b x h)) (inter_sub : ∀ a b x h, f (inter a b x h) ⊆ f a ∩ f b) variables {α : Type*} {β : Type*} {σ : Type*} {τ : Type*} namespace ctop section variables (F : ctop α σ) instance : has_coe_to_fun (ctop α σ) := ⟨_, ctop.f⟩ @[simp] theorem coe_mk (f T h₁ I h₂ h₃ a) : (@ctop.mk α σ f T h₁ I h₂ h₃) a = f a := rfl /-- Map a ctop to an equivalent representation type. -/ def of_equiv (E : σ ≃ τ) : ctop α σ → ctop α τ | ⟨f, T, h₁, I, h₂, h₃⟩ := { f := λ a, f (E.symm a), top := λ x, E (T x), top_mem := λ x, by simpa using h₁ x, inter := λ a b x h, E (I (E.symm a) (E.symm b) x h), inter_mem := λ a b x h, by simpa using h₂ (E.symm a) (E.symm b) x h, inter_sub := λ a b x h, by simpa using h₃ (E.symm a) (E.symm b) x h } @[simp] theorem of_equiv_val (E : σ ≃ τ) (F : ctop α σ) (a : τ) : F.of_equiv E a = F (E.symm a) := by cases F; refl end /-- Every `ctop` is a topological space. -/ def to_topsp (F : ctop α σ) : topological_space α := topological_space.generate_from (set.range F.f) theorem to_topsp_is_topological_basis (F : ctop α σ) : @topological_space.is_topological_basis _ F.to_topsp (set.range F.f) := ⟨λ u ⟨a, e₁⟩ v ⟨b, e₂⟩, e₁ ▸ e₂ ▸ λ x h, ⟨_, ⟨_, rfl⟩, F.inter_mem a b x h, F.inter_sub a b x h⟩, eq_univ_iff_forall.2 $ λ x, ⟨_, ⟨_, rfl⟩, F.top_mem x⟩, rfl⟩ @[simp] theorem mem_nhds_to_topsp (F : ctop α σ) {s : set α} {a : α} : s ∈ @nhds _ F.to_topsp a ↔ ∃ b, a ∈ F b ∧ F b ⊆ s := (@topological_space.mem_nhds_of_is_topological_basis _ F.to_topsp _ _ _ F.to_topsp_is_topological_basis).trans $ ⟨λ ⟨_, ⟨x, rfl⟩, h⟩, ⟨x, h⟩, λ ⟨x, h⟩, ⟨_, ⟨x, rfl⟩, h⟩⟩ end ctop /-- A `ctop` realizer for the topological space `T` is a `ctop` which generates `T`. -/ structure ctop.realizer (α) [T : topological_space α] := (σ : Type*) (F : ctop α σ) (eq : F.to_topsp = T) open ctop protected def ctop.to_realizer (F : ctop α σ) : @ctop.realizer _ F.to_topsp := @ctop.realizer.mk _ F.to_topsp σ F rfl namespace ctop.realizer protected theorem is_basis [T : topological_space α] (F : realizer α) : topological_space.is_topological_basis (set.range F.F.f) := by have := to_topsp_is_topological_basis F.F; rwa F.eq at this protected theorem mem_nhds [T : topological_space α] (F : realizer α) {s : set α} {a : α} : s ∈ 𝓝 a ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := by have := mem_nhds_to_topsp F.F; rwa F.eq at this theorem is_open_iff [topological_space α] (F : realizer α) {s : set α} : is_open s ↔ ∀ a ∈ s, ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := is_open_iff_mem_nhds.trans $ ball_congr $ λ a h, F.mem_nhds theorem is_closed_iff [topological_space α] (F : realizer α) {s : set α} : is_closed s ↔ ∀ a, (∀ b, a ∈ F.F b → ∃ z, z ∈ F.F b ∩ s) → a ∈ s := F.is_open_iff.trans $ forall_congr $ λ a, show (a ∉ s → (∃ (b : F.σ), a ∈ F.F b ∧ ∀ z ∈ F.F b, z ∉ s)) ↔ _, by haveI := classical.prop_decidable; rw [not_imp_comm]; simp [not_exists, not_and, not_forall, and_comm] theorem mem_interior_iff [topological_space α] (F : realizer α) {s : set α} {a : α} : a ∈ interior s ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := mem_interior_iff_mem_nhds.trans F.mem_nhds protected theorem is_open [topological_space α] (F : realizer α) (s : F.σ) : is_open (F.F s) := is_open_iff_nhds.2 $ λ a m, by simpa using F.mem_nhds.2 ⟨s, m, subset.refl _⟩ theorem ext' [T : topological_space α] {σ : Type*} {F : ctop α σ} (H : ∀ a s, s ∈ 𝓝 a ↔ ∃ b, a ∈ F b ∧ F b ⊆ s) : F.to_topsp = T := begin refine eq_of_nhds_eq_nhds (λ x, _), ext s, rw [mem_nhds_to_topsp, H] end theorem ext [T : topological_space α] {σ : Type*} {F : ctop α σ} (H₁ : ∀ a, is_open (F a)) (H₂ : ∀ a s, s ∈ 𝓝 a → ∃ b, a ∈ F b ∧ F b ⊆ s) : F.to_topsp = T := ext' $ λ a s, ⟨H₂ a s, λ ⟨b, h₁, h₂⟩, mem_nhds_sets_iff.2 ⟨_, h₂, H₁ _, h₁⟩⟩ variable [topological_space α] protected def id : realizer α := ⟨{x:set α // is_open x}, { f := subtype.val, top := λ _, ⟨univ, is_open_univ⟩, top_mem := mem_univ, inter := λ ⟨x, h₁⟩ ⟨y, h₂⟩ a h₃, ⟨_, is_open_inter h₁ h₂⟩, inter_mem := λ ⟨x, h₁⟩ ⟨y, h₂⟩ a, id, inter_sub := λ ⟨x, h₁⟩ ⟨y, h₂⟩ a h₃, subset.refl _ }, ext subtype.property $ λ x s h, let ⟨t, h, o, m⟩ := mem_nhds_sets_iff.1 h in ⟨⟨t, o⟩, m, h⟩⟩ def of_equiv (F : realizer α) (E : F.σ ≃ τ) : realizer α := ⟨τ, F.F.of_equiv E, ext' (λ a s, F.mem_nhds.trans $ ⟨λ ⟨s, h⟩, ⟨E s, by simpa using h⟩, λ ⟨t, h⟩, ⟨E.symm t, by simpa using h⟩⟩)⟩ @[simp] theorem of_equiv_σ (F : realizer α) (E : F.σ ≃ τ) : (F.of_equiv E).σ = τ := rfl @[simp] theorem of_equiv_F (F : realizer α) (E : F.σ ≃ τ) (s : τ) : (F.of_equiv E).F s = F.F (E.symm s) := by delta of_equiv; simp protected def nhds (F : realizer α) (a : α) : (𝓝 a).realizer := ⟨{s : F.σ // a ∈ F.F s}, { f := λ s, F.F s.1, pt := ⟨_, F.F.top_mem a⟩, inf := λ ⟨x, h₁⟩ ⟨y, h₂⟩, ⟨_, F.F.inter_mem x y a ⟨h₁, h₂⟩⟩, inf_le_left := λ ⟨x, h₁⟩ ⟨y, h₂⟩ z h, (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).1, inf_le_right := λ ⟨x, h₁⟩ ⟨y, h₂⟩ z h, (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).2 }, filter_eq $ set.ext $ λ x, ⟨λ ⟨⟨s, as⟩, h⟩, mem_nhds_sets_iff.2 ⟨_, h, F.is_open _, as⟩, λ h, let ⟨s, h, as⟩ := F.mem_nhds.1 h in ⟨⟨s, h⟩, as⟩⟩⟩ @[simp] theorem nhds_σ (m : α → β) (F : realizer α) (a : α) : (F.nhds a).σ = {s : F.σ // a ∈ F.F s} := rfl @[simp] theorem nhds_F (m : α → β) (F : realizer α) (a : α) (s) : (F.nhds a).F s = F.F s.1 := rfl theorem tendsto_nhds_iff {m : β → α} {f : filter β} (F : f.realizer) (R : realizer α) {a : α} : tendsto m f (𝓝 a) ↔ ∀ t, a ∈ R.F t → ∃ s, ∀ x ∈ F.F s, m x ∈ R.F t := (F.tendsto_iff _ (R.nhds a)).trans subtype.forall end ctop.realizer structure locally_finite.realizer [topological_space α] (F : realizer α) (f : β → set α) := (bas : ∀ a, {s // a ∈ F.F s}) (sets : ∀ x:α, fintype {i | (f i ∩ F.F (bas x)).nonempty}) theorem locally_finite.realizer.to_locally_finite [topological_space α] {F : realizer α} {f : β → set α} (R : locally_finite.realizer F f) : locally_finite f := λ a, ⟨_, F.mem_nhds.2 ⟨(R.bas a).1, (R.bas a).2, subset.refl _⟩, ⟨R.sets a⟩⟩ theorem locally_finite_iff_exists_realizer [topological_space α] (F : realizer α) {f : β → set α} : locally_finite f ↔ nonempty (locally_finite.realizer F f) := ⟨λ h, let ⟨g, h₁⟩ := classical.axiom_of_choice h, ⟨g₂, h₂⟩ := classical.axiom_of_choice (λ x, show ∃ (b : F.σ), x ∈ (F.F) b ∧ (F.F) b ⊆ g x, from let ⟨h, h'⟩ := h₁ x in F.mem_nhds.1 h) in ⟨⟨λ x, ⟨g₂ x, (h₂ x).1⟩, λ x, finite.fintype $ let ⟨h, h'⟩ := h₁ x in h'.subset $ λ i hi, hi.mono (inter_subset_inter_right _ (h₂ x).2)⟩⟩, λ ⟨R⟩, R.to_locally_finite⟩ def compact.realizer [topological_space α] (R : realizer α) (s : set α) := ∀ {f : filter α} (F : f.realizer) (x : F.σ), f ≠ ⊥ → F.F x ⊆ s → {a // a∈s ∧ 𝓝 a ⊓ f ≠ ⊥}
e0ddca41279da413e407854e35c2dec1e9d8c3b5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/monotonicity/lemmas.lean
5902c2db98b674e3399813a33bfc3c5f16eb3dff
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,679
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity.basic import algebra.order.ring import data.set.lattice import order.bounds variables {α : Type*} @[mono] lemma mul_mono_nonneg {x y z : α} [ordered_semiring α] (h' : 0 ≤ z) (h : x ≤ y) : x * z ≤ y * z := by apply mul_le_mul_of_nonneg_right; assumption lemma lt_of_mul_lt_mul_neg_right {a b c : α} [linear_ordered_ring α] (h : a * c < b * c) (hc : c ≤ 0) : b < a := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos hc, have h2 : -(b * c) < -(a * c), from neg_lt_neg h, have h3 : b * (-c) < a * (-c), from calc b * (-c) = - (b * c) : by rewrite neg_mul_eq_mul_neg ... < - (a * c) : h2 ... = a * (-c) : by rewrite neg_mul_eq_mul_neg, lt_of_mul_lt_mul_right h3 nhc @[mono] lemma mul_mono_nonpos {x y z : α} [linear_ordered_ring α] (h' : z ≤ 0) (h : y ≤ x) : x * z ≤ y * z := begin classical, by_contradiction h'', revert h, apply not_le_of_lt, apply lt_of_mul_lt_mul_neg_right _ h', apply lt_of_not_ge h'' end @[mono] lemma nat.sub_mono_left_strict {x y z : ℕ} (h' : z ≤ x) (h : x < y) : x - z < y - z := begin have : z ≤ y, { transitivity, assumption, apply le_of_lt h, }, apply @nat.lt_of_add_lt_add_left z, rw [add_tsub_cancel_of_le,add_tsub_cancel_of_le]; solve_by_elim end @[mono] lemma nat.sub_mono_right_strict {x y z : ℕ} (h' : x ≤ z) (h : y < x) : z - x < z - y := begin have h'' : y ≤ z, { transitivity, apply le_of_lt h, assumption }, apply @nat.lt_of_add_lt_add_right _ x, rw [tsub_add_cancel_of_le h'], apply @lt_of_le_of_lt _ _ _ (z - y + y), rw [tsub_add_cancel_of_le h''], apply nat.add_lt_add_left h end open set attribute [mono] inter_subset_inter union_subset_union sUnion_mono bUnion_mono sInter_subset_sInter bInter_mono image_subset preimage_mono prod_mono monotone_prod seq_mono image2_subset order_embedding.monotone attribute [mono] upper_bounds_mono_set lower_bounds_mono_set upper_bounds_mono_mem lower_bounds_mono_mem upper_bounds_mono lower_bounds_mono bdd_above.mono bdd_below.mono attribute [mono] add_le_add mul_le_mul neg_le_neg mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right imp_imp_imp le_implies_le_of_le_of_le sub_le_sub tsub_le_tsub tsub_le_tsub_right abs_le_abs sup_le_sup inf_le_inf attribute [mono left] add_lt_add_of_le_of_lt mul_lt_mul' attribute [mono right] add_lt_add_of_lt_of_le mul_lt_mul
a978f2eaf46949e7a7bd144e3036b34ca82e0c9d
649957717d58c43b5d8d200da34bf374293fe739
/src/category_theory/monoidal/functor.lean
5c54126e27321971a4c5fe0b3718e232d43dcc86
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
6,668
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Michael Jendrusch, Scott Morrison import category_theory.monoidal.category open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory.category open category_theory.functor namespace category_theory section open monoidal_category variables (C : Type u₁) [𝒞 : monoidal_category.{v₁} C] (D : Type u₂) [𝒟 : monoidal_category.{v₂} D] include 𝒞 𝒟 structure lax_monoidal_functor extends C ⥤ D := -- unit morphism (ε : tensor_unit D ⟶ obj (tensor_unit C)) -- tensorator (μ : Π X Y : C, (obj X) ⊗ (obj Y) ⟶ obj (X ⊗ Y)) (μ_natural' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), ((map f) ⊗ (map g)) ≫ μ Y Y' = μ X X' ≫ map (f ⊗ g) . obviously) -- associativity of the tensorator (associativity' : ∀ (X Y Z : C), (μ X Y ⊗ 𝟙 (obj Z)) ≫ μ (X ⊗ Y) Z ≫ map (associator X Y Z).hom = (associator (obj X) (obj Y) (obj Z)).hom ≫ (𝟙 (obj X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) . obviously) -- unitality (left_unitality' : ∀ X : C, (left_unitor (obj X)).hom = (ε ⊗ 𝟙 (obj X)) ≫ μ (tensor_unit C) X ≫ map (left_unitor X).hom . obviously) (right_unitality' : ∀ X : C, (right_unitor (obj X)).hom = (𝟙 (obj X) ⊗ ε) ≫ μ X (tensor_unit C) ≫ map (right_unitor X).hom . obviously) restate_axiom lax_monoidal_functor.μ_natural' attribute [simp] lax_monoidal_functor.μ_natural restate_axiom lax_monoidal_functor.left_unitality' attribute [simp] lax_monoidal_functor.left_unitality restate_axiom lax_monoidal_functor.right_unitality' attribute [simp] lax_monoidal_functor.right_unitality restate_axiom lax_monoidal_functor.associativity' attribute [simp] lax_monoidal_functor.associativity -- When `rewrite_search` lands, add @[search] attributes to -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity structure monoidal_functor extends lax_monoidal_functor.{v₁ v₂} C D := (ε_is_iso : is_iso ε . obviously) (μ_is_iso : Π X Y : C, is_iso (μ X Y) . obviously) attribute [instance] monoidal_functor.ε_is_iso monoidal_functor.μ_is_iso variables {C D} def monoidal_functor.ε_iso (F : monoidal_functor.{v₁ v₂} C D) : tensor_unit D ≅ F.obj (tensor_unit C) := as_iso F.ε def monoidal_functor.μ_iso (F : monoidal_functor.{v₁ v₂} C D) (X Y : C) : (F.obj X) ⊗ (F.obj Y) ≅ F.obj (X ⊗ Y) := as_iso (F.μ X Y) end open monoidal_category namespace monoidal_functor section -- In order to express the tensorator as a natural isomorphism, -- we need to be in at least `Type 0`, so we have products. variables {C : Type u₁} [𝒞 : monoidal_category.{v₁+1} C] variables {D : Type u₂} [𝒟 : monoidal_category.{v₂+1} D] include 𝒞 𝒟 def μ_nat_iso (F : monoidal_functor.{v₁+1 v₂+1} C D) : (functor.prod F.to_functor F.to_functor) ⋙ (tensor D) ≅ (tensor C) ⋙ F.to_functor := nat_iso.of_components (by { intros, apply F.μ_iso }) (by { intros, apply F.to_lax_monoidal_functor.μ_natural }) end section variables (C : Type u₁) [𝒞 : monoidal_category.{v₁} C] include 𝒞 def id : monoidal_functor.{v₁ v₁} C C := { ε := 𝟙 _, μ := λ X Y, 𝟙 _, .. functor.id C } @[simp] lemma id_obj (X : C) : (monoidal_functor.id C).obj X = X := rfl @[simp] lemma id_map {X X' : C} (f : X ⟶ X') : (monoidal_functor.id C).map f = f := rfl @[simp] lemma id_ε : (monoidal_functor.id C).ε = 𝟙 _ := rfl @[simp] lemma id_μ (X Y) : (monoidal_functor.id C).μ X Y = 𝟙 _ := rfl end end monoidal_functor variables {C : Type u₁} [𝒞 : monoidal_category.{v₁} C] variables {D : Type u₂} [𝒟 : monoidal_category.{v₂} D] variables {E : Type u₃} [ℰ : monoidal_category.{v₃} E] include 𝒞 𝒟 ℰ namespace lax_monoidal_functor variables (F : lax_monoidal_functor.{v₁ v₂} C D) (G : lax_monoidal_functor.{v₂ v₃} D E) -- The proofs here are horrendous; rewrite_search helps a lot. def comp : lax_monoidal_functor.{v₁ v₃} C E := { ε := G.ε ≫ (G.map F.ε), μ := λ X Y, G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y), μ_natural' := λ _ _ _ _ f g, begin simp only [functor.comp_map, assoc], rw [←category.assoc, lax_monoidal_functor.μ_natural, category.assoc, ←map_comp, ←map_comp, ←lax_monoidal_functor.μ_natural] end, associativity' := λ X Y Z, begin dsimp, rw id_tensor_comp, slice_rhs 3 4 { rw [← G.to_functor.map_id, G.μ_natural], }, slice_rhs 1 3 { rw ←G.associativity, }, rw comp_tensor_id, slice_lhs 2 3 { rw [← G.to_functor.map_id, G.μ_natural], }, rw [category.assoc, category.assoc, category.assoc, category.assoc, category.assoc, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, F.associativity], end, left_unitality' := λ X, begin dsimp, rw [G.left_unitality, comp_tensor_id, category.assoc, category.assoc], apply congr_arg, rw [F.left_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, right_unitality' := λ X, begin dsimp, rw [G.right_unitality, id_tensor_comp, category.assoc, category.assoc], apply congr_arg, rw [F.right_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, .. (F.to_functor) ⋙ (G.to_functor) }. @[simp] lemma comp_obj (X : C) : (F.comp G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map {X X' : C} (f : X ⟶ X') : (F.comp G).map f = (G.map (F.map f) : G.obj (F.obj X) ⟶ G.obj (F.obj X')) := rfl @[simp] lemma comp_ε : (F.comp G).ε = G.ε ≫ (G.map F.ε) := rfl @[simp] lemma comp_μ (X Y : C) : (F.comp G).μ X Y = G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y) := rfl end lax_monoidal_functor namespace monoidal_functor variables (F : monoidal_functor.{v₁ v₂} C D) (G : monoidal_functor.{v₂ v₃} D E) def comp : monoidal_functor.{v₁ v₃} C E := { ε_is_iso := by { dsimp, apply_instance }, -- TODO tidy would get this if we deferred ext μ_is_iso := by { dsimp, apply_instance }, -- TODO as above .. (F.to_lax_monoidal_functor).comp (G.to_lax_monoidal_functor) }. end monoidal_functor end category_theory
5f9bda35f4db4c135d7520893245c751fcfc710b
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/interp.lean
fbf9259c45575adb877483b560f76b8b2f716f16
[ "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
765
lean
open bool nat open function inductive univ := | ubool : univ | unat : univ | uarrow : univ → univ → univ open univ definition interp [reducible] : univ → Type₁ | ubool := bool | unat := nat | (uarrow fr to) := interp fr → interp to definition foo : Π (u : univ) (el : interp u), interp u | ubool tt := ff | ubool ff := tt | unat n := succ n | (uarrow fr to) f := λ x : interp fr, f (foo fr x) definition is_even : nat → bool | zero := tt | (succ n) := bnot (is_even n) example : foo unat (10:nat) = 11 := rfl example : foo ubool tt = ff := rfl example : foo (uarrow unat ubool) (λ x : nat, is_even x) 3 = tt := rfl example : foo (uarrow unat ubool) (λ x : nat, is_even x) 4 = ff := rfl
fd3fc9c369adcc6e289e0be955730e49bf078393
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/lifting_properties/adjunction.lean
c285c0e87de1606543f5b0c8b4fb249fcefbb017
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,949
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.lifting_properties.basic import category_theory.adjunction.basic /-! # Lifting properties and adjunction In this file, we obtain `adjunction.has_lifting_property_iff`, which states that when we have an adjunction `adj : G ⊣ F` between two functors `G : C ⥤ D` and `F : D ⥤ C`, then a morphism of the form `G.map i` has the left lifting property in `D` with respect to a morphism `p` if and only the morphism `i` has the left lifting property in `C` with respect to `F.map p`. -/ namespace category_theory open category variables {C D : Type*} [category C] [category D] {G : C ⥤ D} {F : D ⥤ C} namespace comm_sq section variables {A B : C} {X Y : D} {i : A ⟶ B} {p : X ⟶ Y} {u : G.obj A ⟶ X} {v : G.obj B ⟶ Y} (sq : comm_sq u (G.map i) p v) (adj : G ⊣ F) include sq /-- When we have an adjunction `G ⊣ F`, any commutative square where the left map is of the form `G.map i` and the right map is `p` has an "adjoint" commutative square whose left map is `i` and whose right map is `F.map p`. -/ lemma right_adjoint : comm_sq (adj.hom_equiv _ _ u) i (F.map p) (adj.hom_equiv _ _ v) := ⟨begin simp only [adjunction.hom_equiv_unit, assoc, ← F.map_comp, sq.w], rw [F.map_comp, adjunction.unit_naturality_assoc], end⟩ /-- The liftings of a commutative are in bijection with the liftings of its (right) adjoint square. -/ def right_adjoint_lift_struct_equiv : sq.lift_struct ≃ (sq.right_adjoint adj).lift_struct := { to_fun := λ l, { l := adj.hom_equiv _ _ l.l, fac_left' := by rw [← adj.hom_equiv_naturality_left, l.fac_left], fac_right' := by rw [← adjunction.hom_equiv_naturality_right, l.fac_right], }, inv_fun := λ l, { l := (adj.hom_equiv _ _).symm l.l, fac_left' := begin rw [← adjunction.hom_equiv_naturality_left_symm, l.fac_left], apply (adj.hom_equiv _ _).left_inv, end, fac_right' := begin rw [← adjunction.hom_equiv_naturality_right_symm, l.fac_right], apply (adj.hom_equiv _ _).left_inv, end, }, left_inv := by tidy, right_inv := by tidy, } /-- A square has a lifting if and only if its (right) adjoint square has a lifting. -/ lemma right_adjoint_has_lift_iff : has_lift (sq.right_adjoint adj) ↔ has_lift sq := begin simp only [has_lift.iff], exact equiv.nonempty_congr (sq.right_adjoint_lift_struct_equiv adj).symm, end instance [has_lift sq] : has_lift (sq.right_adjoint adj) := by { rw right_adjoint_has_lift_iff, apply_instance, } end section variables {A B : C} {X Y : D} {i : A ⟶ B} {p : X ⟶ Y} {u : A ⟶ F.obj X} {v : B ⟶ F.obj Y} (sq : comm_sq u i (F.map p) v) (adj : G ⊣ F) include sq /-- When we have an adjunction `G ⊣ F`, any commutative square where the left map is of the form `i` and the right map is `F.map p` has an "adjoint" commutative square whose left map is `G.map i` and whose right map is `p`. -/ lemma left_adjoint : comm_sq ((adj.hom_equiv _ _).symm u) (G.map i) p ((adj.hom_equiv _ _).symm v) := ⟨begin simp only [adjunction.hom_equiv_counit, assoc, ← G.map_comp_assoc, ← sq.w], rw [G.map_comp, assoc, adjunction.counit_naturality], end⟩ /-- The liftings of a commutative are in bijection with the liftings of its (left) adjoint square. -/ def left_adjoint_lift_struct_equiv : sq.lift_struct ≃ (sq.left_adjoint adj).lift_struct := { to_fun := λ l, { l := (adj.hom_equiv _ _).symm l.l, fac_left' := by rw [← adj.hom_equiv_naturality_left_symm, l.fac_left], fac_right' := by rw [← adj.hom_equiv_naturality_right_symm, l.fac_right], }, inv_fun := λ l, { l := (adj.hom_equiv _ _) l.l, fac_left' := begin rw [← adj.hom_equiv_naturality_left, l.fac_left], apply (adj.hom_equiv _ _).right_inv, end, fac_right' := begin rw [← adj.hom_equiv_naturality_right, l.fac_right], apply (adj.hom_equiv _ _).right_inv, end, }, left_inv := by tidy, right_inv := by tidy, } /-- A (left) adjoint square has a lifting if and only if the original square has a lifting. -/ lemma left_adjoint_has_lift_iff : has_lift (sq.left_adjoint adj) ↔ has_lift sq := begin simp only [has_lift.iff], exact equiv.nonempty_congr (sq.left_adjoint_lift_struct_equiv adj).symm, end instance [has_lift sq] : has_lift (sq.left_adjoint adj) := by { rw left_adjoint_has_lift_iff, apply_instance, } end end comm_sq namespace adjunction lemma has_lifting_property_iff (adj : G ⊣ F) {A B : C} {X Y : D} (i : A ⟶ B) (p : X ⟶ Y) : has_lifting_property (G.map i) p ↔ has_lifting_property i (F.map p) := begin split; introI; constructor; intros f g sq, { rw ← sq.left_adjoint_has_lift_iff adj, apply_instance, }, { rw ← sq.right_adjoint_has_lift_iff adj, apply_instance, }, end end adjunction end category_theory
eaddd71ad8da55368bf9843c13f6e584c9f1e902
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/star/gelfand_duality.lean
58777a5d3fd29d63cce26dac25b76bb67b27b50d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
11,086
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Reeased under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.spectrum import analysis.normed.group.quotient import analysis.normed_space.algebra import topology.continuous_function.units import topology.continuous_function.compact import topology.algebra.algebra import topology.continuous_function.stone_weierstrass /-! # Gelfand Duality > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The `gelfand_transform` is an algebra homomorphism from a topological `𝕜`-algebra `A` to `C(character_space 𝕜 A, 𝕜)`. In the case where `A` is a commutative complex Banach algebra, then the Gelfand transform is actually spectrum-preserving (`spectrum.gelfand_transform_eq`). Moreover, when `A` is a commutative C⋆-algebra over `ℂ`, then the Gelfand transform is a surjective isometry, and even an equivalence between C⋆-algebras. ## Main definitions * `ideal.to_character_space` : constructs an element of the character space from a maximal ideal in a commutative complex Banach algebra * `weak_dual.character_space.comp_continuous_map`: The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` given by pre-composition with `ψ`. ## Main statements * `spectrum.gelfand_transform_eq` : the Gelfand transform is spectrum-preserving when the algebra is a commutative complex Banach algebra. * `gelfand_transform_isometry` : the Gelfand transform is an isometry when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. * `gelfand_transform_bijective` : the Gelfand transform is bijective when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. ## TODO * After `star_alg_equiv` is defined, realize `gelfand_transform` as a `star_alg_equiv`. * Prove that if `A` is the unital C⋆-algebra over `ℂ` generated by a fixed normal element `x` in a larger C⋆-algebra `B`, then `character_space ℂ A` is homeomorphic to `spectrum ℂ x`. * From the previous result, construct the **continuous functional calculus**. * Show that if `X` is a compact Hausdorff space, then `X` is (canonically) homeomorphic to `character_space ℂ C(X, ℂ)`. * Conclude using the previous fact that the functors `C(⬝, ℂ)` and `character_space ℂ ⬝` along with the canonical homeomorphisms described above constitute a natural contravariant equivalence of the categories of compact Hausdorff spaces (with continuous maps) and commutative unital C⋆-algebras (with unital ⋆-algebra homomoprhisms); this is known as **Gelfand duality**. ## Tags Gelfand transform, character space, C⋆-algebra -/ open weak_dual open_locale nnreal section complex_banach_algebra open ideal variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] (I : ideal A) [ideal.is_maximal I] /-- Every maximal ideal in a commutative complex Banach algebra gives rise to a character on that algebra. In particular, the character, which may be identified as an algebra homomorphism due to `weak_dual.character_space.equiv_alg_hom`, is given by the composition of the quotient map and the Gelfand-Mazur isomorphism `normed_ring.alg_equiv_complex_of_complete`. -/ noncomputable def ideal.to_character_space : character_space ℂ A := character_space.equiv_alg_hom.symm $ ((@normed_ring.alg_equiv_complex_of_complete (A ⧸ I) _ _ (by { letI := quotient.field I, exact @is_unit_iff_ne_zero (A ⧸ I) _ }) _).symm : A ⧸ I →ₐ[ℂ] ℂ).comp (quotient.mkₐ ℂ I) lemma ideal.to_character_space_apply_eq_zero_of_mem {a : A} (ha : a ∈ I) : I.to_character_space a = 0 := begin unfold ideal.to_character_space, simpa only [character_space.equiv_alg_hom_symm_coe, alg_hom.coe_comp, alg_equiv.coe_alg_hom, quotient.mkₐ_eq_mk, function.comp_app, quotient.eq_zero_iff_mem.mpr ha, spectrum.zero_eq, normed_ring.alg_equiv_complex_of_complete_symm_apply] using set.eq_of_mem_singleton (set.singleton_nonempty (0 : ℂ)).some_mem, end /-- If `a : A` is not a unit, then some character takes the value zero at `a`. This is equivlaent to `gelfand_transform ℂ A a` takes the value zero at some character. -/ lemma weak_dual.character_space.exists_apply_eq_zero {a : A} (ha : ¬ is_unit a) : ∃ f : character_space ℂ A, f a = 0 := begin unfreezingI { obtain ⟨M, hM, haM⟩ := (span {a}).exists_le_maximal (span_singleton_ne_top ha) }, exact ⟨M.to_character_space, M.to_character_space_apply_eq_zero_of_mem (haM (mem_span_singleton.mpr ⟨1, (mul_one a).symm⟩))⟩, end lemma weak_dual.character_space.mem_spectrum_iff_exists {a : A} {z : ℂ} : z ∈ spectrum ℂ a ↔ ∃ f : character_space ℂ A, f a = z := begin refine ⟨λ hz, _, _⟩, { obtain ⟨f, hf⟩ := weak_dual.character_space.exists_apply_eq_zero hz, simp only [map_sub, sub_eq_zero, alg_hom_class.commutes, algebra.id.map_eq_id, ring_hom.id_apply] at hf, exact (continuous_map.spectrum_eq_range (gelfand_transform ℂ A a)).symm ▸ ⟨f, hf.symm⟩ }, { rintro ⟨f, rfl⟩, exact alg_hom.apply_mem_spectrum f a, } end /-- The Gelfand transform is spectrum-preserving. -/ lemma spectrum.gelfand_transform_eq (a : A) : spectrum ℂ (gelfand_transform ℂ A a) = spectrum ℂ a := begin ext z, rw [continuous_map.spectrum_eq_range, weak_dual.character_space.mem_spectrum_iff_exists], exact iff.rfl, end instance [nontrivial A] : nonempty (character_space ℂ A) := ⟨classical.some $ weak_dual.character_space.exists_apply_eq_zero $ zero_mem_nonunits.2 zero_ne_one⟩ end complex_banach_algebra section complex_cstar_algebra variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] variables [star_ring A] [cstar_ring A] [star_module ℂ A] lemma gelfand_transform_map_star (a : A) : gelfand_transform ℂ A (star a) = star (gelfand_transform ℂ A a) := continuous_map.ext $ λ φ, map_star φ a variable (A) /-- The Gelfand transform is an isometry when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_isometry : isometry (gelfand_transform ℂ A) := begin nontriviality A, refine add_monoid_hom_class.isometry_of_norm (gelfand_transform ℂ A) (λ a, _), /- By `spectrum.gelfand_transform_eq`, the spectra of `star a * a` and its `gelfand_transform` coincide. Therefore, so do their spectral radii, and since they are self-adjoint, so also do their norms. Applying the C⋆-property of the norm and taking square roots shows that the norm is preserved. -/ have : spectral_radius ℂ (gelfand_transform ℂ A (star a * a)) = spectral_radius ℂ (star a * a), { unfold spectral_radius, rw spectrum.gelfand_transform_eq, }, simp only [map_mul, (is_self_adjoint.star_mul_self _).spectral_radius_eq_nnnorm, gelfand_transform_map_star a, ennreal.coe_eq_coe, cstar_ring.nnnorm_star_mul_self, ←sq] at this, simpa only [function.comp_app, nnreal.sqrt_sq] using congr_arg ((coe : ℝ≥0 → ℝ) ∘ ⇑nnreal.sqrt) this, end /-- The Gelfand transform is bijective when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_bijective : function.bijective (gelfand_transform ℂ A) := begin refine ⟨(gelfand_transform_isometry A).injective, _⟩, suffices : (gelfand_transform ℂ A).range = ⊤, { exact λ x, this.symm ▸ (gelfand_transform ℂ A).mem_range.mp (this.symm ▸ algebra.mem_top) }, /- Because the `gelfand_transform ℂ A` is an isometry, it has closed range, and so by the Stone-Weierstrass theorem, it suffices to show that the image of the Gelfand transform separates points in `C(character_space ℂ A, ℂ)` and is closed under `star`. -/ have h : (gelfand_transform ℂ A).range.topological_closure = (gelfand_transform ℂ A).range, from le_antisymm (subalgebra.topological_closure_minimal _ le_rfl (gelfand_transform_isometry A).closed_embedding.closed_range) (subalgebra.le_topological_closure _), refine h ▸ continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points _ (λ _ _, _) (λ f hf, _), /- Separating points just means that elements of the `character_space` which agree at all points of `A` are the same functional, which is just extensionality. -/ { contrapose!, exact λ h, subtype.ext (continuous_linear_map.ext $ λ a, h (gelfand_transform ℂ A a) ⟨gelfand_transform ℂ A a, ⟨a, rfl⟩, rfl⟩), }, /- If `f = gelfand_transform ℂ A a`, then `star f` is also in the range of `gelfand_transform ℂ A` using the argument `star a`. The key lemma below may be hard to spot; it's `map_star` coming from `weak_dual.star_hom_class`, which is a nontrivial result. -/ { obtain ⟨f, ⟨a, rfl⟩, rfl⟩ := subalgebra.mem_map.mp hf, refine ⟨star a, continuous_map.ext $ λ ψ, _⟩, simpa only [gelfand_transform_map_star a, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] } end /-- The Gelfand transform as a `star_alg_equiv` between a commutative unital C⋆-algebra over `ℂ` and the continuous functions on its `character_space`. -/ @[simps] noncomputable def gelfand_star_transform : A ≃⋆ₐ[ℂ] C(character_space ℂ A, ℂ) := star_alg_equiv.of_bijective (show A →⋆ₐ[ℂ] C(character_space ℂ A, ℂ), from { map_star' := λ x, gelfand_transform_map_star x, .. gelfand_transform ℂ A }) (gelfand_transform_bijective A) end complex_cstar_algebra section functoriality namespace weak_dual namespace character_space variables {A B C : Type*} variables [normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] variables [normed_ring B] [normed_algebra ℂ B] [complete_space B] [star_ring B] variables [normed_ring C] [normed_algebra ℂ C] [complete_space C] [star_ring C] /-- The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` obtained by pre-composition with `ψ`. -/ @[simps] noncomputable def comp_continuous_map (ψ : A →⋆ₐ[ℂ] B) : C(character_space ℂ B, character_space ℂ A) := { to_fun := λ φ, equiv_alg_hom.symm ((equiv_alg_hom φ).comp (ψ.to_alg_hom)), continuous_to_fun := continuous.subtype_mk (continuous_of_continuous_eval $ λ a, map_continuous $ gelfand_transform ℂ B (ψ a)) _ } variables (A) /-- `weak_dual.character_space.comp_continuous_map` sends the identity to the identity. -/ @[simp] lemma comp_continuous_map_id : comp_continuous_map (star_alg_hom.id ℂ A) = continuous_map.id (character_space ℂ A) := continuous_map.ext $ λ a, ext $ λ x, rfl variables {A} /-- `weak_dual.character_space.comp_continuous_map` is functorial. -/ @[simp] lemma comp_continuous_map_comp (ψ₂ : B →⋆ₐ[ℂ] C) (ψ₁ : A →⋆ₐ[ℂ] B) : comp_continuous_map (ψ₂.comp ψ₁) = (comp_continuous_map ψ₁).comp (comp_continuous_map ψ₂) := continuous_map.ext $ λ a, ext $ λ x, rfl end character_space end weak_dual end functoriality
c5522fbea170f36d285f003b0b6cdfdadf1438d6
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/ring_theory/associated.lean
429d584fdddb6b1da1acad89bca4a96c73690f24
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
16,680
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Associated and irreducible elements. -/ import order.galois_connection algebra.group data.equiv.basic data.multiset data.int.gcd variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} open lattice def is_unit [monoid α] (a : α) : Prop := ∃u:units α, a = u @[simp] theorem not_is_unit_zero [nonzero_comm_ring α] : ¬ is_unit (0 : α) | ⟨⟨a, b, hab, hba⟩, rfl⟩ := have 0 * b = 1, from hab, by simpa using this @[simp] theorem is_unit_one [monoid α] : is_unit (1:α) := ⟨1, rfl⟩ theorem units.is_unit_of_mul_one [comm_monoid α] (a b : α) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[simp] theorem is_unit_mul_units [monoid α] (a : α) (u : units α) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [hv, units.mul_coe], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv.symm ▸ ⟨v * u, (units.mul_coe v u).symm⟩) theorem is_unit_iff_dvd_one {α} [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd {α} [comm_semiring α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu @[simp] theorem is_unit_nat {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ @[class] def irreducible [monoid α] (p : α) : Prop := ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible] @[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.mul_coe, mul_assoc]⟩ theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, one_mul _⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin haveI := classical.dec_eq α, rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have : a * 1 = a * (c * d), { simpa [mul_assoc] using a_eq }, have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this, exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩ end protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := λa b, ∃c, a * c = b, le_refl := assume a, ⟨1, by simp⟩, le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩} theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1 | ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1 theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h.symm ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := ⟨a, one_mul a⟩ theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_semiring variables [comm_semiring α] @[simp] theorem mk_zero_eq (a : α) : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ @[simp] theorem mul_zero : ∀(a : associates α), a * 0 = 0 := by rintros ⟨a⟩; show associates.mk (a * 0) = associates.mk 0; rw [mul_zero] @[simp] theorem zero_mul : ∀(a : associates α), 0 * a = 0 := by rintros ⟨a⟩; show associates.mk (0 * a) = associates.mk 0; rw [zero_mul] theorem mk_eq_zero_iff_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := calc associates.mk a = 0 ↔ (a ~ᵤ 0) : mk_eq_mk_iff_associated ... ↔ a = 0 : associated_zero_iff_eq_zero a theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d⁻¹) * c, calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one] ... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd end comm_semiring section integral_domain variable [integral_domain α] instance : partial_order (associates α) := { le_antisymm := assume a' b', quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩, (quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂, let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in quotient.sound $ associated_of_dvd_dvd (h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) (h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂ .. associates.preorder } instance : lattice.order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : lattice.order_top (associates α) := { top := 0, le_top := assume a, ⟨0, mul_zero a⟩, .. associates.partial_order } theorem zero_ne_one : (0 : associates α) ≠ 1 := assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this theorem mul_eq_zero_iff {x y : associates α} : x * y = 0 ↔ x = 0 ∨ y = 0 := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero_iff_eq_zero_or_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl)) (by simp [or_imp_distrib] {contextual := tt}) theorem prod_eq_zero_iff {s : multiset (associates α)} : s.prod = 0 ↔ (0 : associates α) ∈ s := multiset.induction_on s (by simp; exact zero_ne_one.symm) $ assume a s, by simp [mul_eq_zero_iff, @eq_comm _ 0 a] {contextual := tt} theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp [irreducible, is_unit_mk], apply and_congr (iff.refl _), split, { assume h x y eq, have : is_unit (associates.mk x) ∨ is_unit (associates.mk y), from h _ _ (by rw [eq]; refl), simpa [is_unit_mk] }, { refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _), rcases quotient.exact eq.symm with ⟨u, eq⟩, have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ this } end end integral_domain section normalization_domain variable [normalization_domain α] protected def out : associates α → α := begin refine quotient.lift (λa, a * ↑(norm_unit a)) _, letI := classical.dec_eq α, rintros a _ ⟨u, rfl⟩, by_cases a = 0, { simp [h] }, calc a * ↑(norm_unit a) = a * ↑(u * norm_unit a * u⁻¹) : by rw [mul_comm u, mul_assoc, mul_inv_self, mul_one] ... = a * ↑u * ↑(norm_unit (a * ↑u)) : by simp [h, norm_unit_mul, units.mul_coe, units.inv_coe, mul_assoc] end lemma out_mk (a : α) : (associates.mk a).out = a * ↑(norm_unit a) := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := calc (1 : associates α).out = 1 * ↑(norm_unit (1 : α)) : out_mk _ ... = 1 : by simp lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := begin refine quotient.induction_on₂ a b (assume a b, _), simp [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk], letI := classical.dec_eq α, by_cases a = 0; by_cases b = 0; simp [*, mul_assoc, mul_comm, mul_left_comm] end lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := calc (⊤ : associates α).out = 0 * ↑(norm_unit (0:α)) : out_mk _ ... = 0 : by simp @[simp] lemma norm_unit_out (a : associates α) : norm_unit a.out = 1 := quotient.induction_on a $ assume a, by rw [associates.quotient_mk_eq_mk, associates.out_mk, norm_unit_mul_norm_unit] end normalization_domain end associates def associates_int_equiv_nat : (associates ℤ) ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), simp [associates.out_mk, associates.quotient_mk_eq_mk, associated, int.coe_nat_abs_eq_mul_norm_unit.symm] }, { assume n, simp [associates.out_mk, int.coe_nat_abs_eq_mul_norm_unit.symm] } end
011bd32eae29882beba5d85a89119e3536a46689
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0302.lean
2fc6ff55b982bada4a1ce1f0b084246855b33f2b
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
128
lean
variables p q : Prop example (hp : p) (hq : q) : p ∧ q := and.intro hp hq #check assume (hp : p) (hq : q), and.intro hp hq
2162b61e616fddf931c21d87c6b429448e86ab5d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/field_theory/algebraic_closure.lean
cd907e470695ec3dc9a118f2548fdbaef86b6ec8
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
12,488
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.direct_limit import Mathlib.field_theory.splitting_field import Mathlib.analysis.complex.polynomial import Mathlib.PostPort universes u l u_1 u_2 v namespace Mathlib /-! # Algebraic Closure In this file we define the typeclass for algebraically closed fields and algebraic closures. We also construct an algebraic closure for any field. ## Main Definitions - `is_alg_closed k` is the typeclass saying `k` is an algebraically closed field, i.e. every polynomial in `k` splits. - `is_alg_closure k K` is the typeclass saying `K` is an algebraic closure of `k`. - `algebraic_closure k` is an algebraic closure of `k` (in the same universe). It is constructed by taking the polynomial ring generated by indeterminates `x_f` corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably many times. See Exercise 1.13 in Atiyah--Macdonald. ## TODO Show that any algebraic extension embeds into any algebraically closed extension (via Zorn's lemma). ## Tags algebraic closure, algebraically closed -/ /-- Typeclass for algebraically closed fields. -/ class is_alg_closed (k : Type u) [field k] where splits : ∀ (p : polynomial k), polynomial.splits (ring_hom.id k) p theorem polynomial.splits' {k : Type u_1} {K : Type u_2} [field k] [is_alg_closed k] [field K] {f : k →+* K} (p : polynomial k) : polynomial.splits f p := polynomial.splits_of_splits_id f (is_alg_closed.splits p) namespace is_alg_closed theorem of_exists_root (k : Type u) [field k] (H : ∀ (p : polynomial k), polynomial.monic p → irreducible p → ∃ (x : k), polynomial.eval x p = 0) : is_alg_closed k := sorry theorem degree_eq_one_of_irreducible (k : Type u) [field k] [is_alg_closed k] {p : polynomial k} (h_nz : p ≠ 0) (hp : irreducible p) : polynomial.degree p = 1 := polynomial.degree_eq_one_of_irreducible_of_splits h_nz hp (polynomial.splits' p) theorem algebra_map_surjective_of_is_integral {k : Type u_1} {K : Type u_2} [field k] [domain K] [hk : is_alg_closed k] [algebra k K] (hf : algebra.is_integral k K) : function.surjective ⇑(algebra_map k K) := sorry theorem algebra_map_surjective_of_is_integral' {k : Type u_1} {K : Type u_2} [field k] [integral_domain K] [hk : is_alg_closed k] (f : k →+* K) (hf : ring_hom.is_integral f) : function.surjective ⇑f := algebra_map_surjective_of_is_integral hf theorem algebra_map_surjective_of_is_algebraic {k : Type u_1} {K : Type u_2} [field k] [domain K] [hk : is_alg_closed k] [algebra k K] (hf : algebra.is_algebraic k K) : function.surjective ⇑(algebra_map k K) := algebra_map_surjective_of_is_integral (iff.mp (is_algebraic_iff_is_integral' k) hf) end is_alg_closed protected instance complex.is_alg_closed : is_alg_closed ℂ := is_alg_closed.of_exists_root ℂ fun (p : polynomial ℂ) (_x : polynomial.monic p) (hp : irreducible p) => complex.exists_root (polynomial.degree_pos_of_irreducible hp) /-- Typeclass for an extension being an algebraic closure. -/ def is_alg_closure (k : Type u) [field k] (K : Type v) [field K] [algebra k K] := is_alg_closed K ∧ algebra.is_algebraic k K namespace algebraic_closure /-- The subtype of monic irreducible polynomials -/ def monic_irreducible (k : Type u) [field k] := Subtype fun (f : polynomial k) => polynomial.monic f ∧ irreducible f /-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/ def eval_X_self (k : Type u) [field k] (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k := polynomial.eval₂ mv_polynomial.C (mv_polynomial.X f) ↑f /-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/ def span_eval (k : Type u) [field k] : ideal (mv_polynomial (monic_irreducible k) k) := ideal.span (set.range (eval_X_self k)) /-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the splitting field of the product of the polynomials sending each indeterminate `x_f` represented by the polynomial `f` in the finset to a root of `f`. -/ def to_splitting_field (k : Type u) [field k] (s : finset (monic_irreducible k)) : alg_hom k (mv_polynomial (monic_irreducible k) k) (polynomial.splitting_field (finset.prod s fun (x : monic_irreducible k) => ↑x)) := mv_polynomial.aeval fun (f : monic_irreducible k) => dite (f ∈ s) (fun (hf : f ∈ s) => polynomial.root_of_splits (algebra_map k (polynomial.splitting_field (finset.prod s fun (x : monic_irreducible k) => ↑x))) sorry sorry) fun (hf : ¬f ∈ s) => bit1 (bit0 (bit1 (bit0 (bit0 1)))) theorem to_splitting_field_eval_X_self (k : Type u) [field k] {s : finset (monic_irreducible k)} {f : monic_irreducible k} (hf : f ∈ s) : coe_fn (to_splitting_field k s) (eval_X_self k f) = 0 := sorry theorem span_eval_ne_top (k : Type u) [field k] : span_eval k ≠ ⊤ := sorry /-- A random maximal ideal that contains `span_eval k` -/ def max_ideal (k : Type u) [field k] : ideal (mv_polynomial (monic_irreducible k) k) := classical.some sorry protected instance max_ideal.is_maximal (k : Type u) [field k] : ideal.is_maximal (max_ideal k) := and.left (classical.some_spec (ideal.exists_le_maximal (span_eval k) (span_eval_ne_top k))) theorem le_max_ideal (k : Type u) [field k] : span_eval k ≤ max_ideal k := and.right (classical.some_spec (ideal.exists_le_maximal (span_eval k) (span_eval_ne_top k))) /-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/ def adjoin_monic (k : Type u) [field k] := ideal.quotient (max_ideal k) protected instance adjoin_monic.field (k : Type u) [field k] : field (adjoin_monic k) := ideal.quotient.field (max_ideal k) protected instance adjoin_monic.inhabited (k : Type u) [field k] : Inhabited (adjoin_monic k) := { default := bit1 (bit0 (bit1 (bit0 (bit0 1)))) } /-- The canonical ring homomorphism to `adjoin_monic k`. -/ def to_adjoin_monic (k : Type u) [field k] : k →+* adjoin_monic k := ring_hom.comp (ideal.quotient.mk (max_ideal k)) mv_polynomial.C protected instance adjoin_monic.algebra (k : Type u) [field k] : algebra k (adjoin_monic k) := ring_hom.to_algebra (to_adjoin_monic k) theorem adjoin_monic.algebra_map (k : Type u) [field k] : algebra_map k (adjoin_monic k) = ring_hom.comp (ideal.quotient.mk (max_ideal k)) mv_polynomial.C := rfl theorem adjoin_monic.is_integral (k : Type u) [field k] (z : adjoin_monic k) : is_integral k z := sorry theorem adjoin_monic.exists_root (k : Type u) [field k] {f : polynomial k} (hfm : polynomial.monic f) (hfi : irreducible f) : ∃ (x : adjoin_monic k), polynomial.eval₂ (to_adjoin_monic k) x f = 0 := sorry /-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/ def step_aux (k : Type u) [field k] (n : ℕ) : sigma fun (α : Type u) => field α := nat.rec_on n (sigma.mk k infer_instance) fun (n : ℕ) (ih : sigma fun (α : Type u) => field α) => sigma.mk (adjoin_monic (sigma.fst ih)) (adjoin_monic.field (sigma.fst ih)) /-- The `n`th step of constructing `algebraic_closure`. -/ def step (k : Type u) [field k] (n : ℕ) := sigma.fst (step_aux k n) protected instance step.field (k : Type u) [field k] (n : ℕ) : field (step k n) := sigma.snd (step_aux k n) protected instance step.inhabited (k : Type u) [field k] (n : ℕ) : Inhabited (step k n) := { default := bit1 (bit0 (bit1 (bit0 (bit0 1)))) } /-- The canonical inclusion to the `0`th step. -/ def to_step_zero (k : Type u) [field k] : k →+* step k 0 := ring_hom.id k /-- The canonical ring homomorphism to the next step. -/ def to_step_succ (k : Type u) [field k] (n : ℕ) : step k n →+* step k (n + 1) := to_adjoin_monic (step k n) protected instance step.algebra_succ (k : Type u) [field k] (n : ℕ) : algebra (step k n) (step k (n + 1)) := ring_hom.to_algebra (to_step_succ k n) theorem to_step_succ.exists_root (k : Type u) [field k] {n : ℕ} {f : polynomial (step k n)} (hfm : polynomial.monic f) (hfi : irreducible f) : ∃ (x : step k (n + 1)), polynomial.eval₂ (to_step_succ k n) x f = 0 := adjoin_monic.exists_root (step k n) hfm hfi /-- The canonical ring homomorphism to a step with a greater index. -/ def to_step_of_le (k : Type u) [field k] (m : ℕ) (n : ℕ) (h : m ≤ n) : step k m →+* step k n := ring_hom.mk (nat.le_rec_on h fun (n : ℕ) => ⇑(to_step_succ k n)) sorry sorry sorry sorry @[simp] theorem coe_to_step_of_le (k : Type u) [field k] (m : ℕ) (n : ℕ) (h : m ≤ n) : ⇑(to_step_of_le k m n h) = nat.le_rec_on h fun (n : ℕ) => ⇑(to_step_succ k n) := rfl protected instance step.algebra (k : Type u) [field k] (n : ℕ) : algebra k (step k n) := ring_hom.to_algebra (to_step_of_le k 0 n (nat.zero_le n)) protected instance step.scalar_tower (k : Type u) [field k] (n : ℕ) : is_scalar_tower k (step k n) (step k (n + 1)) := is_scalar_tower.of_algebra_map_eq fun (z : k) => nat.le_rec_on_succ (nat.zero_le n) z theorem step.is_integral (k : Type u) [field k] (n : ℕ) (z : step k n) : is_integral k z := nat.rec_on n (fun (z : step k 0) => is_integral_algebra_map) fun (n : ℕ) (ih : ∀ (z : step k n), is_integral k z) (z : step k (Nat.succ n)) => is_integral_trans ih z (adjoin_monic.is_integral (step k n) z) protected instance to_step_of_le.directed_system (k : Type u) [field k] : directed_system (step k) fun (i j : ℕ) (h : i ≤ j) => ⇑(to_step_of_le k i j h) := directed_system.mk (fun (i : ℕ) (x : step k i) (h : i ≤ i) => nat.le_rec_on_self x) fun (i₁ i₂ i₃ : ℕ) (h₁₂ : i₁ ≤ i₂) (h₂₃ : i₂ ≤ i₃) (x : step k i₁) => Eq.symm (nat.le_rec_on_trans h₁₂ h₂₃ x) end algebraic_closure /-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/ def algebraic_closure (k : Type u) [field k] := ring.direct_limit sorry fun (i j : ℕ) (h : i ≤ j) => ⇑sorry namespace algebraic_closure protected instance field (k : Type u) [field k] : field (algebraic_closure k) := field.direct_limit.field (step k) fun (i j : ℕ) (h : i ≤ j) => to_step_of_le k i j h protected instance inhabited (k : Type u) [field k] : Inhabited (algebraic_closure k) := { default := bit1 (bit0 (bit1 (bit0 (bit0 1)))) } /-- The canonical ring embedding from the `n`th step to the algebraic closure. -/ def of_step (k : Type u) [field k] (n : ℕ) : step k n →+* algebraic_closure k := ring_hom.of ⇑(ring.direct_limit.of (step k) (fun (i j : ℕ) (h : i ≤ j) => ⇑(to_step_of_le k i j h)) n) protected instance algebra_of_step (k : Type u) [field k] (n : ℕ) : algebra (step k n) (algebraic_closure k) := ring_hom.to_algebra (of_step k n) theorem of_step_succ (k : Type u) [field k] (n : ℕ) : ring_hom.comp (of_step k (n + 1)) (to_step_succ k n) = of_step k n := sorry theorem exists_of_step (k : Type u) [field k] (z : algebraic_closure k) : ∃ (n : ℕ), ∃ (x : step k n), coe_fn (of_step k n) x = z := ring.direct_limit.exists_of z -- slow theorem exists_root (k : Type u) [field k] {f : polynomial (algebraic_closure k)} (hfm : polynomial.monic f) (hfi : irreducible f) : ∃ (x : algebraic_closure k), polynomial.eval x f = 0 := sorry protected instance is_alg_closed (k : Type u) [field k] : is_alg_closed (algebraic_closure k) := is_alg_closed.of_exists_root (algebraic_closure k) fun (f : polynomial (algebraic_closure k)) => exists_root k protected instance algebra (k : Type u) [field k] : algebra k (algebraic_closure k) := ring_hom.to_algebra (of_step k 0) /-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/ def of_step_hom (k : Type u) [field k] (n : ℕ) : alg_hom k (step k n) (algebraic_closure k) := alg_hom.mk (ring_hom.to_fun (of_step k n)) sorry sorry sorry sorry sorry theorem is_algebraic (k : Type u) [field k] : algebra.is_algebraic k (algebraic_closure k) := sorry protected instance is_alg_closure (k : Type u) [field k] : is_alg_closure k (algebraic_closure k) := { left := algebraic_closure.is_alg_closed k, right := is_algebraic k }
499d645c1dc11c7b68c238fef682ef6a6fd6c80a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/unsigned.lean
6f848085821b014a409334ad4075a98631babb6b
[ "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
836
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.fin open nat definition unsigned_sz : nat := succ 4294967295 attribute [reducible] definition unsigned := fin unsigned_sz namespace unsigned /- We cannot use tactic dec_trivial here because the tactic framework has not been defined yet. -/ private lemma zero_lt_unsigned_sz : 0 < unsigned_sz := zero_lt_succ _ definition of_nat (n : nat) : unsigned := if H : n < unsigned_sz then fin.mk n H else fin.mk 0 zero_lt_unsigned_sz definition to_nat (c : unsigned) : nat := fin.val c end unsigned attribute [instance] definition unsigned.has_decidable_eq : decidable_eq unsigned := have decidable_eq (fin unsigned_sz), from fin.has_decidable_eq _, this
c85b250c4cd1a864f358d7872ffd2d425cac52ce
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/number_field/embeddings.lean
a42a2fc245ed589621433ec34c51a0ff13913abb
[ "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
19,674
lean
/- Copyright (c) 2022 Xavier Roblot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Xavier Roblot -/ import analysis.complex.polynomial import field_theory.minpoly.is_integrally_closed import number_theory.number_field.basic import ring_theory.norm import topology.instances.complex /-! # Embeddings of number fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the embeddings of a number field into an algebraic closed field. ## Main Results * `number_field.embeddings.range_eval_eq_root_set_minpoly`: let `x ∈ K` with `K` number field and let `A` be an algebraic closed field of char. 0, then the images of `x` by the embeddings of `K` in `A` are exactly the roots in `A` of the minimal polynomial of `x` over `ℚ`. * `number_field.embeddings.pow_eq_one_of_norm_eq_one`: an algebraic integer whose conjugates are all of norm one is a root of unity. ## Tags number field, embeddings, places, infinite places -/ open_locale classical namespace number_field.embeddings section fintype open finite_dimensional variables (K : Type*) [field K] [number_field K] variables (A : Type*) [field A] [char_zero A] /-- There are finitely many embeddings of a number field. -/ noncomputable instance : fintype (K →+* A) := fintype.of_equiv (K →ₐ[ℚ] A) ring_hom.equiv_rat_alg_hom.symm variables [is_alg_closed A] /-- The number of embeddings of a number field is equal to its finrank. -/ lemma card : fintype.card (K →+* A) = finrank ℚ K := by rw [fintype.of_equiv_card ring_hom.equiv_rat_alg_hom.symm, alg_hom.card] instance : nonempty (K →+* A) := begin rw [← fintype.card_pos_iff, number_field.embeddings.card K A], exact finite_dimensional.finrank_pos, end end fintype section roots open set polynomial variables (K A : Type*) [field K] [number_field K] [field A] [algebra ℚ A] [is_alg_closed A] (x : K) /-- Let `A` be an algebraically closed field and let `x ∈ K`, with `K` a number field. The images of `x` by the embeddings of `K` in `A` are exactly the roots in `A` of the minimal polynomial of `x` over `ℚ`. -/ lemma range_eval_eq_root_set_minpoly : range (λ φ : K →+* A, φ x) = (minpoly ℚ x).root_set A := begin convert (number_field.is_algebraic K).range_eval_eq_root_set_minpoly A x using 1, ext a, exact ⟨λ ⟨φ, hφ⟩, ⟨φ.to_rat_alg_hom, hφ⟩, λ ⟨φ, hφ⟩, ⟨φ.to_ring_hom, hφ⟩⟩, end end roots section bounded open finite_dimensional polynomial set variables {K : Type*} [field K] [number_field K] variables {A : Type*} [normed_field A] [is_alg_closed A] [normed_algebra ℚ A] lemma coeff_bdd_of_norm_le {B : ℝ} {x : K} (h : ∀ φ : K →+* A, ‖φ x‖ ≤ B) (i : ℕ) : ‖(minpoly ℚ x).coeff i‖ ≤ (max B 1) ^ (finrank ℚ K) * (finrank ℚ K).choose ((finrank ℚ K) / 2) := begin have hx := is_separable.is_integral ℚ x, rw [← norm_algebra_map' A, ← coeff_map (algebra_map ℚ A)], refine coeff_bdd_of_roots_le _ (minpoly.monic hx) (is_alg_closed.splits_codomain _) (minpoly.nat_degree_le hx) (λ z hz, _) i, classical, rw ← multiset.mem_to_finset at hz, obtain ⟨φ, rfl⟩ := (range_eval_eq_root_set_minpoly K A x).symm.subset hz, exact h φ, end variables (K A) /-- Let `B` be a real number. The set of algebraic integers in `K` whose conjugates are all smaller in norm than `B` is finite. -/ lemma finite_of_norm_le (B : ℝ) : {x : K | is_integral ℤ x ∧ ∀ φ : K →+* A, ‖φ x‖ ≤ B}.finite := begin let C := nat.ceil ((max B 1) ^ (finrank ℚ K) * (finrank ℚ K).choose ((finrank ℚ K) / 2)), have := bUnion_roots_finite (algebra_map ℤ K) (finrank ℚ K) (finite_Icc (-C : ℤ) C), refine this.subset (λ x hx, _), simp_rw mem_Union, have h_map_ℚ_minpoly := minpoly.is_integrally_closed_eq_field_fractions' ℚ hx.1, refine ⟨_, ⟨_, λ i, _⟩, mem_root_set.2 ⟨minpoly.ne_zero hx.1, minpoly.aeval ℤ x⟩⟩, { rw [← (minpoly.monic hx.1).nat_degree_map (algebra_map ℤ ℚ), ← h_map_ℚ_minpoly], exact minpoly.nat_degree_le (is_integral_of_is_scalar_tower hx.1) }, rw [mem_Icc, ← abs_le, ← @int.cast_le ℝ], refine (eq.trans_le _ $ coeff_bdd_of_norm_le hx.2 i).trans (nat.le_ceil _), rw [h_map_ℚ_minpoly, coeff_map, eq_int_cast, int.norm_cast_rat, int.norm_eq_abs, int.cast_abs], end /-- An algebraic integer whose conjugates are all of norm one is a root of unity. -/ lemma pow_eq_one_of_norm_eq_one {x : K} (hxi : is_integral ℤ x) (hx : ∀ φ : K →+* A, ‖φ x‖ = 1) : ∃ (n : ℕ) (hn : 0 < n), x ^ n = 1 := begin obtain ⟨a, -, b, -, habne, h⟩ := @set.infinite.exists_ne_map_eq_of_maps_to _ _ _ _ ((^) x : ℕ → K) set.infinite_univ _ (finite_of_norm_le K A (1:ℝ)), { wlog hlt : b < a, { exact this hxi hx b a habne.symm h.symm (habne.lt_or_lt.resolve_right hlt) }, refine ⟨a - b, tsub_pos_of_lt hlt, _⟩, rw [← nat.sub_add_cancel hlt.le, pow_add, mul_left_eq_self₀] at h, refine h.resolve_right (λ hp, _), specialize hx (is_alg_closed.lift (number_field.is_algebraic K)).to_ring_hom, rw [pow_eq_zero hp, map_zero, norm_zero] at hx, norm_num at hx }, { exact λ a _, ⟨hxi.pow a, λ φ, by simp only [hx φ, norm_pow, one_pow, map_pow]⟩ }, end end bounded end number_field.embeddings section place variables {K : Type*} [field K] {A : Type*} [normed_division_ring A] [nontrivial A] (φ : K →+* A) /-- An embedding into a normed division ring defines a place of `K` -/ def number_field.place : absolute_value K ℝ := (is_absolute_value.to_absolute_value (norm : A → ℝ)).comp φ.injective @[simp] lemma number_field.place_apply (x : K) : (number_field.place φ) x = norm (φ x) := rfl end place namespace number_field.complex_embedding open complex number_field open_locale complex_conjugate variables {K : Type*} [field K] /-- The conjugate of a complex embedding as a complex embedding. -/ @[reducible] def conjugate (φ : K →+* ℂ) : K →+* ℂ := star φ @[simp] lemma conjugate_coe_eq (φ : K →+* ℂ) (x : K) : (conjugate φ) x = conj (φ x) := rfl lemma place_conjugate (φ : K →+* ℂ) : place (conjugate φ) = place φ := by { ext, simp only [place_apply, norm_eq_abs, abs_conj, conjugate_coe_eq] } /-- A embedding into `ℂ` is real if it is fixed by complex conjugation. -/ @[reducible] def is_real (φ : K →+* ℂ) : Prop := is_self_adjoint φ lemma is_real_iff {φ : K →+* ℂ} : is_real φ ↔ conjugate φ = φ := is_self_adjoint_iff /-- A real embedding as a ring homomorphism from `K` to `ℝ` . -/ def is_real.embedding {φ : K →+* ℂ} (hφ : is_real φ) : K →+* ℝ := { to_fun := λ x, (φ x).re, map_one' := by simp only [map_one, one_re], map_mul' := by simp only [complex.conj_eq_iff_im.mp (ring_hom.congr_fun hφ _), map_mul, mul_re, mul_zero, tsub_zero, eq_self_iff_true, forall_const], map_zero' := by simp only [map_zero, zero_re], map_add' := by simp only [map_add, add_re, eq_self_iff_true, forall_const], } @[simp] lemma is_real.coe_embedding_apply {φ : K →+* ℂ} (hφ : is_real φ) (x : K) : (hφ.embedding x : ℂ) = φ x := begin ext, { refl, }, { rw [of_real_im, eq_comm, ← complex.conj_eq_iff_im], rw is_real at hφ, exact ring_hom.congr_fun hφ x, }, end lemma is_real.place_embedding {φ : K →+* ℂ} (hφ : is_real φ) : place hφ.embedding = place φ := by { ext x, simp only [place_apply, real.norm_eq_abs, ←abs_of_real, norm_eq_abs, hφ.coe_embedding_apply x], } lemma is_real_conjugate_iff {φ : K →+* ℂ} : is_real (conjugate φ) ↔ is_real φ := is_self_adjoint.star_iff end number_field.complex_embedding section infinite_place open number_field variables (K : Type*) [field K] /-- An infinite place of a number field `K` is a place associated to a complex embedding. -/ def number_field.infinite_place := { w : absolute_value K ℝ // ∃ φ : K →+* ℂ, place φ = w} instance [number_field K] : nonempty (number_field.infinite_place K) := set.range.nonempty _ variables {K} /-- Return the infinite place defined by a complex embedding `φ`. -/ noncomputable def number_field.infinite_place.mk (φ : K →+* ℂ) : number_field.infinite_place K := ⟨place φ, ⟨φ, rfl⟩⟩ namespace number_field.infinite_place open number_field instance : has_coe_to_fun (infinite_place K) (λ _, K → ℝ) := { coe := λ w, w.1 } instance : monoid_with_zero_hom_class (infinite_place K) K ℝ := { coe := λ w x, w.1 x, coe_injective' := λ _ _ h, subtype.eq (absolute_value.ext (λ x, congr_fun h x)), map_mul := λ w _ _, w.1.map_mul _ _, map_one := λ w, w.1.map_one, map_zero := λ w, w.1.map_zero, } instance : nonneg_hom_class (infinite_place K) K ℝ := { coe := λ w x, w x, coe_injective' := λ _ _ h, subtype.eq (absolute_value.ext (λ x, congr_fun h x)), map_nonneg := λ w x, w.1.nonneg _ } lemma coe_mk (φ : K →+* ℂ) : ⇑(mk φ) = place φ := rfl lemma apply (φ : K →+* ℂ) (x : K) : (mk φ) x = complex.abs (φ x) := rfl /-- For an infinite place `w`, return an embedding `φ` such that `w = infinite_place φ` . -/ noncomputable def embedding (w : infinite_place K) : K →+* ℂ := (w.2).some @[simp] lemma mk_embedding (w : infinite_place K) : mk (embedding w) = w := subtype.ext (w.2).some_spec @[simp] lemma abs_embedding (w : infinite_place K) (x : K) : complex.abs (embedding w x) = w x := congr_fun (congr_arg coe_fn w.2.some_spec) x lemma eq_iff_eq (x : K) (r : ℝ) : (∀ w : infinite_place K, w x = r) ↔ (∀ φ : K →+* ℂ, ‖φ x‖ = r) := ⟨λ hw φ, hw (mk φ), λ hφ ⟨w, ⟨φ, rfl⟩⟩, hφ φ⟩ lemma le_iff_le (x : K) (r : ℝ) : (∀ w : infinite_place K, w x ≤ r) ↔ (∀ φ : K →+* ℂ, ‖φ x‖ ≤ r) := ⟨λ hw φ, hw (mk φ), λ hφ ⟨w, ⟨φ, rfl⟩⟩, hφ φ⟩ lemma pos_iff {w : infinite_place K} {x : K} : 0 < w x ↔ x ≠ 0 := absolute_value.pos_iff w.1 @[simp] lemma mk_conjugate_eq (φ : K →+* ℂ) : mk (complex_embedding.conjugate φ) = mk φ := begin ext x, exact congr_fun (congr_arg coe_fn (complex_embedding.place_conjugate φ)) x, end @[simp] lemma mk_eq_iff {φ ψ : K →+* ℂ} : mk φ = mk ψ ↔ φ = ψ ∨ complex_embedding.conjugate φ = ψ := begin split, { -- We prove that the map ψ ∘ φ⁻¹ between φ(K) and ℂ is uniform continuous, thus it is either the -- inclusion or the complex conjugation using complex.uniform_continuous_ring_hom_eq_id_or_conj intro h₀, obtain ⟨j, hiφ⟩ := φ.injective.has_left_inverse, let ι := ring_equiv.of_left_inverse hiφ, have hlip : lipschitz_with 1 (ring_hom.comp ψ ι.symm.to_ring_hom), { change lipschitz_with 1 (ψ ∘ ι.symm), apply lipschitz_with.of_dist_le_mul, intros x y, rw [nonneg.coe_one, one_mul, normed_field.dist_eq, ← map_sub, ← map_sub], apply le_of_eq, suffices : ‖φ ((ι.symm) (x - y))‖ = ‖ψ ((ι.symm) (x - y))‖, { rw [← this, ← ring_equiv.of_left_inverse_apply hiφ _ , ring_equiv.apply_symm_apply ι _], refl, }, exact congr_fun (congr_arg coe_fn h₀) _, }, cases (complex.uniform_continuous_ring_hom_eq_id_or_conj φ.field_range hlip.uniform_continuous), { left, ext1 x, convert (congr_fun h (ι x)).symm, exact (ring_equiv.apply_symm_apply ι.symm x).symm, }, { right, ext1 x, convert (congr_fun h (ι x)).symm, exact (ring_equiv.apply_symm_apply ι.symm x).symm, }}, { rintros (⟨h⟩ | ⟨h⟩), { exact congr_arg mk h, }, { rw ← mk_conjugate_eq, exact congr_arg mk h, }}, end /-- An infinite place is real if it is defined by a real embedding. -/ def is_real (w : infinite_place K) : Prop := ∃ φ : K →+* ℂ, complex_embedding.is_real φ ∧ mk φ = w /-- An infinite place is complex if it is defined by a complex (ie. not real) embedding. -/ def is_complex (w : infinite_place K) : Prop := ∃ φ : K →+* ℂ, ¬ complex_embedding.is_real φ ∧ mk φ = w @[simp] lemma _root_.number_field.complex_embeddings.is_real.embedding_mk {φ : K →+* ℂ} (h : complex_embedding.is_real φ) : embedding (mk φ) = φ := begin have := mk_eq_iff.mp (mk_embedding (mk φ)).symm, rwa [complex_embedding.is_real_iff.mp h, or_self, eq_comm] at this, end lemma is_real_iff {w : infinite_place K} : is_real w ↔ complex_embedding.is_real (embedding w) := begin split, { rintros ⟨φ, ⟨hφ, rfl⟩⟩, rwa _root_.number_field.complex_embeddings.is_real.embedding_mk hφ, }, { exact λ h, ⟨embedding w, h, mk_embedding w⟩, }, end lemma is_complex_iff {w : infinite_place K} : is_complex w ↔ ¬ complex_embedding.is_real (embedding w) := begin split, { rintros ⟨φ, ⟨hφ, rfl⟩⟩, contrapose! hφ, cases mk_eq_iff.mp (mk_embedding (mk φ)), { rwa ← h, }, { rw ← complex_embedding.is_real_conjugate_iff at hφ, rwa ← h, }}, { exact λ h, ⟨embedding w, h, mk_embedding w⟩, }, end @[simp] lemma not_is_real_iff_is_complex {w : infinite_place K} : ¬ is_real w ↔ is_complex w := by rw [is_complex_iff, is_real_iff] @[simp] lemma not_is_complex_iff_is_real {w : infinite_place K} : ¬ is_complex w ↔ is_real w := by rw [←not_is_real_iff_is_complex, not_not] lemma is_real_or_is_complex (w : infinite_place K) : is_real w ∨ is_complex w := by { rw ←not_is_real_iff_is_complex, exact em _ } /-- For `w` a real infinite place, return the corresponding embedding as a morphism `K →+* ℝ`. -/ noncomputable def is_real.embedding {w : infinite_place K} (hw : is_real w) : K →+* ℝ := (is_real_iff.mp hw).embedding @[simp] lemma is_real.place_embedding_apply {w : infinite_place K} (hw : is_real w) (x : K): place (is_real.embedding hw) x = w x := begin rw [is_real.embedding, complex_embedding.is_real.place_embedding, ← coe_mk], exact congr_fun (congr_arg coe_fn (mk_embedding w)) x, end @[simp] lemma is_real.abs_embedding_apply {w : infinite_place K} (hw : is_real w) (x : K) : |is_real.embedding hw x| = w x := by { rw ← is_real.place_embedding_apply hw x, congr, } variable (K) /-- The map from real embeddings to real infinite places as an equiv -/ noncomputable def mk_real : {φ : K →+* ℂ // complex_embedding.is_real φ} ≃ {w : infinite_place K // is_real w} := { to_fun := subtype.map mk (λ φ hφ, ⟨φ, hφ, rfl⟩), inv_fun := λ w, ⟨w.1.embedding, is_real_iff.1 w.2⟩, left_inv := λ φ, subtype.ext_iff.2 (number_field.complex_embeddings.is_real.embedding_mk φ.2), right_inv := λ w, subtype.ext_iff.2 (mk_embedding w.1), } /-- The map from nonreal embeddings to complex infinite places -/ noncomputable def mk_complex : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ} → {w : infinite_place K // is_complex w} := subtype.map mk (λ φ hφ, ⟨φ, hφ, rfl⟩) lemma mk_complex_embedding (φ : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ}) : ((mk_complex K φ) : infinite_place K).embedding = φ ∨ ((mk_complex K φ) : infinite_place K).embedding = complex_embedding.conjugate φ := begin rw [@eq_comm _ _ ↑φ, @eq_comm _ _ (complex_embedding.conjugate ↑φ), ← mk_eq_iff, mk_embedding], refl, end @[simp] lemma mk_real_coe (φ : {φ : K →+* ℂ // complex_embedding.is_real φ}) : (mk_real K φ : infinite_place K) = mk (φ : K →+* ℂ) := rfl @[simp] lemma mk_complex_coe (φ : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ}) : (mk_complex K φ : infinite_place K) = mk (φ : K →+* ℂ) := rfl @[simp] lemma mk_real.apply (φ : {φ : K →+* ℂ // complex_embedding.is_real φ}) (x : K) : mk_real K φ x = complex.abs (φ x) := apply φ x @[simp] lemma mk_complex.apply (φ : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ}) (x : K) : mk_complex K φ x = complex.abs (φ x) := apply φ x variable [number_field K] lemma mk_complex.filter (w : { w : infinite_place K // w.is_complex }) : finset.univ.filter (λ φ, mk_complex K φ = w) = { ⟨w.1.embedding, is_complex_iff.1 w.2⟩, ⟨complex_embedding.conjugate w.1.embedding, complex_embedding.is_real_conjugate_iff.not.2 (is_complex_iff.1 w.2)⟩ } := begin ext φ, simp_rw [finset.mem_filter, subtype.val_eq_coe, finset.mem_insert, finset.mem_singleton, @subtype.ext_iff_val (infinite_place K), @subtype.ext_iff_val (K →+* ℂ), @eq_comm _ φ.val, ← mk_eq_iff, mk_embedding, @eq_comm _ _ w.val], simpa only [finset.mem_univ, true_and], end lemma mk_complex.filter_card (w : { w : infinite_place K // w.is_complex }) : (finset.univ.filter (λ φ, mk_complex K φ = w)).card = 2 := begin rw mk_complex.filter, exact finset.card_doubleton (subtype.mk_eq_mk.not.2 $ ne_comm.1 $ complex_embedding.is_real_iff.not.1 $ is_complex_iff.1 w.2), end noncomputable instance number_field.infinite_place.fintype : fintype (infinite_place K) := set.fintype_range _ /-- The infinite part of the product formula : for `x ∈ K`, we have `Π_w ‖x‖_w = |norm(x)|` where `‖·‖_w` is the normalized absolute value for `w`. -/ lemma prod_eq_abs_norm (x : K) : finset.univ.prod (λ w : infinite_place K, ite (w.is_real) (w x) ((w x) ^ 2)) = abs (algebra.norm ℚ x) := begin convert (congr_arg complex.abs (@algebra.norm_eq_prod_embeddings ℚ _ _ _ _ ℂ _ _ _ _ _ x)).symm, { rw [map_prod, ← equiv.prod_comp' ring_hom.equiv_rat_alg_hom (λ f, complex.abs (f x)) (λ φ, complex.abs (φ x)) (λ _, by simpa only [ring_hom.equiv_rat_alg_hom_apply])], dsimp only, conv { to_rhs, congr, skip, funext, rw ( by simp only [if_t_t] : complex.abs (f x) = ite (complex_embedding.is_real f) (complex.abs (f x)) (complex.abs (f x))) }, rw [finset.prod_ite, finset.prod_ite], refine congr (congr_arg has_mul.mul _) _, { rw [← finset.prod_subtype_eq_prod_filter, ← finset.prod_subtype_eq_prod_filter], convert (equiv.prod_comp' (mk_real K) (λ φ, complex.abs (φ x)) (λ w, w x) _).symm, any_goals { ext, simp only [finset.mem_subtype, finset.mem_univ], }, exact λ φ, mk_real.apply K φ x, }, { rw [finset.filter_congr (λ (w : infinite_place K) _, @not_is_real_iff_is_complex K _ w), ← finset.prod_subtype_eq_prod_filter, ← finset.prod_subtype_eq_prod_filter], convert finset.prod_fiberwise finset.univ (λ φ, mk_complex K φ) (λ φ, complex.abs (φ x)), any_goals { ext, simp only [finset.mem_subtype, finset.mem_univ, not_is_real_iff_is_complex], }, { ext w, rw [@finset.prod_congr _ _ _ _ _ (λ φ, w x) _ (eq.refl _) (λ φ hφ, (mk_complex.apply K φ x).symm.trans (congr_fun (congr_arg coe_fn (finset.mem_filter.1 hφ).2) x)), finset.prod_const, mk_complex.filter_card K w], refl, }}}, { rw [eq_rat_cast, ← complex.abs_of_real, complex.of_real_rat_cast], }, end open fintype lemma card_real_embeddings : card {φ : K →+* ℂ // complex_embedding.is_real φ} = card {w : infinite_place K // is_real w} := by convert (fintype.of_equiv_card (mk_real K)).symm lemma card_complex_embeddings : card {φ : K →+* ℂ // ¬ complex_embedding.is_real φ} = 2 * card {w : infinite_place K // is_complex w} := begin rw [fintype.card, fintype.card, mul_comm, ← algebra.id.smul_eq_mul, ← finset.sum_const], conv { to_rhs, congr, skip, funext, rw ← mk_complex.filter_card K x }, simp_rw finset.card_eq_sum_ones, exact (finset.sum_fiberwise finset.univ (λ φ, mk_complex K φ) (λ φ, 1)).symm end end number_field.infinite_place end infinite_place
2dc7e6a1b60b052d670feefb355518191a551144
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/padics/padic_integers.lean
949f31e3f1be2756a9c746b7714c4e05567f0fa6
[ "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
29,834
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin -/ import data.int.modeq import data.zmod.basic import linear_algebra.adic_completion import data.padics.padic_numbers import ring_theory.discrete_valuation_ring /-! # p-adic integers This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`. We show that `ℤ_p` * is complete * is nonarchimedean * is a normed ring * is a local ring * is a discrete valuation ring * has a ring hom to `ℤ/p^nℤ` for each `n` ## Important definitions * `padic_int` : the type of p-adic numbers * `to_zmod`: ring hom to `ℤ/pℤ` * `to_zmod_pow` : ring hom to `ℤ/p^nℤ` ## Notation We introduce the notation `ℤ_[p]` for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (nat.prime p)] as a type class argument. Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, p-adic integer -/ open nat padic metric local_ring noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int variables {p : ℕ} [fact p.prime] instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ @[ext] lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2 /-- Addition on ℤ_p is inherited from ℚ_p. -/ instance : has_add ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩ /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ instance : has_mul ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩ /-- Negation on ℤ_p is inherited from ℚ_p. -/ instance : has_neg ℤ_[p] := ⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩ /-- Zero on ℤ_p is inherited from ℚ_p. -/ instance : has_zero ℤ_[p] := ⟨⟨0, by norm_num⟩⟩ instance : inhabited ℤ_[p] := ⟨0⟩ /-- One on ℤ_p is inherited from ℚ_p. -/ instance : has_one ℤ_[p] := ⟨⟨1, by norm_num⟩⟩ @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl @[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 | ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n | 0 := rfl | (k+1) := by simp [coe_coe] @[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z | (int.of_nat n) := by simp | -[1+n] := by simp @[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl instance : ring ℤ_[p] := begin refine { add := (+), mul := (*), neg := has_neg.neg, zero := 0, one := 1, .. }; intros; ext; simp; ring end @[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma cast_pow (x : ℤ_[p]) : ∀ (n : ℕ), (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n | 0 := by simp | (k+1) := by simp [monoid.pow, pow]; congr; apply cast_pow @[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 instance : char_zero ℤ_[p] := { cast_injective := λ m n h, cast_injective $ show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } } @[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this, by norm_cast end padic_int section instances variables {p : ℕ} [fact p.prime] instance : metric_space ℤ_[p] := subtype.metric_space instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩ lemma padic_norm_z {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl instance : normed_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _ } instance padic_norm_z.is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _, abv_mul := λ _ _, by simp [padic_norm_z] } protected lemma padic_int.pmul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [mul_comm] instance : comm_ring ℤ_[p] := { mul_comm := padic_int.pmul_comm, ..padic_int.ring } protected lemma padic_int.zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one protected lemma padic_int.eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext_iff_val.1 h, (mul_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := padic_int.eq_zero_or_eq_zero_of_mul_eq_zero, exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩, ..padic_int.comm_ring } end instances namespace padic_norm_z variables {p : ℕ} [fact p.prime] lemma le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma one : ∥(1 : ℤ_[p])∥ = 1 := by simp [norm, padic_norm_z] @[simp] lemma mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by simp [padic_norm_z] @[simp] lemma pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw mul, congr, apply pow} theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne lemma norm_one : ∥(1 : ℤ_[p])∥ = 1 := normed_field.norm_one lemma eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [padic_norm_z] lemma padic_norm_z_of_int (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ := by simp [padic_norm_z] @[simp] lemma padic_norm_z_eq_padic_norm_e {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl @[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ := show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p @[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) := show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ), by { convert padic_norm_e.norm_p_pow n, simp, } end padic_norm_z namespace padic_int variables {p : ℕ} [hp_prime : fact p.prime] include hp_prime lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a := begin split, { intro h, cases h with w hw, have := congr_arg has_norm.norm hw, simp only [padic_norm_z.padic_norm_z_of_int, padic_norm_z.norm_p_pow, padic_norm_z.mul, fpow_neg, fpow_coe_nat] at this, rw_mod_cast [padic_norm_e.norm_int_lt_pow_iff_dvd, this], simp only [fpow_neg, fpow_coe_nat, nat.cast_pow], convert mul_le_of_le_one_right _ _ using 1, { apply inv_nonneg.mpr, apply pow_nonneg, exact_mod_cast le_of_lt hp_prime.pos }, { apply padic_norm_z.le_one } }, { intro h, simpa only [ring_hom.map_pow] using (int.cast_ring_hom ℤ_[p]).map_dvd h, } end /-! ### Valuation on `ℤ_[p]` -/ /-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/ def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p]) lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) : ∥x∥ = p^(-x.valuation) := begin convert padic.norm_eq_pow_val _, contrapose! hx, exact subtype.val_injective hx end @[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := padic.valuation_zero @[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := padic.valuation_one @[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation, -cast_eq_of_rat_of_nat] lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp [hx] }, have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.one_lt, rw [← neg_nonpos, ← (fpow_strict_mono h).le_iff_le], show (p : ℝ) ^ -valuation x ≤ p ^ 0, rw [← norm_eq_pow_val hx], simpa using x.property, end @[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) : (↑p ^ n * c).valuation = n + c.valuation := begin have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥, { exact padic_norm_z.mul _ _ }, have aux : ↑p ^ n * c ≠ 0, { contrapose! hc, rw mul_eq_zero at hc, cases hc, { refine (hp_prime.ne_zero _).elim, exact_mod_cast (pow_eq_zero hc) }, { exact hc } }, rwa [norm_eq_pow_val aux, padic_norm_z.norm_p_pow, norm_eq_pow_val hc, ← fpow_add, ← neg_add, fpow_inj, neg_inj] at this, { exact_mod_cast hp_prime.pos }, { exact_mod_cast hp_prime.ne_one }, { exact_mod_cast hp_prime.ne_zero }, end /-! ### Units of `ℤ_[p]` -/ local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (padic_norm_z.le_one _) _, have := mul_le_mul_of_nonneg_left (padic_norm_z.le_one w) (norm_nonneg z), rwa [mul_one, ← padic_norm_z.mul, ← eq, padic_norm_z.one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (padic_norm_z.nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (padic_norm_z.le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [padic_norm_z.le_one z, nonunits, is_unit_iff] /-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/ def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] := let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩ @[simp] lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u := rfl @[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 := is_unit_iff.mp $ by simp /-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`. See `unit_coeff_spec`. -/ def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] := let u : ℚ_[p] := x*p^(-x.valuation) in have hu : ∥u∥ = 1, by simp [hx, nat.fpow_ne_zero_of_pos (by exact_mod_cast hp_prime.pos) x.valuation, norm_eq_pow_val, fpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat], mk_units hu @[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) : (unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) : x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) := begin apply subtype.coe_injective, push_cast, have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation, { rw [unit_coeff_coe, mul_assoc, ← fpow_add], { simp }, { exact_mod_cast hp_prime.ne_zero } }, convert repr using 2, rw [← fpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)], end instance : local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, padic_norm_z] using f.cauchy hε ⟩ instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, padic_norm_z.le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, padic_norm_z] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ /-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/ def coe.ring_hom : ℤ_[p] →+* ℚ_[p] := { to_fun := (coe : ℤ_[p] → ℚ_[p]), map_zero' := rfl, map_one' := rfl, map_mul' := coe_mul, map_add' := coe_add } lemma p_dvd_of_norm_lt_one {x : ℤ_[p]} (hx : ∥x∥ < 1) : ↑p ∣ x := begin by_cases hx0 : x = 0, { simp only [hx0, dvd_zero] }, rw unit_coeff_spec hx0, by_cases H : x.valuation.nat_abs = 0, { rw [int.nat_abs_eq_zero] at H, rw [norm_eq_pow_val hx0, H, neg_zero, fpow_zero] at hx, exact (lt_irrefl _ hx).elim, }, { apply dvd_mul_of_dvd_right, exact dvd_pow (dvd_refl _) H, } end lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.one_lt, by simp [this] lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} := begin apply le_antisymm, { intros x hx, rw ideal.mem_span_singleton, simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx, exact p_dvd_of_norm_lt_one hx, }, { rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit } end lemma prime_p : prime (p : ℤ_[p]) := begin rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p], { apply_instance }, { exact_mod_cast hp_prime.ne_zero } end lemma irreducible_p : irreducible (p : ℤ_[p]) := irreducible_of_prime prime_p instance : discrete_valuation_ring ℤ_[p] := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization ⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx, by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩ lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) : ∃ n : ℕ, s = ideal.span {p ^ n} := discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k := suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa padic_norm_z.padic_norm_z_of_int, padic_norm_e.norm_int_lt_one_iff_dvd k lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x := begin rw [← mem_nonunits, ← local_ring.mem_maximal_ideal, maximal_ideal_eq_span_p, ideal.mem_span_singleton], end lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_coe], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : _ ... = 1 : mul_one 1, apply mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one, }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_z.padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.cast_mod_nat p, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime ‹_› _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end section variables (r : ℚ) variable (p) omit hp_prime /-- `mod_part r p` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.ne_zero variable {p} lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, by_cases aux : (⟨r,h⟩ - n : ℤ_[p]) = 0, { rw [aux, norm_zero], exact zero_lt_one, }, suffices : ↑p ∣ (⟨r,h⟩ - n : ℤ_[p]), { rcases this with ⟨x, hx⟩, calc ∥(⟨r,h⟩ - n : ℤ_[p])∥ = ∥(p : ℤ_[p])∥ * ∥x∥ : by rw [hx, padic_norm_z.mul] ... ≤ ∥(p : ℤ_[p])∥ * 1 : mul_le_mul (le_refl _) x.2 (norm_nonneg _) (norm_nonneg _) ... < 1 : _, { rw [mul_one, padic_norm_z.norm_p], apply inv_lt_one, exact_mod_cast hp_prime.one_lt }, }, rw ← (is_unit_denom r h).dvd_mul_right, suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_coe], rw_mod_cast @rat.mul_denom_eq_num r, refl }, dsimp [n, mod_part], apply norm_sub_mod_part_aux r h, end end section lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [_root_.pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw nat.pow_one) (zmod p) at this, simpa only [ring_hom.map_int_cast], end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, rw show (r : ℚ_[p]) = (r - x) + x, by ring, apply le_trans (padic_norm_e.nonarchimedean _ _), apply max_le (le_of_lt hr) x.2 }, have hnp := mod_part_lt_p p r, have hn := norm_sub_mod_part r H, lift mod_part p r to ℕ using mod_part_nonneg p r with n, use [n], split, {exact_mod_cast hnp}, simp only [padic_norm_z, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 end /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, have A : x * (y - f y) ∈ I := I.mul_mem_left (f_spec _), have B : (x - f x) * (f y) ∈ I := I.mul_mem_right (f_spec _), convert I.add_mem A B, rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp [zmod.val_cast_nat], rw mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', nat.pow_zero], }, simp only [appr, ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { simp [← nat.pow_eq_pow], apply pow_lt_pow hp_prime.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [nat.mul_sub_left_distrib, mul_one, ← nat.pow_succ], apply nat.add_sub_cancel' (le_of_lt hp) } } end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, { intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, { push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, by_cases hc0 : c.valuation.nat_abs = 0, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, have hcu : is_unit c, { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, fpow_zero], }, rcases hcu with ⟨c, rfl⟩, obtain rfl := discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, swap, { exact irreducible_p }, rw [← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec, }, { rw [_root_.zero_pow (nat.pos_of_ne_zero hc0)], simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', apply dvd_mul_of_dvd_right, apply dvd_pow (dvd_refl _), exact hc0, } } } end /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b; [simpa using ha, simpa using hb] }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end end padic_int namespace padic_norm_z variables {p : ℕ} [fact p.prime] lemma padic_val_of_cong_pow_p {z1 z2 : ℤ} {n : ℕ} (hz : z1 ≡ z2 [ZMOD ↑(p^n)]) : ∥(z1 - z2 : ℚ_[p])∥ ≤ ↑(↑p ^ (-n : ℤ) : ℚ) := have hdvd : ↑(p^n) ∣ z2 - z1, from int.modeq.modeq_iff_dvd.1 hz, have (z2 - z1 : ℚ_[p]) = ↑(↑(z2 - z1) : ℚ), by norm_cast, begin rw [norm_sub_rev, this, padic_norm_e.eq_padic_norm], exact_mod_cast padic_norm.dvd_iff_norm_le.mp hdvd end end padic_norm_z
2972b0ceb41d85031f0ee7a37d78fccbf02b6c99
4fa118f6209450d4e8d058790e2967337811b2b5
/src/Huber_pair.lean
d193c1f9f593b75923139eb7d2a2bc9ac5376a16
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
3,672
lean
import for_mathlib.integral_closure import power_bounded Huber_ring.basic /-! # Huber pairs This short file defines Huber pairs. A Huber pair consists of a Huber ring and a so-call ring of integral elements: an integrally closed, power bounded, open subring. A typical example is ℤ_p ⊆ ℚ_p. (However, this example is hard to use as is, because our fomalisation uses subrings and Lean's version of ℤ_p is not a subring of ℚ_p. This could be fixed by using injective ring homomorphisms instead of subrings.) -/ universes u v open_locale classical open power_bounded -- Notation for the power bounded subring local postfix `ᵒ` : 66 := power_bounded_subring set_option old_structure_cmd true /- An subring of a Huber ring is called a “ring of integral elements” if it is open, integrally closed, and power bounded. See [Wedhorn, Def 7.14].-/ structure is_ring_of_integral_elements (Rplus : Type u) (R : Type u) [comm_ring Rplus] [topological_space Rplus] [Huber_ring R] [algebra Rplus R] extends is_integrally_closed Rplus R, open_embedding (algebra_map R : Rplus → R) : Prop := (is_power_bounded : set.range (algebra_map R : Rplus → R) ≤ Rᵒ) namespace is_ring_of_integral_elements variables (Rplus : Type u) (R : Type u) variables [comm_ring Rplus] [topological_space Rplus] [Huber_ring R] [algebra Rplus R] lemma plus_is_topological_ring (h : is_ring_of_integral_elements Rplus R) : topological_ring Rplus := { continuous_add := begin rw h.to_open_embedding.to_embedding.to_inducing.continuous_iff, simp only [function.comp, algebra.map_add], apply continuous.add, all_goals { apply h.to_open_embedding.continuous.comp }, { exact continuous_fst }, { exact continuous_snd }, end, continuous_mul := begin rw h.to_open_embedding.to_embedding.to_inducing.continuous_iff, simp only [function.comp, algebra.map_mul], apply continuous.mul, all_goals { apply h.to_open_embedding.continuous.comp }, { exact continuous_fst }, { exact continuous_snd }, end, continuous_neg := begin rw h.to_open_embedding.to_embedding.to_inducing.continuous_iff, simp only [function.comp, algebra.map_neg], exact h.to_open_embedding.continuous.neg, end } end is_ring_of_integral_elements /-- A Huber pair consists of a Huber ring and a so-call ring of integral elements: an integrally closed, power bounded, open subring. (The name “Huber pair” was introduced by Scholze. Before that, they were called “affinoid rings”.) See [Wedhorn, Def 7.14].-/ structure Huber_pair := (plus : Type) -- change this to (Type u) to enable universes (carrier : Type) [ring : comm_ring plus] [top : topological_space plus] [Huber : Huber_ring carrier] [alg : algebra plus carrier] (intel : is_ring_of_integral_elements plus carrier) namespace Huber_pair variable (A : Huber_pair) /-- The coercion of a Huber pair to a type (the ambient ring).-/ instance : has_coe_to_sort Huber_pair := { S := Type, coe := Huber_pair.carrier } -- The following notation is very common in the literature. local postfix `⁺` : 66 := λ A : Huber_pair, A.plus /-- The Huber ring structure on a Huber pair. -/ instance : Huber_ring A := A.Huber /-- The ring structure on the ring of integral elements. -/ instance : comm_ring (A⁺) := A.ring /-- The algebra structure of a Huber pair. -/ instance : algebra (A⁺) A := A.alg /-- The topology on the ring of integral elements. -/ instance : topological_space (A⁺) := A.top /-- The ring of integral elements is a topological ring.-/ instance : topological_ring (A⁺) := is_ring_of_integral_elements.plus_is_topological_ring _ A A.intel end Huber_pair