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
33bdaa2972651c531b2071e108d770e8ad328393
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/t13.lean
cef8024b67b5acd19aa5fcac33203dbc2dac1600
[ "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
327
lean
prelude constant A : Type.{1} constant f : A → A → A constant g : A → A → A precedence `+` : 65 infixl + := f infixl + := g constant a : A constant b : A print raw a+b -- + is overloaded check fun (h : A → A → A) (infixl + := h), -- Like local declarations, local notation "shadows" global one. a+b
e1d086be1777cbea86b66e37c9766d087fe0def0
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/ring_theory/adjoin_root.lean
83445af23e45ad3ccf6e2360371617cfffc2ccf3
[ "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
3,691
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial ring_theory.principal_ideal_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open polynomial ideal def adjoin_root [comm_ring α] [decidable_eq α] (f : polynomial α) : Type u := ideal.quotient (span {f} : ideal (polynomial α)) namespace adjoin_root section comm_ring variables [comm_ring α] [decidable_eq α] (f : polynomial α) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ noncomputable instance : decidable_eq (adjoin_root f) := classical.dec_eq _ variable {f} def mk : polynomial α → adjoin_root f := ideal.quotient.mk _ def root : adjoin_root f := mk X def of (x : α) : adjoin_root f := mk (C x) instance adjoin_root.has_coe_t : has_coe_t α (adjoin_root f) := ⟨of⟩ instance mk.is_ring_hom : is_ring_hom (mk : polynomial α → adjoin_root f) := ideal.quotient.is_ring_hom_mk _ @[simp] lemma mk_self : (mk f : adjoin_root f) = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) instance : is_ring_hom (coe : α → adjoin_root f) := @is_ring_hom.comp _ _ _ _ C _ _ _ mk mk.is_ring_hom lemma eval₂_root (f : polynomial α) : f.eval₂ coe (root : adjoin_root f) = 0 := quotient.induction_on' (root : adjoin_root f) (λ (g : polynomial α) (hg : mk g = mk X), show finsupp.sum f (λ (e : ℕ) (a : α), mk (C a) * mk g ^ e) = 0, by simp only [hg, (is_semiring_hom.map_pow (mk : polynomial α → adjoin_root f) _ _).symm, (is_ring_hom.map_mul (mk : polynomial α → adjoin_root f)).symm]; rw [finsupp.sum, finset.sum_hom (mk : polynomial α → adjoin_root f), show finset.sum _ _ = _, from sum_C_mul_X_eq _, mk_self]) (show (root : adjoin_root f) = mk X, from rfl) lemma is_root_root (f : polynomial α) : is_root (f.map coe) (root : adjoin_root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring β] def lift (i : α → β) [is_ring_hom i] (x : β) (h : f.eval₂ i x = 0) : (adjoin_root f) → β := ideal.quotient.lift _ (eval₂ i x) $ λ g H, begin simp [mem_span_singleton] at H, cases H with y H, dsimp at H, rw [H, eval₂_mul], simp [h] end variables {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial α} : lift i a h (mk g) = g.eval₂ i a := ideal.quotient.lift_mk @[simp] lemma lift_root : lift i a h root = a := by simp [root, h] @[simp] lemma lift_of {x : α} : lift i a h x = i x := by show lift i a h (ideal.quotient.mk _ (C x)) = i x; convert ideal.quotient.lift_mk; simp instance is_ring_hom_lift : is_ring_hom (lift i a h) := by unfold lift; apply_instance end comm_ring variables [discrete_field α] {f : polynomial α} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial α)) := principal_ideal_domain.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : discrete_field (adjoin_root f) := ideal.quotient.field (span {f} : ideal (polynomial α)) instance : is_field_hom (coe : α → adjoin_root f) := by apply_instance instance lift_is_field_hom [field β] {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0} : is_field_hom (lift i a h) := by apply_instance lemma coe_injective : function.injective (coe : α → adjoin_root f) := is_field_hom.injective _ lemma mul_div_root_cancel (f : polynomial α) [irreducible f] : (X - C (root : adjoin_root f)) * (f.map coe / (X - C root)) = f.map coe := mul_div_eq_iff_is_root.2 $ is_root_root _ end adjoin_root
f0cdf48916a94106c2efc4fc0da228f0b4998d63
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/category_theory/groupoid.lean
23fd1e92bdde7aecedfb4cddffe78165c28f1f39
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
1,034
lean
/- Copyright (c) 2018 Reid Barton All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import category_theory.category import category_theory.isomorphism namespace category_theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation class groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) := (inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X)) (inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously) (comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously) restate_axiom groupoid.inv_comp' restate_axiom groupoid.comp_inv' attribute [simp] groupoid.inv_comp groupoid.comp_inv abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C instance of_groupoid {C : Type u} [groupoid.{v} C] {X Y : C} (f : X ⟶ Y) : is_iso f := { inv := groupoid.inv f } end category_theory
6243aa796b92dfd2dc30f1b17418a4b24ab856dc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/SSet.lean
578340f86402462562d3a02c867fb09298b73ca9
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,379
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.SMap namespace Lean /-- Staged set. It is just a simple wrapper on top of Staged maps. -/ def SSet (α : Type u) [BEq α] [Hashable α] := SMap α Unit namespace SSet variable {α : Type u} [BEq α] [Hashable α] instance : Inhabited (SSet α) := inferInstanceAs (Inhabited (SMap ..)) abbrev empty : SSet α := SMap.empty abbrev insert (s : SSet α) (a : α) : SSet α := SMap.insert s a () abbrev contains (s : SSet α) (a : α) : Bool := SMap.contains s a abbrev forM [Monad m] (s : SSet α) (f : α → m PUnit) : m PUnit := SMap.forM s fun a _ => f a /-- Move from stage 1 into stage 2. -/ abbrev switch (s : SSet α) : SSet α := SMap.switch s abbrev fold (f : σ → α → σ) (init : σ) (s : SSet α) : σ := SMap.fold (fun d a _ => f d a) init s abbrev size (s : SSet α) : Nat := SMap.size s def toList (m : SSet α) : List α := m.fold (init := []) fun es a => a::es end SSet end Lean def List.toSSet [BEq α] [Hashable α] (es : List α) : Lean.SSet α := es.foldl (init := {}) fun s a => s.insert a instance {_ : BEq α} {_ : Hashable α} [Repr α] : Repr (Lean.SSet α) where reprPrec v prec := Repr.addAppParen (reprArg v.toList ++ ".toSSet") prec
725950a956f5d7c420363a2f4c7c88c0787851d2
5719a16e23dfc08cdea7a5bf035b81690f307965
/stage0/src/Init/Data/Array/Basic.lean
875106bbdc49935e96cf3fd5d2b95dcb2c0e091d
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,820
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString import Init.Control.Id import Init.Util universes u v w /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) := (sz : Nat) (data : Fin sz → α) attribute [extern "lean_array_mk"] Array.mk attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_sz"] Array.sz @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.sz namespace Array variables {α : Type u} /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def mkEmpty (c : @& Nat) : Array α := { sz := 0, data := fun ⟨x, h⟩ => absurd h (Nat.notLtZero x) } @[extern "lean_array_push"] def push (a : Array α) (v : α) : Array α := { sz := Nat.succ a.sz, data := fun ⟨j, h₁⟩ => if h₂ : j = a.sz then v else a.data ⟨j, Nat.ltOfLeOfNe (Nat.leOfLtSucc h₁) h₂⟩ } @[extern "lean_mk_array"] def mkArray {α : Type u} (n : Nat) (v : α) : Array α := { sz := n, data := fun _ => v} theorem szMkArrayEq {α : Type u} (n : Nat) (v : α) : (mkArray n v).sz = n := rfl def empty : Array α := mkEmpty 0 instance : HasEmptyc (Array α) := ⟨Array.empty⟩ instance : Inhabited (Array α) := ⟨Array.empty⟩ def isEmpty (a : Array α) : Bool := a.size = 0 def singleton (v : α) : Array α := mkArray 1 v @[extern "lean_array_fget"] def get (a : @& Array α) (i : @& Fin a.size) : α := a.data i /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α := a.get ⟨i.toNat, h⟩ /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def get! [Inhabited α] (a : @& Array α) (i : @& Nat) : α := if h : i < a.size then a.get ⟨i, h⟩ else arbitrary α def back [Inhabited α] (a : Array α) : α := a.get! (a.size - 1) def get? (a : Array α) (i : Nat) : Option α := if h : i < a.size then some (a.get ⟨i, h⟩) else none def getD (a : Array α) (i : Nat) (v₀ : α) : α := if h : i < a.size then a.get ⟨i, h⟩ else v₀ def getOp [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁.symm ▸ h₂⟩ @[extern "lean_array_fset"] def set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { sz := a.sz, data := fun j => if h : i = j then v else a.data j } theorem szFSetEq (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size := rfl theorem szPushEq (a : Array α) (v : α) : (push a v).size = a.size + 1 := rfl /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α := a.set ⟨i.toNat, h⟩ v /- "Comfortable" version of `fset`. It performs a bound check at runtime. -/ @[extern "lean_array_set"] def set! (a : Array α) (i : @& Nat) (v : α) : Array α := if h : i < a.size then a.set ⟨i, h⟩ v else panic! "index out of bounds" @[extern "lean_array_fswap"] def swap (a : Array α) (i j : @& Fin a.size) : Array α := let v₁ := a.get i; let v₂ := a.get j; let a := a.set i v₂; a.set j v₁ @[extern "lean_array_swap"] def swap! (a : Array α) (i j : @& Nat) : Array α := if h₁ : i < a.size then if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩ else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt {α : Type} (a : Array α) (i : Fin a.size) (v : α) : α × Array α := let e := a.get i; let a := a.set i v; (e, a) -- TODO: delete as soon as we can define local instances @[neverExtract] private def swapAtPanic! [Inhabited α] (i : Nat) : α × Array α := panic! ("index " ++ toString i ++ " out of bounds") @[inline] def swapAt! {α : Type} (a : Array α) (i : Nat) (v : α) : α × Array α := if h : i < a.size then swapAt a ⟨i, h⟩ v else @swapAtPanic! _ ⟨v⟩ i @[extern "lean_array_pop"] def pop (a : Array α) : Array α := { sz := Nat.pred a.size, data := fun ⟨j, h⟩ => a.get ⟨j, Nat.ltOfLtOfLe h (Nat.predLe _)⟩ } -- TODO(Leo): justify termination using wf-rec partial def shrink : Array α → Nat → Array α | a, n => if n ≥ a.size then a else shrink a.pop n section variables {m : Type v → Type w} [Monad m] variables {β : Type v} {σ : Type u} -- TODO(Leo): justify termination using wf-rec @[specialize] partial def iterateMAux (a : Array α) (f : ∀ (i : Fin a.size), α → β → m β) : Nat → β → m β | i, b => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; f idx (a.get idx) b >>= iterateMAux (i+1) else pure b @[inline] def iterateM (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → m β) : m β := iterateMAux a f 0 b @[inline] def foldlM (f : β → α → m β) (init : β) (a : Array α) : m β := iterateM a init (fun _ b a => f a b) @[inline] def foldlFromM (f : β → α → m β) (init : β) (a : Array α) (beginIdx : Nat := 0) : m β := iterateMAux a (fun _ b a => f a b) beginIdx init -- TODO(Leo): justify termination using wf-rec @[specialize] partial def iterateM₂Aux (a₁ : Array α) (a₂ : Array σ) (f : ∀ (i : Fin a₁.size), α → σ → β → m β) : Nat → β → m β | i, b => if h₁ : i < a₁.size then let idx₁ : Fin a₁.size := ⟨i, h₁⟩; if h₂ : i < a₂.size then let idx₂ : Fin a₂.size := ⟨i, h₂⟩; f idx₁ (a₁.get idx₁) (a₂.get idx₂) b >>= iterateM₂Aux (i+1) else pure b else pure b @[inline] def iterateM₂ (a₁ : Array α) (a₂ : Array σ) (b : β) (f : ∀ (i : Fin a₁.size), α → σ → β → m β) : m β := iterateM₂Aux a₁ a₂ f 0 b @[inline] def foldlM₂ (f : β → α → σ → m β) (b : β) (a₁ : Array α) (a₂ : Array σ): m β := iterateM₂ a₁ a₂ b (fun _ a₁ a₂ b => f b a₁ a₂) @[specialize] partial def findSomeMAux (a : Array α) (f : α → m (Option β)) : Nat → m (Option β) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; do r ← f (a.get idx); match r with | some v => pure r | none => findSomeMAux (i+1) else pure none @[inline] def findSomeM? (a : Array α) (f : α → m (Option β)) : m (Option β) := findSomeMAux a f 0 @[specialize] partial def findSomeRevMAux (a : Array α) (f : α → m (Option β)) : ∀ (idx : Nat), idx ≤ a.size → m (Option β) | i, h => if hLt : 0 < i then have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0); have i - 1 < a.size from Nat.ltOfLtOfLe this h; let idx : Fin a.size := ⟨i - 1, this⟩; do r ← f (a.get idx); match r with | some v => pure r | none => have i - 1 ≤ a.size from Nat.leOfLt this; findSomeRevMAux (i-1) this else pure none @[inline] def findSomeRevM? (a : Array α) (f : α → m (Option β)) : m (Option β) := findSomeRevMAux a f a.size (Nat.leRefl _) end -- TODO(Leo): justify termination using wf-rec @[specialize] partial def findMAux {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : Nat → m (Option α) | i => if h : i < a.size then do let v := a.get ⟨i, h⟩; condM (p v) (pure (some v)) (findMAux (i+1)) else pure none @[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : m (Option α) := findMAux a p 0 @[inline] def find? {α : Type} (a : Array α) (p : α → Bool) : Option α := Id.run $ a.findM? p @[specialize] partial def findRevMAux {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : ∀ (idx : Nat), idx ≤ a.size → m (Option α) | i, h => if hLt : 0 < i then have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0); have i - 1 < a.size from Nat.ltOfLtOfLe this h; let v := a.get ⟨i - 1, this⟩; do { condM (p v) (pure (some v)) $ have i - 1 ≤ a.size from Nat.leOfLt this; findRevMAux (i-1) this } else pure none @[inline] def findRevM? {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : m (Option α) := findRevMAux a p a.size (Nat.leRefl _) @[inline] def findRev? {α : Type} (a : Array α) (p : α → Bool) : Option α := Id.run $ a.findRevM? p section variables {β : Type w} {σ : Type u} @[inline] def iterate (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → β) : β := Id.run $ iterateMAux a f 0 b @[inline] def iterateFrom (a : Array α) (b : β) (i : Nat) (f : ∀ (i : Fin a.size), α → β → β) : β := Id.run $ iterateMAux a f i b @[inline] def foldl (f : β → α → β) (init : β) (a : Array α) : β := iterate a init (fun _ a b => f b a) @[inline] def foldlFrom (f : β → α → β) (init : β) (a : Array α) (beginIdx : Nat := 0) : β := Id.run $ foldlFromM f init a beginIdx @[inline] def iterate₂ (a₁ : Array α) (a₂ : Array σ) (b : β) (f : ∀ (i : Fin a₁.size), α → σ → β → β) : β := Id.run $ iterateM₂Aux a₁ a₂ f 0 b @[inline] def foldl₂ (f : β → α → σ → β) (b : β) (a₁ : Array α) (a₂ : Array σ) : β := iterate₂ a₁ a₂ b (fun _ a₁ a₂ b => f b a₁ a₂) @[inline] def findSome? (a : Array α) (f : α → Option β) : Option β := Id.run $ findSomeMAux a f 0 @[inline] def findSome! [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? (a : Array α) (f : α → Option β) : Option β := Id.run $ findSomeRevMAux a f a.size (Nat.leRefl _) @[inline] def findSomeRev! [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSomeRev? a f with | some b => b | none => panic! "failed to find element" @[specialize] partial def findIdxMAux {m : Type → Type u} [Monad m] (a : Array α) (p : α → m Bool) : Nat → m (Option Nat) | i => if h : i < a.size then condM (p (a.get ⟨i, h⟩)) (pure (some i)) (findIdxMAux (i+1)) else pure none @[inline] def findIdxM? {m : Type → Type u} [Monad m] (a : Array α) (p : α → m Bool) : m (Option Nat) := findIdxMAux a p 0 @[specialize] partial def findIdxAux (a : Array α) (p : α → Bool) : Nat → Option Nat | i => if h : i < a.size then if p (a.get ⟨i, h⟩) then some i else findIdxAux (i+1) else none @[inline] def findIdx? (a : Array α) (p : α → Bool) : Option Nat := findIdxAux a p 0 @[inline] def findIdx! (a : Array α) (p : α → Bool) : Nat := match findIdxAux a p 0 with | some i => i | none => panic! "failed to find element" def getIdx? [HasBeq α] (a : Array α) (v : α) : Option Nat := a.findIdx? $ fun a => a == v end section variables {m : Type → Type w} [Monad m] @[specialize] partial def anyRangeMAux (a : Array α) (endIdx : Nat) (hlt : endIdx ≤ a.size) (p : α → m Bool) : Nat → m Bool | i => if h : i < endIdx then let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe h hlt⟩; do b ← p (a.get idx); match b with | true => pure true | false => anyRangeMAux (i+1) else pure false @[inline] def anyM (a : Array α) (p : α → m Bool) : m Bool := anyRangeMAux a a.size (Nat.leRefl _) p 0 @[inline] def allM (a : Array α) (p : α → m Bool) : m Bool := do b ← anyM a (fun v => do b ← p v; pure (!b)); pure (!b) @[inline] def anyRangeM (a : Array α) (beginIdx endIdx : Nat) (p : α → m Bool) : m Bool := if h : endIdx ≤ a.size then anyRangeMAux a endIdx h p beginIdx else anyRangeMAux a a.size (Nat.leRefl _) p beginIdx @[inline] def allRangeM (a : Array α) (beginIdx endIdx : Nat) (p : α → m Bool) : m Bool := do b ← anyRangeM a beginIdx endIdx (fun v => do b ← p v; pure b); pure (!b) end @[inline] def any (a : Array α) (p : α → Bool) : Bool := Id.run $ anyM a p @[inline] def anyRange (a : Array α) (beginIdx endIdx : Nat) (p : α → Bool) : Bool := Id.run $ anyRangeM a beginIdx endIdx p @[inline] def anyFrom (a : Array α) (beginIdx : Nat) (p : α → Bool) : Bool := Id.run $ anyRangeM a beginIdx a.size p @[inline] def all (a : Array α) (p : α → Bool) : Bool := !any a (fun v => !p v) @[inline] def allRange (a : Array α) (beginIdx endIdx : Nat) (p : α → Bool) : Bool := !anyRange a beginIdx endIdx (fun v => !p v) section variables {m : Type v → Type w} [Monad m] variable {β : Type v} @[specialize] private def iterateRevMAux (a : Array α) (f : ∀ (i : Fin a.size), α → β → m β) : ∀ (i : Nat), i ≤ a.size → β → m β | 0, h, b => pure b | j+1, h, b => do let i : Fin a.size := ⟨j, h⟩; b ← f i (a.get i) b; iterateRevMAux j (Nat.leOfLt h) b @[inline] def iterateRevM (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → m β) : m β := iterateRevMAux a f a.size (Nat.leRefl _) b @[inline] def foldrM (f : α → β → m β) (init : β) (a : Array α) : m β := iterateRevM a init (fun _ => f) @[specialize] private def foldrRangeMAux (a : Array α) (f : α → β → m β) (beginIdx : Nat) : ∀ (i : Nat), i ≤ a.size → β → m β | 0, h, b => pure b | j+1, h, b => do let i : Fin a.size := ⟨j, h⟩; b ← f (a.get i) b; if j == beginIdx then pure b else foldrRangeMAux j (Nat.leOfLt h) b @[inline] def foldrRangeM (beginIdx endIdx : Nat) (f : α → β → m β) (ini : β) (a : Array α) : m β := if h : endIdx ≤ a.size then foldrRangeMAux a f beginIdx endIdx h ini else foldrRangeMAux a f beginIdx a.size (Nat.leRefl _) ini @[specialize] partial def foldlStepMAux (step : Nat) (a : Array α) (f : β → α → m β) : Nat → β → m β | i, b => if h : i < a.size then do let curr := a.get ⟨i, h⟩; b ← f b curr; foldlStepMAux (i+step) b else pure b @[inline] def foldlStepM (f : β → α → m β) (init : β) (step : Nat) (a : Array α) : m β := foldlStepMAux step a f 0 init end @[inline] def iterateRev {β} (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → β) : β := Id.run $ iterateRevM a b f @[inline] def foldr {β} (f : α → β → β) (init : β) (a : Array α) : β := Id.run $ foldrM f init a @[inline] def foldrRange {β} (beginIdx endIdx : Nat) (f : α → β → β) (init : β) (a : Array α) : β := Id.run $ foldrRangeM beginIdx endIdx f init a @[inline] def foldlStep {β} (f : β → α → β) (init : β) (step : Nat) (a : Array α) : β := Id.run $ foldlStepM f init step a @[inline] def getEvenElems (a : Array α) : Array α := a.foldlStep (fun r a => Array.push r a) empty 2 def toList (a : Array α) : List α := a.foldr List.cons [] instance [HasRepr α] : HasRepr (Array α) := ⟨fun a => "#" ++ repr a.toList⟩ instance [HasToString α] : HasToString (Array α) := ⟨fun a => "#" ++ toString a.toList⟩ section variables {m : Type v → Type w} [Monad m] variable {β : Type v} @[specialize] unsafe partial def umapMAux (f : Nat → α → m β) : Nat → Array NonScalar → m (Array PNonScalar.{v}) | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let v : NonScalar := a.get idx; let a := a.set idx (arbitrary _); do newV ← f i (unsafeCast v); umapMAux (i+1) (a.set idx (unsafeCast newV)) else pure (unsafeCast a) @[inline] unsafe partial def umapM (f : α → m β) (as : Array α) : m (Array β) := @unsafeCast (m (Array PNonScalar.{v})) (m (Array β)) $ umapMAux (fun i a => f a) 0 (unsafeCast as) @[inline] unsafe partial def umapIdxM (f : Nat → α → m β) (as : Array α) : m (Array β) := @unsafeCast (m (Array PNonScalar.{v})) (m (Array β)) $ umapMAux f 0 (unsafeCast as) @[implementedBy Array.umapM] def mapM (f : α → m β) (as : Array α) : m (Array β) := as.foldlM (fun bs a => do b ← f a; pure (bs.push b)) (mkEmpty as.size) @[implementedBy Array.umapIdxM] def mapIdxM (f : Nat → α → m β) (as : Array α) : m (Array β) := as.iterateM (mkEmpty as.size) (fun i a bs => do b ← f i.val a; pure (bs.push b)) end section variables {m : Type u → Type v} [Monad m] @[inline] def modifyM [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) := if h : i < a.size then do let idx : Fin a.size := ⟨i, h⟩; let v := a.get idx; let a := a.set idx (arbitrary α); v ← f v; pure $ (a.set idx v) else pure a end section variable {β : Type v} @[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α := Id.run $ a.modifyM i f @[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α := self.modify idx f @[inline] def mapIdx (f : Nat → α → β) (a : Array α) : Array β := Id.run $ mapIdxM f a @[inline] def map (f : α → β) (as : Array α) : Array β := Id.run $ mapM f as end section variables {m : Type v → Type w} [Monad m] variable {β : Type v} @[specialize] partial def forMAux (f : α → m β) (a : Array α) : Nat → m PUnit | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let v : α := a.get idx; do f v; forMAux (i+1) else pure ⟨⟩ @[inline] def forM (f : α → m β) (a : Array α) : m PUnit := a.forMAux f 0 @[specialize] partial def forRevMAux (f : α → m β) (a : Array α) : forall (i : Nat), i ≤ a.size → m PUnit | i, h => if hLt : 0 < i then have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0); have i - 1 < a.size from Nat.ltOfLtOfLe this h; let v : α := a.get ⟨i-1, this⟩; have i - 1 ≤ a.size from Nat.leOfLt this; do f v; forRevMAux (i-1) this else pure ⟨⟩ @[inline] def forRevM (f : α → m β) (a : Array α) : m PUnit := a.forRevMAux f a.size (Nat.leRefl _) end -- TODO(Leo): justify termination using wf-rec partial def extractAux (a : Array α) : Nat → ∀ (e : Nat), e ≤ a.size → Array α → Array α | i, e, hle, r => if hlt : i < e then let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe hlt hle⟩; extractAux (i+1) e hle (r.push (a.get idx)) else r def extract (a : Array α) (b e : Nat) : Array α := let r : Array α := mkEmpty (e - b); if h : e ≤ a.size then extractAux a b e h r else r protected def append (a : Array α) (b : Array α) : Array α := b.foldl (fun a v => a.push v) a instance : HasAppend (Array α) := ⟨Array.append⟩ -- TODO(Leo): justify termination using wf-rec @[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) : Nat → Bool | i => if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz ▸ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux (i+1) | false => false else true @[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [HasBeq α] : HasBeq (Array α) := ⟨fun a b => isEqv a b HasBeq.beq⟩ -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverseAux : Array α → Nat → Array α | a, i => let n := a.size; if i < n / 2 then reverseAux (a.swap! i (n - i - 1)) (i+1) else a def reverse (a : Array α) : Array α := reverseAux a 0 -- TODO(Leo): justify termination using wf-rec @[specialize] partial def filterAux (p : α → Bool) : Array α → Nat → Nat → Array α | a, i, j => if h₁ : i < a.size then if p (a.get ⟨i, h₁⟩) then if h₂ : j < i then filterAux (a.swap ⟨i, h₁⟩ ⟨j, Nat.ltTrans h₂ h₁⟩) (i+1) (j+1) else filterAux a (i+1) (j+1) else filterAux a (i+1) j else a.shrink j @[inline] def filter (p : α → Bool) (as : Array α) : Array α := filterAux p as 0 0 @[specialize] partial def filterMAux {m : Type → Type} [Monad m] {α : Type} (p : α → m Bool) : Array α → Nat → Nat → m (Array α) | a, i, j => if h₁ : i < a.size then condM (p (a.get ⟨i, h₁⟩)) (if h₂ : j < i then filterMAux (a.swap ⟨i, h₁⟩ ⟨j, Nat.ltTrans h₂ h₁⟩) (i+1) (j+1) else filterMAux a (i+1) (j+1)) (filterMAux a (i+1) j) else pure $ a.shrink j @[inline] def filterM {m : Type → Type} [Monad m] {α : Type} (p : α → m Bool) (as : Array α) : m (Array α) := filterMAux p as 0 0 partial def indexOfAux {α} [HasBeq α] (a : Array α) (v : α) : Nat → Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux (i+1) else none def indexOf {α} [HasBeq α] (a : Array α) (v : α) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux {α} : Nat → Array α → Array α | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx {α} (a : Array α) (i : Fin a.size) : Array α := eraseIdxAux (i.val + 1) a def eraseIdx {α} (a : Array α) (i : Nat) : Array α := if i < a.size then eraseIdxAux (i+1) a else a theorem szFSwapEq (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size := rfl theorem szPopEq (a : Array α) : a.pop.size = a.size - 1 := rfl section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } := ⟨⟨a.pop, szPopEq a⟩⟩ partial def eraseIdxSzAux {α} (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxSzAux (i+1) (r.swap idx idx1) ((szFSwapEq r idx idx1).trans heq) else ⟨r.pop, (szPopEq r).trans (heq ▸ rfl)⟩ end def eraseIdx' {α} (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def contains [HasBeq α] (as : Array α) (a : α) : Bool := as.any $ fun b => a == b def elem [HasBeq α] (a : α) (as : Array α) : Bool := as.contains a partial def insertAtAux {α} (i : Nat) : Array α → Nat → Array α | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt {α} (as : Array α) (i : Nat) (a : α) : Array α := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size theorem ext {α : Type u} (a b : Array α) : a.size = b.size → (∀ (i : Nat) (hi₁ : i < a.size) (hi₂ : i < b.size) , a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) → a = b := match a, b with | ⟨sz₁, f₁⟩, ⟨sz₂, f₂⟩ => show sz₁ = sz₂ → (∀ (i : Nat) (hi₁ : i < sz₁) (hi₂ : i < sz₂) , f₁ ⟨i, hi₁⟩ = f₂ ⟨i, hi₂⟩) → Array.mk sz₁ f₁ = Array.mk sz₂ f₂ from fun h₁ h₂ => match sz₁, sz₂, f₁, f₂, h₁, h₂ with | sz, _, f₁, f₂, rfl, h₂ => have f₁ = f₂ from funext $ fun ⟨i, hi₁⟩ => h₂ i hi₁ hi₁; congrArg _ this theorem extLit {α : Type u} {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : ∀ (i : Nat) (hi : i < n), a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) $ fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) end Array export Array (mkArray) @[inlineIfReduce] def List.toArrayAux {α : Type u} : List α → Array α → Array α | [], r => r | a::as, r => List.toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength {α : Type u} : List α → Nat | [] => 0 | _::as => as.redLength + 1 @[inline] def List.toArray {α : Type u} (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength)
2707ebccf7f0b9ae1c5468e56fefb5903dcc6ddb
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/270.lean
6d6b122b6d67cad36f978981bd50549d0cfe25c3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,083
lean
class CommAddSemigroup (α : Type u) extends Add α where addComm : {a b : α} → a + b = b + a addAssoc : {a b c : α} → a + b + c = a + (b + c) open CommAddSemigroup theorem addComm3 [CommAddSemigroup α] {a b c : α} : a + b + c = a + c + b := by { have h : b + c = c + b := addComm; have h' := congrArg (a + .) h; simp at h'; rw [←addAssoc] at h'; rw [←addAssoc (a := a)] at h'; exact h'; } theorem addComm4 [CommAddSemigroup α] {a b c : α} : a + b + c = a + c + b := by { rw [addAssoc, addAssoc]; rw [addComm (a := b)]; } theorem addComm5 [CommAddSemigroup α] {a b c : α} : a + b + c = a + c + b := by { have h : b + c = c + b := addComm; have h' := congrArg (a + .) h; simp at h'; rw [←addAssoc] at h'; rw [←@addAssoc (a := a)] at h'; exact h'; } theorem addComm6 [CommAddSemigroup α] {a b c : α} : a + b + c = a + c + b := by { have h : b + c = c + b := addComm; have h' := congrArg (a + .) h; simp at h'; rw [←addAssoc] at h'; rw [←addAssoc] at h'; exact h'; }
1834d5e85c8740fe1c118a07c3fd9c1fe8bcaedc
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.22.lean
da22fad0928e1b41d20c90199a96657752b04ea1
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
225
lean
/- page 40 -/ import standard variables p q r: Prop -- BEGIN example (H : p ∨ q) : q ∨ p := or.elim H (assume Hp : p, show q ∨ p, from or.intro_right q Hp) (assume Hq : q, show q ∨ p, from or.intro_left p Hq) -- END
fc29a24fd0c3b8068cd718cedbc11a619cdebd49
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/ordered_ring.lean
b61bae03643de571aa7339a53df69f81d346a229
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,617
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.ordered_group import algebra.invertible import data.set.intervals.basic set_option old_structure_cmd true universe u variable {α : Type u} lemma add_one_le_two_mul [preorder α] [semiring α] [covariant_class α α (+) (≤)] {a : α} (a1 : 1 ≤ a) : a + 1 ≤ 2 * a := calc a + 1 ≤ a + a : add_le_add_left a1 a ... = 2 * a : (two_mul _).symm /-- An `ordered_semiring α` is a semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (zero_le_one : 0 ≤ (1 : α)) (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} @[simp] lemma zero_le_one : 0 ≤ (1:α) := ordered_semiring.zero_le_one lemma zero_le_two : 0 ≤ (2:α) := add_nonneg zero_le_one zero_le_one lemma one_le_two : 1 ≤ (2:α) := calc (1:α) = 0 + 1 : (zero_add _).symm ... ≤ 1 + 1 : add_le_add_right zero_le_one _ section nontrivial variables [nontrivial α] @[simp] lemma zero_lt_one : 0 < (1 : α) := lt_of_le_of_ne zero_le_one zero_ne_one lemma zero_lt_two : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt zero_lt_two) lemma one_lt_two : 1 < (2:α) := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma zero_lt_three : 0 < (3:α) := add_pos zero_lt_two zero_lt_one lemma zero_lt_four : 0 < (4:α) := add_pos zero_lt_two zero_lt_two end nontrivial lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonneg_right -- TODO: there are four variations, depending on which variables we assume to be nonneg -- See Note [decidable namespace] protected lemma decidable.mul_le_mul [@decidable_rel α (≤)] (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_le_mul : a ≤ c → b ≤ d → 0 ≤ b → 0 ≤ c → a * b ≤ c * d := by classical; exact decidable.mul_le_mul -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] [@decidable_rel α (≤)] {a b c : α} (h₁ : 0 ≤ c) (h₂ : a ≤ c) (h₃ : 0 ≤ b) (h₄ : b ≤ 1) : a * b ≤ c := by simpa only [mul_one] using decidable.mul_le_mul h₂ h₄ h₃ h₁ lemma mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] {a b c : α} : 0 ≤ c → a ≤ c → 0 ≤ b → b ≤ 1 → a * b ≤ c := by classical; exact decidable.mul_nonneg_le_one_le -- See Note [decidable namespace] protected lemma decidable.mul_nonneg [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := have h : 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonneg_of_nonpos [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from decidable.mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonneg_of_nonpos : 0 ≤ a → b ≤ 0 → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonneg_of_nonpos -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonpos_of_nonneg [@decidable_rel α (≤)] (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_nonpos_of_nonpos_of_nonneg : a ≤ 0 → 0 ≤ b → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonpos_of_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul [@decidable_rel α (≤)] (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul : a < c → b ≤ d → 0 < b → 0 ≤ c → a * b < c * d := by classical; exact decidable.mul_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul' [@decidable_rel α (≤)] (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_lt_mul' : a ≤ c → b < d → 0 ≤ b → 0 < c → a * b < c * d := by classical; exact decidable.mul_lt_mul' lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h -- See Note [decidable namespace] protected lemma decidable.mul_self_lt_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := decidable.mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 -- See Note [decidable namespace] protected lemma decidable.strict_mono_incr_on_mul_self [@decidable_rel α (≤)] : strict_mono_incr_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, decidable.mul_self_lt_mul_self hx hxy lemma strict_mono_incr_on_mul_self : strict_mono_incr_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, mul_self_lt_mul_self hx hxy -- See Note [decidable namespace] protected lemma decidable.mul_self_le_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := decidable.mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul'' [@decidable_rel α (≤)] (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := h4.lt_or_eq_dec.elim (λ b0, decidable.mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma mul_lt_mul'' : a < c → b < d → 0 ≤ a → 0 ≤ b → a * b < c * d := by classical; exact decidable.mul_lt_mul'' -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_right [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, decidable.mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_right : 0 ≤ b → 1 ≤ a → b ≤ b * a := by classical; exact decidable.le_mul_of_one_le_right -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, decidable.mul_le_mul_of_nonneg_right h hb lemma le_mul_of_one_le_left : 0 ≤ b → 1 ≤ a → b ≤ a * b := by classical; exact decidable.le_mul_of_one_le_left -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_right [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, decidable.mul_lt_mul' (le_refl _) h zero_le_one hb lemma lt_mul_of_one_lt_right : 0 < b → 1 < a → b < b * a := by classical; exact decidable.lt_mul_of_one_lt_right -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_left [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < a * b := suffices 1 * b < a * b, by rwa one_mul at this, decidable.mul_lt_mul h (le_refl _) hb (zero_le_one.trans h.le) lemma lt_mul_of_one_lt_left : 0 < b → 1 < a → b < a * b := by classical; exact decidable.lt_mul_of_one_lt_left -- See Note [decidable namespace] protected lemma decidable.add_le_mul_two_add [@decidable_rel α (≤)] {a b : α} (a2 : 2 ≤ a) (b0 : 0 ≤ b) : a + (2 + b) ≤ a * (2 + b) := calc a + (2 + b) ≤ a + (a + a * b) : add_le_add_left (add_le_add a2 (decidable.le_mul_of_one_le_left b0 (one_le_two.trans a2))) a ... ≤ a * (2 + b) : by rw [mul_add, mul_two, add_assoc] lemma add_le_mul_two_add {a b : α} : 2 ≤ a → 0 ≤ b → a + (2 + b) ≤ a * (2 + b) := by classical; exact decidable.add_le_mul_two_add -- See Note [decidable namespace] protected lemma decidable.one_le_mul_of_one_le_of_one_le [@decidable_rel α (≤)] {a b : α} (a1 : 1 ≤ a) (b1 : 1 ≤ b) : (1 : α) ≤ a * b := (mul_one (1 : α)).symm.le.trans (decidable.mul_le_mul a1 b1 zero_le_one (zero_le_one.trans a1)) lemma one_le_mul_of_one_le_of_one_le {a b : α} : 1 ≤ a → 1 ≤ b → (1 : α) ≤ a * b := by classical; exact decidable.one_le_mul_of_one_le_of_one_le /-- Pullback an `ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_semiring β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, zero_le_one], mul_lt_mul_of_pos_left := λ a b c ab c0, show f (c * a) < f (c * b), begin rw [mul, mul], refine mul_lt_mul_of_pos_left ab _, rwa ← zero, end, mul_lt_mul_of_pos_right := λ a b c ab c0, show f (a * c) < f (b * c), begin rw [mul, mul], refine mul_lt_mul_of_pos_right ab _, rwa ← zero, end, ..hf.ordered_cancel_add_comm_monoid f zero add, ..hf.semiring f zero one add mul } section variable [nontrivial α] lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } end lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := begin nontriviality, exact bit1_pos h.le, end -- See Note [decidable namespace] protected lemma decidable.one_lt_mul [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, exact (one_mul (1 : α)) ▸ decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_le_one [@decidable_rel α (≤)] (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply decidable.mul_le_mul; {assumption <|> apply zero_le_one} end lemma mul_le_one : a ≤ 1 → 0 ≤ b → b ≤ 1 → a * b ≤ 1 := by classical; exact decidable.mul_le_one -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_le_of_lt [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul_of_le_of_lt : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_le_of_lt -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_lt_of_le [@decidable_rel α (≤)] (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le end lemma one_lt_mul_of_lt_of_le : 1 < a → 1 ≤ b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_lt_of_le -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_right [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : decidable.mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_right : 0 ≤ a → b ≤ 1 → a * b ≤ a := by classical; exact decidable.mul_le_of_le_one_right -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : decidable.mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_le_of_le_one_left : 0 ≤ b → a ≤ 1 → a * b ≤ b := by classical; exact decidable.mul_le_of_le_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_left [@decidable_rel α (≤)] (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : decidable.mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_left : 0 ≤ a → a < 1 → b ≤ 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_right [@decidable_rel α (≤)] (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : decidable.mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_lt_one_of_nonneg_of_lt_one_right : a ≤ 1 → 0 ≤ b → b < 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_right end ordered_semiring section ordered_comm_semiring /-- An `ordered_comm_semiring α` is a commutative semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_comm_semiring (α : Type u) extends ordered_semiring α, comm_semiring α /-- Pullback an `ordered_comm_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_semiring [ordered_comm_semiring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_comm_semiring β := { ..hf.comm_semiring f zero one add mul, ..hf.ordered_semiring f zero one add mul } end ordered_comm_semiring /-- A `linear_ordered_semiring α` is a nontrivial semiring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ -- It's not entirely clear we should assume `nontrivial` at this point; -- it would be reasonable to explore changing this, -- but be warned that the instances involving `domain` may cause -- typeclass search loops. @[protect_proj] class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_order α, nontrivial α section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} -- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument -- (see `norm_num.prove_pos_nat`). -- Rather than working out how to relax that assumption, -- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring α` and `nontrivial α`) -- with only a `linear_ordered_semiring` typeclass argument. lemma zero_lt_one' : 0 < (1 : α) := zero_lt_one lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from decidable.mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from decidable.mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin haveI := @linear_order.decidable_le α _, rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonneg_of_nonpos ha.le hb }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonpos_of_nonneg ha.le hb } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≤ a * b) : (0 ≤ a ∧ 0 ≤ b) ∨ (a ≤ 0 ∧ b ≤ 0) := begin haveI := @linear_order.decidable_le α _, refine decidable.or_iff_not_and_not.2 _, simp only [not_and, not_le], intros ab nab, apply not_lt_of_le hab _, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (ab ha.le), ((ab le_rfl).asymm (nab le_rfl)).elim, mul_neg_of_neg_of_pos ha (nab ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.1.not_le ha).2 lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.2.not_le hb).1 @[simp] lemma inv_of_pos [invertible a] : 0 < ⅟a ↔ 0 < a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, pos_of_mul_pos_right this h.le, λ h, pos_of_mul_pos_left this h.le⟩ end @[simp] lemma inv_of_nonpos [invertible a] : ⅟a ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_of_pos] lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h) lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h) @[simp] lemma inv_of_nonneg [invertible a] : 0 ≤ ⅟a ↔ 0 ≤ a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, (pos_of_mul_pos_right this h).le, λ h, (pos_of_mul_pos_left this h).le⟩ end @[simp] lemma inv_of_lt_zero [invertible a] : ⅟a < 0 ↔ a < 0 := by simp only [← not_le, inv_of_nonneg] @[simp] lemma inv_of_le_one [invertible a] (h : 1 ≤ a) : ⅟a ≤ 1 := by haveI := @linear_order.decidable_le α _; exact mul_inv_of_self a ▸ decidable.le_mul_of_one_le_left (inv_of_nonneg.2 $ zero_le_one.trans h) h lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h2 : b ≥ 0, (decidable.mul_nonneg h1 h2).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h2 : a ≥ 0, (decidable.mul_nonneg h2 h1).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_left h' h, λ h', decidable.mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_right h' h, λ h', decidable.mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_left h' h.le, λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_right h' h.le, λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } lemma add_le_mul_of_left_le_right (a2 : 2 ≤ a) (ab : a ≤ b) : a + b ≤ a * b := have 0 < b, from calc 0 < 2 : zero_lt_two ... ≤ a : a2 ... ≤ b : ab, calc a + b ≤ b + b : add_le_add_right ab b ... = 2 * b : (two_mul b).symm ... ≤ a * b : (mul_le_mul_right this).mpr a2 lemma add_le_mul_of_right_le_left (b2 : 2 ≤ b) (ba : b ≤ a) : a + b ≤ a * b := have 0 < a, from calc 0 < 2 : zero_lt_two ... ≤ b : b2 ... ≤ a : ba, calc a + b ≤ a + a : add_le_add_left ba a ... = a * 2 : (mul_two a).symm ... ≤ a * b : (mul_le_mul_left this).mpr b2 lemma add_le_mul (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ a * b := if hab : a ≤ b then add_le_mul_of_left_le_right a2 hab else add_le_mul_of_right_le_left b2 (le_of_not_le hab) lemma add_le_mul' (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ b * a := (le_of_eq (add_comm _ _)).trans (add_le_mul b2 a2) section variables [nontrivial α] @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] end lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb theorem mul_nonneg_iff_right_nonneg_of_pos (ha : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h, nonneg_of_mul_nonneg_right h ha, λ h, decidable.mul_nonneg h ha.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha, absurd h (decidable.mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ hb, absurd h (decidable.mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ /-- Pullback a `linear_ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_semiring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_semiring f zero one add mul } end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c : α} lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_max lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_min lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_max lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_min end linear_ordered_semiring /-- An `ordered_ring α` is a ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α := (zero_le_one : 0 ≤ (1 : α)) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) section ordered_ring variables [ordered_ring α] {a b c : α} -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_nonneg [@decidable_rel α (≤)] {a b : α} (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin by_cases ha : a ≤ 0, { simp [le_antisymm ha h₁] }, by_cases hb : b ≤ 0, { simp [le_antisymm hb h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le ha) (h₂.lt_of_not_le hb))).1, end lemma ordered_ring.mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.ordered_ring.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin rw [← sub_nonneg, ← mul_sub], exact decidable.ordered_ring.mul_nonneg h₂ (sub_nonneg.2 h₁), end lemma ordered_ring.mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin rw [← sub_nonneg, ← sub_mul], exact decidable.ordered_ring.mul_nonneg (sub_nonneg.2 h₁) h₂, end lemma ordered_ring.mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_right lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := begin rw [← sub_pos, ← mul_sub], exact ordered_ring.mul_pos _ _ h₂ (sub_pos.2 h₁), end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := begin rw [← sub_pos, ← sub_mul], exact ordered_ring.mul_pos _ _ (sub_pos.2 h₁) h₂, end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_left [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from decidable.mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_left {a b c : α} : b ≤ a → c ≤ 0 → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonpos_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_right [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from decidable.mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} : b ≤ a → c ≤ 0 → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonpos_right -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_of_nonpos_of_nonpos [@decidable_rel α (≤)] {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} : a ≤ 0 → b ≤ 0 → 0 ≤ a * b := by classical; exact decidable.mul_nonneg_of_nonpos_of_nonpos lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this /-- Pullback an `ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) : ordered_ring β := { mul_pos := λ a b a0 b0, show f 0 < f (a * b), by { rw [zero, mul], apply mul_pos; rwa ← zero }, ..hf.ordered_semiring f zero one add mul, ..hf.ring f zero one add mul neg sub } end ordered_ring section ordered_comm_ring /-- An `ordered_comm_ring α` is a commutative ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_comm_ring (α : Type u) extends ordered_ring α, ordered_comm_semiring α, comm_ring α /-- Pullback an `ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_ring [ordered_comm_ring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) : ordered_comm_ring β := { ..hf.ordered_comm_semiring f zero one add mul, ..hf.ordered_ring f zero one add mul neg sub, ..hf.comm_ring f zero one add mul neg sub } end ordered_comm_ring /-- A `linear_ordered_ring α` is a ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α, nontrivial α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring α] : linear_ordered_add_comm_group α := { .. s } section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, refine decidable.or_iff_not_and_not.2 (λ h, _), revert hab, cases lt_or_gt_of_ne h.1 with ha ha; cases lt_or_gt_of_ne h.2 with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. ‹linear_ordered_ring α› } @[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : abs (2 : α) = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b := begin haveI := @linear_order.decidable_le α _, rw [abs_eq (decidable.mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp only [abs_of_nonpos, abs_of_nonneg, true_or, or_true, eq_self_iff_true, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, neg_neg, *] end /-- `abs` as a `monoid_with_zero_hom`. -/ def abs_hom : monoid_with_zero_hom α α := ⟨abs, abs_zero, abs_one, abs_mul⟩ @[simp] lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) @[simp] lemma abs_mul_self (a : α) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, λ h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by haveI := @linear_order.decidable_le α _; exact ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, λ h, h.elim (and_imp.2 decidable.mul_nonneg) (and_imp.2 decidable.mul_nonneg_of_nonpos_of_nonpos)⟩ /-- Out of three elements of a `linear_ordered_ring`, two must have the same sign. -/ lemma mul_nonneg_of_three (a b c : α) : 0 ≤ a * b ∨ 0 ≤ b * c ∨ 0 ≤ c * a := by iterate 3 { rw mul_nonneg_iff }; have := le_total 0 a; have := le_total 0 b; have := le_total 0 c; itauto lemma mul_nonpos_iff : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : α) : 0 ≤ a * a := abs_mul_self a ▸ abs_nonneg _ @[simp] lemma neg_le_self_iff : -a ≤ a ↔ 0 ≤ a := by simp [neg_le_iff_add_nonneg, ← two_mul, mul_nonneg_iff, zero_le_one, (@zero_lt_two α _ _).not_le] @[simp] lemma neg_lt_self_iff : -a < a ↔ 0 < a := by simp [neg_lt_iff_pos_add, ← two_mul, mul_pos_iff, zero_lt_one, (@zero_lt_two α _ _).not_lt] @[simp] lemma le_neg_self_iff : a ≤ -a ↔ a ≤ 0 := calc a ≤ -a ↔ -(-a) ≤ -a : by rw neg_neg ... ↔ 0 ≤ -a : neg_le_self_iff ... ↔ a ≤ 0 : neg_nonneg @[simp] lemma lt_neg_self_iff : a < -a ↔ a < 0 := calc a < -a ↔ -(-a) < -a : by rw neg_neg ... ↔ 0 < -a : neg_lt_self_iff ... ↔ a < 0 : neg_pos @[simp] lemma abs_eq_self : abs a = a ↔ 0 ≤ a := by simp [abs] @[simp] lemma abs_eq_neg_self : abs a = -a ↔ a ≤ 0 := by simp [abs] /-- For an element `a` of a linear ordered ring, either `abs a = a` and `0 ≤ a`, or `abs a = -a` and `a < 0`. Use cases on this lemma to automate linarith in inequalities -/ lemma abs_cases (a : α) : (abs a = a ∧ 0 ≤ a) ∨ (abs a = -a ∧ a < 0) := begin by_cases 0 ≤ a, { left, exact ⟨abs_eq_self.mpr h, h⟩ }, { right, push_neg at h, exact ⟨abs_eq_neg_self.mpr (le_of_lt h), h⟩ } end lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a := have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:α) := neg_lt_zero.2 zero_lt_one lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) : a ≤ b := by haveI := @linear_order.decidable_le α _; exact have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : decidable.mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_sq_le_sq {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b := by haveI := @linear_order.decidable_le α _; exact le_of_not_gt (λhab, (decidable.mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := by haveI := @linear_order.decidable_le α _; exact ⟨decidable.mul_self_le_mul_self h1, nonneg_le_nonneg_of_sq_le_sq h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := by haveI := @linear_order.decidable_le α _; exact ((@decidable.strict_mono_incr_on_mul_self α _ _).lt_iff_lt h1 h2).symm lemma mul_self_inj {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a * a = b * b ↔ a = b := by haveI := @linear_order.decidable_le α _; exact (@decidable.strict_mono_incr_on_mul_self α _ _).inj_on.eq_iff h1 h2 @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', decidable.mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', decidable.mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin haveI := @linear_order.decidable_le α _, rw [← abs_mul_abs_self x], exact decidable.mul_self_le_mul_self (abs_nonneg x) (abs_le.2 ⟨neg_le.2 h₂, h₁⟩) end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ hb, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) /-- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := by rw [add_eq_zero_iff', mul_self_eq_zero, mul_self_eq_zero]; apply mul_self_nonneg lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := (mul_self_add_mul_self_eq_zero.mp h).left lemma abs_eq_iff_mul_self_eq : abs a = abs b ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : abs a < abs b ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : abs a ≤ abs b ↔ a * a ≤ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_one_iff_mul_self_le_one : abs a ≤ 1 ↔ a * a ≤ 1 := by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le α _ a 1 /-- Pullback a `linear_ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : linear_ordered_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_ring f zero one add mul neg sub } end linear_ordered_ring /-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_ordered_comm_ring [d : linear_ordered_comm_ring α] : ordered_comm_ring α := -- One might hope that `{ ..linear_ordered_ring.to_linear_ordered_semiring, ..d }` -- achieved the same result here. -- Unfortunately with that definition we see mismatched instances in `algebra.star.chsh`. let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring α] : integral_domain α := { ..linear_ordered_ring.to_domain, ..s } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring α] : linear_ordered_semiring α := -- One might hope that `{ ..linear_ordered_ring.to_linear_ordered_semiring, ..d }` -- achieved the same result here. -- Unfortunately with that definition we see mismatched `preorder ℝ` instances in -- `topology.metric_space.basic`. let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] {a b c d : α} lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) : max (a * b) (d * c) ≤ max a c * max d b := by haveI := @linear_order.decidable_le α _; exact have ba : b * a ≤ max d b * max c a, from decidable.mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≤ max a c * max b d, from decidable.mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) lemma abs_sub_sq (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp only [mul_add, add_comm, add_left_comm, mul_comm, sub_eq_add_neg, mul_one, mul_neg_eq_neg_mul_symm, neg_add_rev, neg_neg], end @[simp] lemma abs_dvd (a b : α) : abs a ∣ b ↔ a ∣ b := by { cases abs_choice a with h h; simp only [h, neg_dvd] } lemma abs_dvd_self (a : α) : abs a ∣ a := (abs_dvd a a).mpr (dvd_refl a) @[simp] lemma dvd_abs (a b : α) : a ∣ abs b ↔ a ∣ b := by { cases abs_choice b with h h; simp only [h, dvd_neg] } lemma self_dvd_abs (a : α) : a ∣ abs a := (dvd_abs a a).mpr (dvd_refl a) lemma abs_dvd_abs (a b : α) : abs a ∣ abs b ↔ a ∣ b := (abs_dvd _ _).trans (dvd_abs _ _) lemma even_abs {a : α} : even (abs a) ↔ even a := dvd_abs _ _ /-- Pullback a `linear_ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_comm_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : linear_ordered_comm_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_comm_ring f zero one add mul neg sub } end linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, nonneg_add_comm_group α := (one_nonneg : nonneg 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α := (one_pos : pos 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) [dec_nonneg : decidable_pred nonneg] namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring α] /-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`, hence a `linear_nonneg_ring`. -/ def to_linear_nonneg_ring [nontrivial α] [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { one_pos := (pos_iff 1).mpr ⟨one_nonneg, λ h, zero_ne_one (nonneg_antisymm one_nonneg h).symm⟩, nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, decidable.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, decidable.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..‹nontrivial α›, ..‹nonneg_ring α› } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring α] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring α := { one_nonneg := ((pos_iff _).mp one_pos).1, mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..‹linear_nonneg_ring α› } /-- Construct `linear_order` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_order [decidable_pred (nonneg : α → Prop)] : linear_order α := { le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α) } /-- Construct `linear_ordered_ring` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_ordered_ring [decidable_pred (nonneg : α → Prop)] : linear_ordered_ring α := { mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_le_one := le_of_lt $ lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α), ..(infer_instance : linear_order α) } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `linear_ordered_comm_ring` -/ def to_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : linear_ordered_comm_ring α := { mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ _ } end linear_nonneg_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) namespace canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring α] {a b : α} @[priority 100] -- see Note [lower instance priority] instance to_no_zero_divisors : no_zero_divisors α := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance to_covariant_mul_le : covariant_class α α (*) (≤) := begin refine ⟨λ a b c h, _⟩, rcases le_iff_exists_add.1 h with ⟨c, rfl⟩, rw mul_add, apply self_le_add_right end /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one [nontrivial α] : (0:α) < 1 := (zero_le 1).lt_of_ne zero_ne_one lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] end canonically_ordered_comm_semiring /-! ### Structures involving `*` and `0` on `with_top` and `with_bot` The main results of this section are `with_top.canonically_ordered_comm_semiring` and `with_bot.comm_monoid_with_zero`. -/ namespace with_top instance [nonempty α] : nontrivial (with_top α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊤ * (b : with_top α) = ⊤ ↔ b ≠ 0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top α) * ⊤ = ⊤ ↔ a ≠ 0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end lemma mul_lt_top [partial_order α] {a b : with_top α} (ha : a < ⊤) (hb : b < ⊤) : a * b < ⊤ := begin lift a to α using ne_top_of_lt ha, lift b to α using ne_top_of_lt hb, simp only [← coe_mul, coe_lt_top] end end mul_zero_class /-- `nontrivial α` is needed here as otherwise we have `1 * ⊤ = ⊤` but also `= 0 * ⊤ = 0`. -/ instance [mul_zero_one_class α] [nontrivial α] : mul_zero_one_class (with_top α) := { mul := (*), one := 1, zero := 0, one_mul := λ a, match a with | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_top.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_top.coe_one] end, mul_one := λ a, match a with | none := show ⊤ * ((1:α) : with_top α) = ⊤, by simp [-with_top.coe_one] | (some a) := show ↑a * ((1:α) : with_top α) = a, by simp [coe_mul.symm, -with_top.coe_one] end, .. with_top.mul_zero_class } instance [mul_zero_class α] [no_zero_divisors α] : no_zero_divisors (with_top α) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ instance [semigroup_with_zero α] [no_zero_divisors α] : semigroup_with_zero (with_top α) := { mul := (*), zero := 0, mul_assoc := λ a b c, begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end, .. with_top.mul_zero_class } instance [monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : monoid_with_zero (with_top α) := { .. with_top.mul_zero_one_class, .. with_top.semigroup_with_zero } instance [comm_monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : comm_monoid_with_zero (with_top α) := { mul := (*), zero := 0, mul_comm := λ a b, begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end, .. with_top.monoid_with_zero } variables [canonically_ordered_comm_semiring α] private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end /-- This instance requires `canonically_ordered_comm_semiring` as it is the smallest class that derives from both `non_assoc_non_unital_semiring` and `canonically_ordered_add_monoid`, both of which are required for distributivity. -/ instance [nontrivial α] : comm_semiring (with_top α) := { right_distrib := distrib', left_distrib := assume a b c, by rw [mul_comm, distrib', mul_comm b, mul_comm c]; refl, .. with_top.add_comm_monoid, .. with_top.comm_monoid_with_zero,} instance [nontrivial α] : canonically_ordered_comm_semiring (with_top α) := { .. with_top.comm_semiring, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, } end with_top namespace with_bot instance [nonempty α] : nontrivial (with_bot α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_bot α) := with_top.mul_zero_class lemma mul_def {a b : with_bot α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_bot {a : with_bot α} (h : a ≠ 0) : a * ⊥ = ⊥ := with_top.mul_top h @[simp] lemma bot_mul {a : with_bot α} (h : a ≠ 0) : ⊥ * a = ⊥ := with_top.top_mul h @[simp] lemma bot_mul_bot : (⊥ * ⊥ : with_bot α) = ⊥ := with_top.top_mul_top end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_bot α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) {a : with_bot α} : a * b = a.bind (λa:α, ↑(a * b)) := with_top.mul_coe hb @[simp] lemma mul_eq_bot_iff {a b : with_bot α} : a * b = ⊥ ↔ (a ≠ 0 ∧ b = ⊥) ∨ (a = ⊥ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma bot_lt_mul [partial_order α] {a b : with_bot α} (ha : ⊥ < a) (hb : ⊥ < b) : ⊥ < a * b := begin lift a to α using ne_bot_of_gt ha, lift b to α using ne_bot_of_gt hb, simp only [← coe_mul, bot_lt_coe], end end mul_zero_class /-- `nontrivial α` is needed here as otherwise we have `1 * ⊥ = ⊥` but also `= 0 * ⊥ = 0`. -/ instance [mul_zero_one_class α] [nontrivial α] : mul_zero_one_class (with_bot α) := with_top.mul_zero_one_class instance [mul_zero_class α] [no_zero_divisors α] : no_zero_divisors (with_bot α) := with_top.no_zero_divisors instance [semigroup_with_zero α] [no_zero_divisors α] : semigroup_with_zero (with_bot α) := with_top.semigroup_with_zero instance [monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : monoid_with_zero (with_bot α) := with_top.monoid_with_zero instance [comm_monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : comm_monoid_with_zero (with_bot α) := with_top.comm_monoid_with_zero instance [canonically_ordered_comm_semiring α] [nontrivial α] : comm_semiring (with_bot α) := with_top.comm_semiring end with_bot
606fb8687b71cbfeb760b567668448a8acd0bc88
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Control/Applicative.lean
2de9cd3cdff8df095e8579427a01c224962bf026
[ "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
1,366
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, Sebastian Ullrich -/ prelude import Init.Control.Functor open Function universes u v class HasPure (f : Type u → Type v) := (pure {} {α : Type u} : α → f α) export HasPure (pure) class HasSeq (f : Type u → Type v) : Type (max (u+1) v) := (seq : ∀ {α β : Type u}, f (α → β) → f α → f β) infixl <*> := HasSeq.seq class HasSeqLeft (f : Type u → Type v) : Type (max (u+1) v) := (seqLeft : ∀ {α β : Type u}, f α → f β → f α) infixl <* := HasSeqLeft.seqLeft class HasSeqRight (f : Type u → Type v) : Type (max (u+1) v) := (seqRight : ∀ {α β : Type u}, f α → f β → f β) infixr *> := HasSeqRight.seqRight class Applicative (f : Type u → Type v) extends Functor f, HasPure f, HasSeq f, HasSeqLeft f, HasSeqRight f := (map := fun _ _ x y => pure x <*> y) (seqLeft := fun α β a b => const β <$> a <*> b) (seqRight := fun α β a b => const α id <$> a <*> b) @[macroInline] def when {m : Type → Type u} [Applicative m] (c : Prop) [h : Decidable c] (t : m Unit) : m Unit := if c then t else pure () @[macroInline] def unless {m : Type → Type u} [Applicative m] (c : Prop) [h : Decidable c] (e : m Unit) : m Unit := if c then pure () else e
0edf1cffa9f13e2970387ef622e3faa72efce9ef
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/zify_auto.lean
698bbc46ce8ad5c80eea526b0342df983717859e
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,060
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.norm_cast import Mathlib.data.int.cast import Mathlib.PostPort namespace Mathlib /-! # A tactic to shift `ℕ` goals to `ℤ` It is often easier to work in `ℤ`, where subtraction is well behaved, than in `ℕ` where it isn't. `zify` is a tactic that casts goals and hypotheses about natural numbers to ones about integers. It makes use of `push_cast`, part of the `norm_cast` family, to simplify these goals. ## Implementation notes `zify` is extensible, using the attribute `@[zify]` to label lemmas used for moving propositions from `ℕ` to `ℤ`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. `zify` is very nearly just `simp only with zify push_cast`. There are a few minor differences: * `zify` lemmas are used in the opposite order of the standard simp form. E.g. we will rewrite with `int.coe_nat_le_coe_nat_iff` from right to left. * `zify` should fail if no `zify` lemma applies (i.e. it was unable to shift any proposition to ℤ). However, once this succeeds, it does not necessarily need to rewrite with any `push_cast` rules. -/ namespace zify /-- The `zify` attribute is used by the `zify` tactic. It applies to lemmas that shift propositions between `nat` and `int`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. -/ /-- Given an expression `e`, `lift_to_z e` looks for subterms of `e` that are propositions "about" natural numbers and change them to propositions about integers. Returns an expression `e'` and a proof that `e = e'`. Includes `ge_iff_le` and `gt_iff_lt` in the simp set. These can't be tagged with `zify` as we want to use them in the "forward", not "backward", direction. -/ end zify theorem int.coe_nat_ne_coe_nat_iff (a : ℕ) (b : ℕ) : ↑a ≠ ↑b ↔ a ≠ b := sorry /-- `zify extra_lems e` is used to shift propositions in `e` from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. The list of extra lemmas is used in the `push_cast` step. Returns an expression `e'` and a proof that `e = e'`.-/ /-- A variant of `tactic.zify` that takes `h`, a proof of a proposition about natural numbers, and returns a proof of the zified version of that propositon. -/ /-- The `zify` tactic is used to shift propositions from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. ```lean example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : c < a + 3*b := begin zify, zify at h, /- h : ¬↑x * ↑y * ↑z < 0 ⊢ ↑c < ↑a + 3 * ↑b -/ end Mathlib
2b53d8f100f7bd879fc5b083d9c0cf5ea42fb99c
fe25de614feb5587799621c41487aaee0d083b08
/src/Init/Data/Array/Basic.lean
d1f5f73a3d97036d5980b8ced6e1601598903e5f
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,617
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString.Basic import Init.Util universe u v w namespace Array variable {α : Type u} @[extern "lean_mk_array"] def mkArray {α : Type u} (n : Nat) (v : α) : Array α := { data := List.replicate n v } @[simp] theorem size_mkArray (n : Nat) (v : α) : (mkArray n v).size = n := List.length_replicate .. instance : EmptyCollection (Array α) := ⟨Array.empty⟩ instance : Inhabited (Array α) where default := Array.empty def isEmpty (a : Array α) : Bool := a.size = 0 def singleton (v : α) : Array α := mkArray 1 v /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α := a.get ⟨i.toNat, h⟩ def back [Inhabited α] (a : Array α) : α := a.get! (a.size - 1) def get? (a : Array α) (i : Nat) : Option α := if h : i < a.size then some (a.get ⟨i, h⟩) else none def back? (a : Array α) : Option α := a.get? (a.size - 1) -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁.symm ▸ h₂⟩ @[simp] theorem size_set (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size := List.length_set .. @[simp] theorem size_push (a : Array α) (v : α) : (push a v).size = a.size + 1 := List.length_concat .. /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α := a.set ⟨i.toNat, h⟩ v @[extern "lean_array_fswap"] def swap (a : Array α) (i j : @& Fin a.size) : Array α := let v₁ := a.get i let v₂ := a.get j let a' := a.set i v₂ a'.set (size_set a i v₂ ▸ j) v₁ @[extern "lean_array_swap"] def swap! (a : Array α) (i j : @& Nat) : Array α := if h₁ : i < a.size then if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩ else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt (a : Array α) (i : Fin a.size) (v : α) : α × Array α := let e := a.get i let a := a.set i v (e, a) @[inline] def swapAt! (a : Array α) (i : Nat) (v : α) : α × Array α := if h : i < a.size then swapAt a ⟨i, h⟩ v else have : Inhabited α := ⟨v⟩ panic! ("index " ++ toString i ++ " out of bounds") @[extern "lean_array_pop"] def pop (a : Array α) : Array α := { data := a.data.dropLast } def shrink (a : Array α) (n : Nat) : Array α := let rec loop | 0, a => a | n+1, a => loop n a.pop loop (a.size - n) a @[inline] def modifyM [Monad m] [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) := do if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩ let v := a.get idx let a' := a.set idx arbitrary let v ← f v pure <| a'.set (size_set a .. ▸ idx) v else pure a @[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α := Id.run <| a.modifyM i f @[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α := self.modify idx f /- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/ @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b -- Move? private theorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b | 0, _, h => h | a+1, b, h => have : a < b := Nat.ltTrans (Nat.ltSuccSelf _) h zeroLtOfLt this /- Reference implementation for `forIn` -/ @[implementedBy Array.forInUnsafe] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h have : as.size - 1 < as.size := Nat.subLt (zeroLtOfLt h') (by decide) have : as.size - 1 - i < as.size := Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.leOfLt h') b loop as.size (Nat.leRefl _) b instance : ForIn m (Array α) α where forIn := Array.forIn /- See comment at forInUnsafe -/ @[inline] unsafe def foldlMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /- Reference implementation for `foldlM` -/ @[implementedBy foldlMUnsafe] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.leRefl _) /- See comment at forInUnsafe -/ @[inline] unsafe def foldrMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i-1) stop (← f (as.uget (i-1) lcProof) b) if start ≤ as.size then if stop < start then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else if stop < as.size then fold (USize.ofNat as.size) (USize.ofNat stop) init else pure init /- Reference implementation for `foldrM` -/ @[implementedBy foldrMUnsafe] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec fold (i : Nat) (h : i ≤ as.size) (b : β) : m β := do if i == stop then pure b else match i, h with | 0, _ => pure b | i+1, h => have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h fold i (Nat.leOfLt this) (← f (as.get ⟨i, this⟩) b) if h : start ≤ as.size then if stop < start then fold start h init else pure init else if stop < as.size then fold as.size (Nat.leRefl _) init else pure init /- See comment at forInUnsafe -/ @[inline] unsafe def mapMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := let sz := USize.ofNat as.size let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do if i < sz then let v := r.uget i lcProof let r := r.uset i arbitrary lcProof let vNew ← f (unsafeCast v) map (i+1) (r.uset i (unsafeCast vNew) lcProof) else pure (unsafeCast r) unsafeCast <| map 0 (unsafeCast as) /- Reference implementation for `mapM` -/ @[implementedBy mapMUnsafe] def mapM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := as.foldlM (fun bs a => do let b ← f a; pure (bs.push b)) (mkEmpty as.size) @[inline] def mapIdxM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : Fin as.size → α → m β) : m (Array β) := let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array β) : m (Array β) := do match i, inv with | 0, _ => pure bs | i+1, inv => have : j < as.size := by rw [← inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_left_comm]; apply Nat.leAddRight let idx : Fin as.size := ⟨j, this⟩ have : i + (j + 1) = as.size := by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] map i (j+1) this (bs.push (← f idx (as.get idx))) map as.size 0 rfl (mkEmpty as.size) @[inline] def findSomeM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := do for a in as do match (← f a) with | some b => return b | _ => pure ⟨⟩ return none @[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := do for a in as do if (← p a) then return a return none @[inline] def findIdxM? [Monad m] (as : Array α) (p : α → m Bool) : m (Option Nat) := do let mut i := 0 for a in as do if (← p a) then return some i i := i + 1 return none @[inline] unsafe def anyMUnsafe {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do if i == stop then pure false else if (← p (as.uget i lcProof)) then pure true else any (i+1) stop if start < stop then if stop ≤ as.size then any (USize.ofNat start) (USize.ofNat stop) else pure false else pure false @[implementedBy anyMUnsafe] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let any (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) : m Bool := do if hlt : j < stop then match i with | 0 => pure false | i'+1 => if (← p (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) then pure true else loop i' (j+1) else pure false loop (stop - start) start if h : stop ≤ as.size then any stop h else any as.size (Nat.leRefl _) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := return !(← as.anyM fun v => return !(← p v)) @[inline] def findSomeRevM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := let rec @[specialize] find : (i : Nat) → i ≤ as.size → m (Option β) | 0, h => pure none | i+1, h => do have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h let r ← f (as.get ⟨i, this⟩) match r with | some v => pure r | none => have : i ≤ as.size := Nat.leOfLt this find i this find as.size (Nat.leRefl _) @[inline] def findRevM? {α : Type} {m : Type → Type w} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := as.findSomeRevM? fun a => return if (← p a) then some a else none @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := 0) (stop := as.size) : m PUnit := as.foldlM (fun _ => f) ⟨⟩ start stop @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := as.size) (stop := 0) : m PUnit := as.foldrM (fun a _ => f a) ⟨⟩ start stop @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Array α) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Array α) (start := as.size) (stop := 0) : β := Id.run <| as.foldrM f init start stop @[inline] def map {α : Type u} {β : Type v} (f : α → β) (as : Array α) : Array β := Id.run <| as.mapM f @[inline] def mapIdx {α : Type u} {β : Type v} (as : Array α) (f : Fin as.size → α → β) : Array β := Id.run <| as.mapIdxM f @[inline] def find? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findM? p @[inline] def findSome? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeM? f @[inline] def findSome! {α : Type u} {β : Type v} [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeRevM? f @[inline] def findRev? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findRevM? p @[inline] def findIdx? {α : Type u} (as : Array α) (p : α → Bool) : Option Nat := let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat := if hlt : j < as.size then match i, inv with | 0, inv => by apply False.elim rw [Nat.zero_add] at inv rw [inv] at hlt exact absurd hlt (Nat.ltIrrefl _) | i+1, inv => if p (as.get ⟨j, hlt⟩) then some j else have : i + (j+1) = as.size := by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] loop i (j+1) this else none loop as.size 0 rfl def getIdx? [BEq α] (a : Array α) (v : α) : Option Nat := a.findIdx? fun a => a == v @[inline] def any (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.anyM p start stop @[inline] def all (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.allM p start stop def contains [BEq α] (as : Array α) (a : α) : Bool := as.any fun b => a == b def elem [BEq α] (a : α) (as : Array α) : Bool := as.contains a -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverse (as : Array α) : Array α := let n := as.size let mid := n / 2 let rec rev (as : Array α) (i : Nat) := if i < mid then rev (as.swap! i (n - i - 1)) (i+1) else as rev as 0 @[inline] def getEvenElems (as : Array α) : Array α := (·.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a => if even then (false, r.push a) else (true, r) @[export lean_array_to_list] def toList (as : Array α) : List α := as.foldr List.cons [] instance {α : Type u} [Repr α] : Repr (Array α) where reprPrec a n := let _ : Std.ToFormat α := ⟨repr⟩ if a.size == 0 then "#[]" else Std.Format.bracketFill "#[" (Std.Format.joinSep (toList a) ("," ++ Std.Format.line)) "]" instance [ToString α] : ToString (Array α) where toString a := "#" ++ toString a.toList protected def append (as : Array α) (bs : Array α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : Append (Array α) := ⟨Array.append⟩ protected def appendList (as : Array α) (bs : List α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : HAppend (Array α) (List α) (Array α) := ⟨Array.appendList⟩ @[inline] def concatMapM [Monad m] (f : α → m (Array β)) (as : Array α) : m (Array β) := as.foldlM (init := empty) fun bs a => do return bs ++ (← f a) @[inline] def concatMap (f : α → Array β) (as : Array α) : Array β := as.foldl (init := empty) fun bs a => bs ++ f a end Array export Array (mkArray) syntax "#[" sepBy(term, ", ") "]" : term macro_rules | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ]) namespace Array -- TODO(Leo): cleanup @[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) (i : Nat) : Bool := if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz ▸ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux a b hsz p (i+1) | false => false else true @[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [BEq α] : BEq (Array α) := ⟨fun a b => isEqv a b BEq.beq⟩ @[inline] def filter (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Array α := as.foldl (init := #[]) (start := start) (stop := stop) fun r a => if p a then r.push a else r @[inline] def filterM [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m (Array α) := as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do if (← p a) then r.push a else r @[specialize] def filterMapM [Monad m] (f : α → m (Option β)) (as : Array α) (start := 0) (stop := as.size) : m (Array β) := as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do match (← f a) with | some b => pure (bs.push b) | none => pure bs @[inline] def filterMap (f : α → Option β) (as : Array α) (start := 0) (stop := as.size) : Array β := Id.run <| as.filterMapM f (start := start) (stop := stop) @[specialize] def getMax? (as : Array α) (lt : α → α → Bool) : Option α := if h : 0 < as.size then let a0 := as.get ⟨0, h⟩ some <| as.foldl (init := a0) (start := 1) fun best a => if lt best a then a else best else none @[inline] def partition (p : α → Bool) (as : Array α) : Array α × Array α := do let mut bs := #[] let mut cs := #[] for a in as do if p a then bs := bs.push a else cs := cs.push a return (bs, cs) theorem ext (a b : Array α) (h₁ : a.size = b.size) (h₂ : (i : Nat) → (hi₁ : i < a.size) → (hi₂ : i < b.size) → a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) : a = b := by let rec extAux (a b : List α) (h₁ : a.length = b.length) (h₂ : (i : Nat) → (hi₁ : i < a.length) → (hi₂ : i < b.length) → a.get i hi₁ = b.get i hi₂) : a = b := by induction a generalizing b with | nil => cases b with | nil => rfl | cons b bs => rw [List.length_cons] at h₁; injection h₁ | cons a as ih => cases b with | nil => rw [List.length_cons] at h₁; injection h₁ | cons b bs => have hz₁ : 0 < (a::as).length := by rw [List.length_cons]; apply Nat.zeroLtSucc have hz₂ : 0 < (b::bs).length := by rw [List.length_cons]; apply Nat.zeroLtSucc have headEq : a = b := h₂ 0 hz₁ hz₂ have h₁' : as.length = bs.length := by rw [List.length_cons, List.length_cons] at h₁; injection h₁; assumption have h₂' : (i : Nat) → (hi₁ : i < as.length) → (hi₂ : i < bs.length) → as.get i hi₁ = bs.get i hi₂ := by intro i hi₁ hi₂ have hi₁' : i+1 < (a::as).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have hi₂' : i+1 < (b::bs).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have : (a::as).get (i+1) hi₁' = (b::bs).get (i+1) hi₂' := h₂ (i+1) hi₁' hi₂' apply this have tailEq : as = bs := ih bs h₁' h₂' rw [headEq, tailEq] cases a; cases b apply congrArg apply extAux assumption assumption theorem extLit {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : (i : Nat) → (hi : i < n) → a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) end Array -- CLEANUP the following code namespace Array partial def indexOfAux [BEq α] (a : Array α) (v : α) : Nat → Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux a v (i+1) else none def indexOf? [BEq α] (a : Array α) (v : α) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux : Nat → Array α → Array α | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx (a : Array α) (i : Fin a.size) : Array α := eraseIdxAux (i.val + 1) a def eraseIdx (a : Array α) (i : Nat) : Array α := if i < a.size then eraseIdxAux (i+1) a else a @[simp] theorem size_swap (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size := by show ((a.set i (a.get j)).set (size_set a i _ ▸ j) (a.get i)).size = a.size rw [size_set, size_set] @[simp] theorem size_pop (a : Array α) : a.pop.size = a.size - 1 := List.length_dropLast .. section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } where default := ⟨a.pop, size_pop a⟩ partial def eraseIdxSzAux (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq) else ⟨r.pop, (size_pop r).trans (heq ▸ rfl)⟩ end def eraseIdx' (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def erase [BEq α] (as : Array α) (a : α) : Array α := match as.indexOf? a with | none => as | some i => as.feraseIdx i partial def insertAtAux (i : Nat) : Array α → Nat → Array α | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux i as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt (as : Array α) (i : Nat) (a : α) : Array α := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size def toListLitAux (a : Array α) (n : Nat) (hsz : a.size = n) : ∀ (i : Nat), i ≤ a.size → List α → List α | 0, hi, acc => acc | (i+1), hi, acc => toListLitAux a n hsz i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc) def toArrayLit (a : Array α) (n : Nat) (hsz : a.size = n) : Array α := List.toArray <| toListLitAux a n hsz n (hsz ▸ Nat.leRefl _) [] theorem toArrayLitEq (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := -- TODO: this is painful to prove without proper automation sorry /- First, we need to prove ∀ i j acc, i ≤ a.size → (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i) by induction Base case is trivial (j : Nat) (acc : List α) (hi : 0 ≤ a.size) |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0) ... |- acc.index j = acc.index j Induction (j : Nat) (acc : List α) (hi : i+1 ≤ a.size) |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def ... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) If j < i, then both are a.getLit j hsz _ If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _) If j >= i + 1, we use - j - i >= 1 > 0 - (a::as).index k = as.index (k-1) If k > 0 - j - (i + 1) = (j - i) - 1 Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs With this proof, we have ∀ j, j < n → (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _ We also need - (toListLitAux a n hsz n _ []).length = n - j < n -> (List.toArray as).getLit j _ _ = as.index j Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ [] -/ partial def isPrefixOfAux [BEq α] (as bs : Array α) (hle : as.size ≤ bs.size) : Nat → Bool | i => if h : i < as.size then let a := as.get ⟨i, h⟩; let b := bs.get ⟨i, Nat.ltOfLtOfLe h hle⟩; if a == b then isPrefixOfAux as bs hle (i+1) else false else true /- Return true iff `as` is a prefix of `bs` -/ def isPrefixOf [BEq α] (as bs : Array α) : Bool := if h : as.size ≤ bs.size then isPrefixOfAux as bs h 0 else false private def allDiffAuxAux [BEq α] (as : Array α) (a : α) : forall (i : Nat), i < as.size → Bool | 0, h => true | i+1, h => have : i < as.size := Nat.ltTrans (Nat.ltSuccSelf _) h; a != as.get ⟨i, this⟩ && allDiffAuxAux as a i this private partial def allDiffAux [BEq α] (as : Array α) : Nat → Bool | i => if h : i < as.size then allDiffAuxAux as (as.get ⟨i, h⟩) i h && allDiffAux as (i+1) else true def allDiff [BEq α] (as : Array α) : Bool := allDiffAux as 0 @[specialize] partial def zipWithAux (f : α → β → γ) (as : Array α) (bs : Array β) : Nat → Array γ → Array γ | i, cs => if h : i < as.size then let a := as.get ⟨i, h⟩; if h : i < bs.size then let b := bs.get ⟨i, h⟩; zipWithAux f as bs (i+1) <| cs.push <| f a b else cs else cs @[inline] def zipWith (as : Array α) (bs : Array β) (f : α → β → γ) : Array γ := zipWithAux f as bs 0 #[] def zip (as : Array α) (bs : Array β) : Array (α × β) := zipWith as bs Prod.mk def unzip (as : Array (α × β)) : Array α × Array β := as.foldl (init := (#[], #[])) fun (as, bs) (a, b) => (as.push a, bs.push b) def split (as : Array α) (p : α → Bool) : Array α × Array α := as.foldl (init := (#[], #[])) fun (as, bs) a => if p a then (as.push a, bs) else (as, bs.push a) end Array
637e060a4cdd2be7889a4fcd8053745cc1404bbe
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/smul_with_zero.lean
6e7dc416dd4993bf4eeb793ae0ff16ea6770fbbc
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
5,251
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import group_theory.group_action.defs import algebra.group_power.basic /-! # Introduce `smul_with_zero` In analogy with the usual monoid action on a Type `M`, we introduce an action of a `monoid_with_zero` on a Type with `0`. In particular, for Types `R` and `M`, both containing `0`, we define `smul_with_zero R M` to be the typeclass where the products `r • 0` and `0 • m` vanish for all `r : R` and all `m : M`. Moreover, in the case in which `R` is a `monoid_with_zero`, we introduce the typeclass `mul_action_with_zero R M`, mimicking group actions and having an absorbing `0` in `R`. Thus, the action is required to be compatible with * the unit of the monoid, acting as the identity; * the zero of the monoid_with_zero, acting as zero; * associativity of the monoid. We also add an `instance`: * any `monoid_with_zero` has a `mul_action_with_zero R R` acting on itself. -/ variables {R R' M M' : Type*} section has_zero variables (R M) /-- `smul_with_zero` is a class consisting of a Type `R` with `0 ∈ R` and a scalar multiplication of `R` on a Type `M` with `0`, such that the equality `r • m = 0` holds if at least one among `r` or `m` equals `0`. -/ class smul_with_zero [has_zero R] [has_zero M] extends has_scalar R M := (smul_zero : ∀ r : R, r • (0 : M) = 0) (zero_smul : ∀ m : M, (0 : R) • m = 0) instance mul_zero_class.to_smul_with_zero [mul_zero_class R] : smul_with_zero R R := { smul := (*), smul_zero := mul_zero, zero_smul := zero_mul } instance add_monoid.to_smul_with_zero [add_monoid M] : smul_with_zero ℕ M := { smul_zero := nsmul_zero, zero_smul := zero_nsmul } variables (R) {M} [has_zero R] [has_zero M] [smul_with_zero R M] @[simp] lemma zero_smul (m : M) : (0 : R) • m = 0 := smul_with_zero.zero_smul m variables {R} (M) /-- Note that this lemma has different typeclass assumptions to `smul_zero`. -/ @[simp] lemma smul_zero' (r : R) : r • (0 : M) = 0 := smul_with_zero.smul_zero r variables {R M} [has_zero R'] [has_zero M'] [has_scalar R M'] /-- Pullback a `smul_with_zero` structure along an injective zero-preserving homomorphism. -/ protected def function.injective.smul_with_zero (f : zero_hom M' M) (hf : function.injective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : smul_with_zero R M' := { smul := (•), zero_smul := λ a, hf $ by simp [smul], smul_zero := λ a, hf $ by simp [smul]} /-- Pushforward a `smul_with_zero` structure along a surjective zero-preserving homomorphism. -/ protected def function.surjective.smul_with_zero (f : zero_hom M M') (hf : function.surjective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : smul_with_zero R M' := { smul := (•), zero_smul := λ m, by { rcases hf m with ⟨x, rfl⟩, simp [←smul] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero'] } variables (M) /-- Compose a `smul_with_zero` with a `zero_hom`, with action `f r' • m` -/ def smul_with_zero.comp_hom (f : zero_hom R' R) : smul_with_zero R' M := { smul := (•) ∘ f, smul_zero := λ m, by simp, zero_smul := λ m, by simp } end has_zero section monoid_with_zero variables [monoid_with_zero R] [monoid_with_zero R'] [has_zero M] variables (R M) /-- An action of a monoid with zero `R` on a Type `M`, also with `0`, extends `mul_action` and is compatible with `0` (both in `R` and in `M`), with `1 ∈ R`, and with associativity of multiplication on the monoid `M`. -/ class mul_action_with_zero extends mul_action R M := -- these fields are copied from `smul_with_zero`, as `extends` behaves poorly (smul_zero : ∀ r : R, r • (0 : M) = 0) (zero_smul : ∀ m : M, (0 : R) • m = 0) @[priority 100] -- see Note [lower instance priority] instance mul_action_with_zero.to_smul_with_zero [m : mul_action_with_zero R M] : smul_with_zero R M := {..m} instance monoid_with_zero.to_mul_action_with_zero : mul_action_with_zero R R := { ..mul_zero_class.to_smul_with_zero R, ..monoid.to_mul_action R } variables {R M} [mul_action_with_zero R M] [has_zero M'] [has_scalar R M'] /-- Pullback a `mul_action_with_zero` structure along an injective zero-preserving homomorphism. -/ protected def function.injective.mul_action_with_zero (f : zero_hom M' M) (hf : function.injective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : mul_action_with_zero R M' := { ..hf.mul_action f smul, ..hf.smul_with_zero f smul } /-- Pushforward a `mul_action_with_zero` structure along a surjective zero-preserving homomorphism. -/ protected def function.surjective.mul_action_with_zero (f : zero_hom M M') (hf : function.surjective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : mul_action_with_zero R M' := { ..hf.mul_action f smul, ..hf.smul_with_zero f smul } variables (M) /-- Compose a `mul_action_with_zero` with a `monoid_with_zero_hom`, with action `f r' • m` -/ def mul_action_with_zero.comp_hom (f : monoid_with_zero_hom R' R) : mul_action_with_zero R' M := { smul := (•) ∘ f, mul_smul := λ r s m, by simp [mul_smul], one_smul := λ m, by simp, .. smul_with_zero.comp_hom M f.to_zero_hom} end monoid_with_zero
dd246ed8b460d46eee667217f455c28934a9aead
87fd6b43d22688237c02b87c30d2a524f53bab24
/src/game/sets/sqrtOfTwo.lean
5a65e871c9572b49759280cd6b01c3a521b95ead
[ "Apache-2.0" ]
permissive
grthomson/real-number-game
66142fedf0987db90f66daed52f9c8b42b70f909
8ddc15fdddc241c246653f7bb341df36e4e880a8
refs/heads/master
1,668,059,330,605
1,592,873,454,000
1,592,873,454,000
262,025,764
0
0
null
1,588,849,107,000
1,588,849,106,000
null
UTF-8
Lean
false
false
3,895
lean
import data.nat.prime open nat theorem sqrt_two_irrational_V1 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 := assume h : a^2 = 2 * b^2, have 2 ∣ a^2, by simp [h], have ha : 2 ∣ a, from prime.dvd_of_dvd_pow prime_two this, -- usually after exists.elim the rest of the proof should be inside -- parantheses exists.elim ha (assume c : ℕ, assume aeq : a = 2 * c, have 2 * (2 * c^2) = 2 * b^2, by simp [eq.symm h, aeq]; simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm], have 2 * c^2 = b^2, from eq_of_mul_eq_mul_left dec_trivial this, have 2 ∣ b^2, by simp [eq.symm this], have hb : 2 ∣ b, from prime.dvd_of_dvd_pow prime_two this, have 2 ∣ gcd a b, from dvd_gcd ha hb, have habs : 2 ∣ (1:ℕ), by simp * at *, -- therefore the ) below!!!! show false, from absurd habs dec_trivial ) #check sqrt_two_irrational_V1 -- tactics mode theorem sqrt_two_irrational_V2 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 := begin intro h, have h1 : 2 ∣ a^2, by simp [h], have h2 : 2 ∣ a, from prime.dvd_of_dvd_pow prime_two h1, cases h2 with c aeq, have h3 : 2 * (2 * c^2) = 2 * b^2, by simp [eq.symm h, aeq]; simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm], have h4 : 2 * c^2 = b^2, from eq_of_mul_eq_mul_left dec_trivial h3, have h5 : 2 ∣ b^2, by simp [eq.symm h4], have hb : 2 ∣ b, from prime.dvd_of_dvd_pow prime_two h5, have h6 : 2 ∣ gcd a b, from dvd_gcd (exists.intro c aeq) hb, have habs : 2 ∣ (1:ℕ), by simp * at *, exact absurd habs dec_trivial, done end -- using let (it may introduce a bug due to _let_match hypothesis) theorem sqrt_two_irrational_V3 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 := assume h : a^2 = 2 * b^2, have 2 ∣ a^2, by simp [h], have ha : 2 ∣ a, from prime.dvd_of_dvd_pow prime_two this, let ⟨c, aeq⟩ := ha in have 2 * (2 * c^2) = 2 * b^2, by simp [eq.symm h, aeq]; simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm], have 2 * c^2 = b^2, from eq_of_mul_eq_mul_left dec_trivial this, have 2 ∣ b^2, by simp [eq.symm this], have hb : 2 ∣ b, from prime.dvd_of_dvd_pow prime_two this, have 2 ∣ gcd a b, from dvd_gcd ha hb, have habs : 2 ∣ (1:ℕ), by clear_aux_decl; simp * at *, -- replaces simp * at *, show false, from absurd habs dec_trivial -- variant with match, needs end to finish theorem sqrt_two_irrational_V4 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 := assume h : a^2 = 2 * b^2, have 2 ∣ a^2, by simp [h], have ha : 2 ∣ a, from prime.dvd_of_dvd_pow prime_two this, match ha with | ⟨c, aeq⟩ := have 2 * (2 * c^2) = 2 * b^2, by simp [eq.symm h, aeq]; simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm], have 2 * c^2 = b^2, from eq_of_mul_eq_mul_left dec_trivial this, have 2 ∣ b^2, by simp [eq.symm this], have hb : 2 ∣ b, from prime.dvd_of_dvd_pow prime_two this, have 2 ∣ gcd a b, from dvd_gcd ha hb, have habs : 2 ∣ (1:ℕ), by clear_aux_decl; simp * at *, -- replaces simp * at *, show false, from absurd habs dec_trivial end theorem sqrt_two_irrational {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 := assume h : a^2 = 2 * b^2, have 2 ∣ a^2, by simp [h], have 2 ∣ a, from prime.dvd_of_dvd_pow prime_two this, exists.elim this $ assume (c : nat) (aeq : a = 2 * c), have 2 * (2 * c^2) = 2 * b^2, by simp [eq.symm h, aeq]; simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm], have 2 * c^2 = b^2, from eq_of_mul_eq_mul_left dec_trivial this, have 2 ∣ b^2, by simp [eq.symm this], have 2 ∣ b, from prime.dvd_of_dvd_pow prime_two this, have 2 ∣ gcd a b, from dvd_gcd ‹2 ∣ a› ‹2 ∣ b›, have 2 ∣ (1 : ℕ), by simp * at *, show false, from absurd ‹2 ∣ 1› dec_trivial #check sqrt_two_irrational
b900dc735393a5cf55a8864037bf8ec78b5ad49f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/field_power.lean
bb35ad0880d844bd5f370942e8b7cd6ab5622bb6
[ "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
8,735
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import algebra.group_with_zero.power import tactic.linarith import data.equiv.ring /-! # Integer power operation on fields and division rings This file collects basic facts about the operation of raising an element of a `division_ring` to an integer power. More specialised results are provided in the case of a linearly ordered field. -/ universe u @[simp] lemma ring_hom.map_zpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L) : ∀ (a : K) (n : ℤ), f (a ^ n) = f a ^ n := f.to_monoid_with_zero_hom.map_zpow @[simp] lemma ring_equiv.map_zpow {K L : Type*} [division_ring K] [division_ring L] (f : K ≃+* L) : ∀ (a : K) (n : ℤ), f (a ^ n) = f a ^ n := f.to_ring_hom.map_zpow @[simp] lemma zpow_bit0_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit0 n) = x ^ bit0 n := by rw [zpow_bit0', zpow_bit0', neg_mul_neg] lemma even.zpow_neg {K : Type*} [division_ring K] {n : ℤ} (h : even n) (a : K) : (-a) ^ n = a ^ n := begin obtain ⟨k, rfl⟩ := h, rw [←bit0_eq_two_mul, zpow_bit0_neg], end @[simp] lemma zpow_bit1_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit1 n) = - x ^ bit1 n := by rw [zpow_bit1', zpow_bit1', neg_mul_neg, neg_mul_eq_mul_neg] section ordered_field_power open int variables {K : Type u} [linear_ordered_field K] {a : K} {n : ℤ} lemma zpow_eq_zero_iff (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨zpow_eq_zero, _⟩, rintros rfl, exact zero_zpow _ hn.ne' end lemma zpow_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (n : ℕ) := by { rw zpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma zpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (n : ℕ) := by { rw zpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } lemma zpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [of_nat_eq_coe, zpow_coe_nat], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [zpow_neg_succ_of_nat, one_div, of_nat_eq_coe, zpow_coe_nat], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [zpow_neg_succ_of_nat], apply (inv_le_inv _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : x ^ (-b) ≤ x ^ (-a), from zpow_le_of_le hx hnle, have : x ^ (-c) ≤ x ^ (-a), { apply zpow_le_of_le hx, simpa only [min_eq_left hle, neg_le_neg_iff] using h }, simpa only [max_eq_left hfle] end lemma zpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 := calc p ^ z ≤ p ^ 0 : zpow_le_of_le hp hz ... = 1 : by simp lemma one_le_zpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z := calc p ^ z ≥ p ^ 0 : zpow_le_of_le hp hz ... = 1 : by simp theorem zpow_bit0_nonneg (a : K) (n : ℤ) : 0 ≤ a ^ bit0 n := by { rw zpow_bit0₀, exact mul_self_nonneg _ } theorem zpow_two_nonneg (a : K) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 theorem zpow_bit0_pos {a : K} (h : a ≠ 0) (n : ℤ) : 0 < a ^ bit0 n := (zpow_bit0_nonneg a n).lt_of_ne (zpow_ne_zero _ h).symm theorem zpow_two_pos_of_ne_zero (a : K) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 @[simp] theorem zpow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ zpow_nonneg h' _, λ h, by rw [bit1, zpow_add_one₀ h.ne]; exact mul_neg_of_pos_of_neg (zpow_bit0_pos h.ne _) h⟩ @[simp] theorem zpow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 zpow_bit1_neg_iff @[simp] theorem zpow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := begin rw [le_iff_lt_or_eq, zpow_bit1_neg_iff], split, { rintro (h | h), { exact h.le }, { exact (zpow_eq_zero h).le } }, { intro h, rcases eq_or_lt_of_le h with rfl|h, { exact or.inr (zero_zpow _ (bit1_ne_zero n)) }, { exact or.inl h } } end @[simp] theorem zpow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le zpow_bit1_nonpos_iff lemma even.zpow_nonneg {n : ℤ} (hn : even n) (a : K) : 0 ≤ a ^ n := begin cases le_or_lt 0 a with h h, { exact zpow_nonneg h _ }, { exact (hn.zpow_neg a).subst (zpow_nonneg (neg_nonneg_of_nonpos h.le) _) } end theorem even.zpow_pos (hn : even n) (ha : a ≠ 0) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit0_pos ha k theorem odd.zpow_nonneg (hn : odd n) (ha : 0 ≤ a) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_nonneg_iff.mpr ha theorem odd.zpow_pos (hn : odd n) (ha : 0 < a) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_pos_iff.mpr ha theorem odd.zpow_nonpos (hn : odd n) (ha : a ≤ 0) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_nonpos_iff.mpr ha theorem odd.zpow_neg (hn : odd n) (ha : a < 0) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_neg_iff.mpr ha lemma even.zpow_abs {p : ℤ} (hp : even p) (a : K) : |a| ^ p = a ^ p := begin cases abs_choice a with h h; simp only [h, hp.zpow_neg _], end @[simp] lemma zpow_bit0_abs (a : K) (p : ℤ) : |a| ^ bit0 p = a ^ bit0 p := (even_bit0 _).zpow_abs _ lemma even.abs_zpow {p : ℤ} (hp : even p) (a : K) : |a ^ p| = a ^ p := begin rw [abs_eq_self], exact hp.zpow_nonneg _ end @[simp] lemma abs_zpow_bit0 (a : K) (p : ℤ) : |a ^ bit0 p| = a ^ bit0 p := (even_bit0 _).abs_zpow _ end ordered_field_power lemma one_lt_zpow {K} [linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (n : ℕ) h := (zpow_coe_nat p n).symm.subst (one_lt_pow hp $ int.coe_nat_ne_zero.mp h.ne') | -[1+ n] h := ((int.neg_succ_not_pos _).mp h).elim section ordered variables {K : Type*} [linear_ordered_field K] lemma nat.zpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n := by { apply zpow_pos_of_pos, exact_mod_cast h } lemma nat.zpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 := ne_of_gt (nat.zpow_pos_of_pos h n) lemma zpow_strict_mono {x : K} (hx : 1 < x) : strict_mono (λ n:ℤ, x ^ n) := λ m n h, show x ^ m < x ^ n, begin have xpos : 0 < x := zero_lt_one.trans hx, have h₀ : x ≠ 0 := xpos.ne', have hxm : 0 < x^m := zpow_pos_of_pos xpos m, have h : 1 < x ^ (n - m) := one_lt_zpow hx _ (sub_pos_of_lt h), replace h := mul_lt_mul_of_pos_right h hxm, rwa [sub_eq_add_neg, zpow_add₀ h₀, mul_assoc, zpow_neg_mul_zpow_self _ h₀, one_mul, mul_one] at h, end @[simp] lemma zpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m < x ^ n ↔ m < n := (zpow_strict_mono hx).lt_iff_lt @[simp] lemma zpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m ≤ x ^ n ↔ m ≤ n := (zpow_strict_mono hx).le_iff_le @[simp] lemma pos_div_pow_pos {a b : K} (ha : 0 < a) (hb : 0 < b) (k : ℕ) : 0 < a/b^k := div_pos ha (pow_pos hb k) @[simp] lemma div_pow_le {a b : K} (ha : 0 < a) (hb : 1 ≤ b) (k : ℕ) : a/b^k ≤ a := (div_le_iff $ pow_pos (lt_of_lt_of_le zero_lt_one hb) k).mpr (calc a = a * 1 : (mul_one a).symm ... ≤ a*b^k : (mul_le_mul_left ha).mpr $ one_le_pow_of_one_le hb _) lemma zpow_injective {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) : function.injective ((^) x : ℤ → K) := begin intros m n h, rcases h₁.lt_or_lt with H|H, { apply (zpow_strict_mono (one_lt_inv h₀ H)).injective, show x⁻¹ ^ m = x⁻¹ ^ n, rw [← zpow_neg_one₀, ← zpow_mul₀, ← zpow_mul₀, mul_comm _ m, mul_comm _ n, zpow_mul₀, zpow_mul₀, h], }, { exact (zpow_strict_mono H).injective h, }, end @[simp] lemma zpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} : x ^ m = x ^ n ↔ m = n := (zpow_injective h₀ h₁).eq_iff end ordered section variables {K : Type*} [field K] @[simp, norm_cast] theorem rat.cast_zpow [char_zero K] (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : K) = q ^ n := (rat.cast_hom K).map_zpow q n end
5b4e959c149be6357e933dc51e74ce1c74868460
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/topology/instances/real.lean
17b963588a19e227a0b70bea3f21d3eb86eea478
[ "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
16,892
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import topology.algebra.continuous_functions import ring_theory.subring import group_theory.archimedean /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast instance : proper_space ℤ := ⟨ begin intros x r, apply set.finite.is_compact, have : closed_ball x r = coe ⁻¹' (closed_ball (x:ℝ) r) := rfl, simp [this, closed_ball_Icc, set.Icc_ℤ_finite], end ⟩ theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, abs (y - x) < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets ((is_open_lt' (abs r / 2)).preimage continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (((is_open_gt' (abs a₁ + 1)).preimage continuous_abs).prod ((is_open_gt' (abs a₂ + 1)).preimage continuous_abs )) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, (set.finite_lt_nat _).image _, _⟩, rintro x ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, use i, split, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : is_compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance {a b : ℝ} : compact_space (Icc a b) := compact_iff_compact_space.mp compact_Icc lemma compact_pi_Icc {ι : Type*} {a b : ι → ℝ} : is_compact (Icc a b) := pi_univ_Icc a b ▸ compact_univ_pi $ λ i, compact_Icc instance compact_space_pi_Icc {ι : Type*} {a b : ι → ℝ} : compact_space (Icc a b) := compact_iff_compact_space.mp compact_pi_Icc instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (compact_Icc.image_of_continuous_on h) end instance reals_semimodule : topological_semimodule ℝ ℝ := ⟨continuous_mul⟩ instance real_maps_algebra {α : Type*} [topological_space α] : algebra ℝ C(α, ℝ) := continuous_map_algebra section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, abs (x - g) < ε, by simpa only [real.mem_closure_iff, abs_sub], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
db5c99292b7b9c65f68721369617b42d2e6e8be7
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/elab_cmd.lean
c835a715370cab4dc00910b2ba1cc876b697fbbf
[ "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
652
lean
import Lean open Lean.Elab.Term open Lean.Elab.Command elab "∃'" b:term "," P:term : term => do let ex ← `(Exists (fun $b => $P)); elabTerm ex none elab "#check2" b:term : command => do let cmd ← `(#check $b #check $b); elabCommand cmd #check ∃' x, x > 0 #check ∃' (x : UInt32), x > 0 #check2 10 elab "try" t:tactic : tactic => do let t' ← `(tactic| first $t | skip); Lean.Elab.Tactic.evalTactic t' theorem tst (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails traceState; try exact h3; traceState; try exact h1; }
73a91713cf6be41c3deba387719e1fc3c3c6d778
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/finiteness.lean
98242602f66305c1502562c1ca51d8861a9b0a35
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
33,018
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 ring_theory.noetherian import ring_theory.ideal.operations import ring_theory.algebra_tower import group_theory.finiteness /-! # Finiteness conditions in commutative algebra In this file we define several notions of finiteness that are common in commutative algebra. ## Main declarations - `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite` all of these express that some object is finitely generated *as module* over some base ring. - `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type` all of these express that some object is finitely generated *as algebra* over some base ring. - `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation` all of these express that some object is finitely presented *as algebra* over some base ring. -/ open function (surjective) open_locale big_operators section module_and_algebra variables (R A B M N : Type*) [comm_ring R] variables [comm_ring A] [algebra R A] [comm_ring B] [algebra R B] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] /-- A module over a commutative ring is `finite` if it is finitely generated as a module. -/ class module.finite (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] : Prop := (out : (⊤ : submodule R M).fg) /-- An algebra over a commutative ring is of `finite_type` if it is finitely generated over the base ring as algebra. -/ class algebra.finite_type : Prop := (out : (⊤ : subalgebra R A).fg) /-- An algebra over a commutative ring is `finite_presentation` if it is the quotient of a polynomial ring in `n` variables by a finitely generated ideal. -/ def algebra.finite_presentation : Prop := ∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg namespace module lemma finite_def {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : finite R M ↔ (⊤ : submodule R M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ @[priority 100] -- see Note [lower instance priority] instance is_noetherian.finite [is_noetherian R M] : finite R M := ⟨is_noetherian.noetherian ⊤⟩ namespace finite open submodule set lemma iff_add_monoid_fg {M : Type*} [add_comm_monoid M] : module.finite ℕ M ↔ add_monoid.fg M := ⟨λ h, add_monoid.fg_def.2 $ (fg_iff_add_submonoid_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_submonoid_fg ⊤).2 (add_monoid.fg_def.1 h)⟩ lemma iff_add_group_fg {G : Type*} [add_comm_group G] : module.finite ℤ G ↔ add_group.fg G := ⟨λ h, add_group.fg_def.2 $ (fg_iff_add_subgroup_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_subgroup_fg ⊤).2 (add_group.fg_def.1 h)⟩ variables {R M N} lemma exists_fin [finite R M] : ∃ (n : ℕ) (s : fin n → M), span R (range s) = ⊤ := submodule.fg_iff_exists_fin_generating_family.mp out lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) : finite R N := ⟨begin rw [← linear_map.range_eq_top.2 hf, ← submodule.map_top], exact submodule.fg_map hM.1 end⟩ lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N) (hf : function.injective f) : finite R M := ⟨fg_of_injective f $ linear_map.ker_eq_bot.2 hf⟩ variables (R) instance self : finite R R := ⟨⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩⟩ variables {R} instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) := ⟨begin rw ← submodule.prod_top, exact submodule.fg_prod hM.1 hN.1 end⟩ lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N := of_surjective (e : M →ₗ[R] N) e.surjective section algebra lemma trans [algebra A B] [is_scalar_tower R A B] : ∀ [finite R A] [finite A B], finite R B | ⟨⟨s, hs⟩⟩ ⟨⟨t, ht⟩⟩ := ⟨submodule.fg_def.2 ⟨set.image2 (•) (↑s : set A) (↑t : set B), set.finite.image2 _ s.finite_to_set t.finite_to_set, by rw [set.image2_smul, submodule.span_smul hs (↑t : set B), ht, submodule.restrict_scalars_top]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance finite_type [hRA : finite R A] : algebra.finite_type R A := ⟨subalgebra.fg_of_submodule_fg hRA.1⟩ end algebra end finite end module namespace algebra namespace finite_type lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩ section open_locale classical protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) := ⟨⟨finset.univ.image mv_polynomial.X, begin rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p (λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x) (λ i n f hif hn ih, _)) (λ p q ihp ihq, subalgebra.add_mem _ ihp ihq), rw [add_comm, mv_polynomial.monomial_add_single], exact subalgebra.mul_mem _ ih (subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _) end⟩⟩ end variables {R A B} lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) : finite_type R B := ⟨begin convert subalgebra.fg_map _ f hRA.1, simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf end⟩ lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B := hRA.of_surjective e e.surjective lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) : finite_type R B := ⟨fg_trans' hRA.1 hAB.1⟩ /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a finset. -/ lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A) (f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) := begin split, { rintro ⟨s, hs⟩, use [s, mv_polynomial.aeval coe], intro x, have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl, rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs], exact mem_top }, { rintro ⟨s, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype. -/ lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) [fintype ι] (f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial, rintro ⟨s, ⟨f, hsur⟩⟩, use [{x // x ∈ s}, by apply_instance, f, hsur] }, { rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩, letI : fintype ι := hfintype, exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n` variables. -/ lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ) (f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial', rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩, letI := hfintype, obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) hfintype, replace equiv := mv_polynomial.rename_equiv R equiv, exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur (alg_equiv.symm equiv).surjective⟩ }, { rintro ⟨n, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur } end /-- A finitely presented algebra is of finite type. -/ lemma of_finite_presentation : finite_presentation R A → finite_type R A := begin rintro ⟨n, f, hf⟩, apply (finite_type.iff_quotient_mv_polynomial'').2, exact ⟨n, f, hf.1⟩ end end finite_type namespace finite_presentation variables {R A B} /-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely presented. -/ lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A := begin refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩, obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h, refine ⟨n, f, hf, _⟩, have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance, replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian, exact hnoet f.to_ring_hom.ker, end /-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/ lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B := begin obtain ⟨n, f, hf⟩ := hfp, use [n, alg_hom.comp ↑e f], split, { exact function.surjective.comp e.surjective hf.1 }, suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker, { rw hker, exact hf.2 }, { have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom, { have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl, have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl, rw [h, h1] }, rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot, ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] } end variable (R) /-- The ring of polynomials in finitely many variables is finitely presented. -/ lemma mv_polynomial (ι : Type u_2) [fintype ι] : finite_presentation R (mv_polynomial ι R) := begin obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _, replace equiv := mv_polynomial.rename_equiv R equiv, refine ⟨_, alg_equiv.to_alg_hom equiv.symm, _⟩, split, { exact (alg_equiv.symm equiv).surjective }, suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom, { rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj], exact submodule.fg_bot }, exact (alg_equiv.symm equiv).injective end /-- `R` is finitely presented as `R`-algebra. -/ lemma self : finite_presentation R R := equiv (mv_polynomial R pempty) (mv_polynomial.pempty_alg_equiv R) variable {R} /-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely presented. -/ lemma quotient {I : ideal A} (h : submodule.fg I) (hfp : finite_presentation R A) : finite_presentation R I.quotient := begin obtain ⟨n, f, hf⟩ := hfp, refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩, { exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 }, { refine submodule.fg_ker_ring_hom_comp _ _ hf.2 _ hf.1, rwa ideal.quotient.mkₐ_ker R I } end /-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented, then so is `B`. -/ lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg) (hfp : finite_presentation R A) : finite_presentation R B := equiv (quotient hker hfp) (ideal.quotient_ker_alg_equiv_of_surjective hf) lemma iff : finite_presentation R A ↔ ∃ n (I : ideal (_root_.mv_polynomial (fin n) R)) (e : I.quotient ≃ₐ[R] A), I.fg := begin refine ⟨λ h,_, λ h, _⟩, { obtain ⟨n, f, hf⟩ := h, use [n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2] }, { obtain ⟨n, I, e, hfg⟩ := h, exact equiv (quotient hfg (mv_polynomial R _)) e } end /-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype by a finitely generated ideal. -/ lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) [fintype ι] (f : (_root_.mv_polynomial ι R) →ₐ[R] A), (surjective f) ∧ f.to_ring_hom.ker.fg := begin split, { rintro ⟨n, f, hfs, hfk⟩, set ulift_var := mv_polynomial.rename_equiv R equiv.ulift, refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom, hfs.comp ulift_var.surjective, submodule.fg_ker_ring_hom_comp _ _ _ hfk ulift_var.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, }, { rintro ⟨ι, hfintype, f, hf⟩, haveI : fintype ι := hfintype, obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _, replace equiv := mv_polynomial.rename_equiv R equiv, refine ⟨fintype.card ι, f.comp equiv.symm, hf.1.comp (alg_equiv.symm equiv).surjective, submodule.fg_ker_ring_hom_comp _ f _ hf.2 equiv.symm.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), } end /-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented as `R`-algebra. -/ lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*) [fintype ι] : finite_presentation R (_root_.mv_polynomial ι A) := begin classical, let n := fintype.card ι, obtain ⟨e⟩ := fintype.trunc_equiv_fin ι, replace e := (mv_polynomial.rename_equiv A e).restrict_scalars R, refine equiv _ e.symm, obtain ⟨m, I, e, hfg⟩ := iff.1 hfp, refine equiv _ (mv_polynomial.map_alg_equiv (fin n) e), -- typeclass inference seems to struggle to find this path letI : is_scalar_tower R (_root_.mv_polynomial (fin m) R) (_root_.mv_polynomial (fin m) R) := is_scalar_tower.right, letI : is_scalar_tower R (_root_.mv_polynomial (fin m) R) (_root_.mv_polynomial (fin n) (_root_.mv_polynomial (fin m) R)) := mv_polynomial.is_scalar_tower, refine equiv _ ((@mv_polynomial.quotient_equiv_quotient_mv_polynomial _ (fin n) _ I).restrict_scalars R).symm, refine quotient (submodule.map_fg_of_fg I hfg _) _, let := mv_polynomial.sum_alg_equiv R (fin n) (fin m), refine equiv _ this, exact equiv (mv_polynomial R (fin (n + m))) (mv_polynomial.rename_equiv R fin_sum_fin_equiv).symm end /-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is finitely presented as `R`-algebra. -/ lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A) (hfpB : finite_presentation A B) : finite_presentation R B := begin obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB, exact equiv (quotient hfg (mv_polynomial_of_finite_presentation hfpA _)) (e.restrict_scalars R) end end finite_presentation end algebra end module_and_algebra namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] /-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/ def finite (f : A →+* B) : Prop := by letI : algebra A B := f.to_algebra; exact module.finite A B /-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra /-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra namespace finite variables (A) lemma id : finite (ring_hom.id A) := module.finite.self A variables {A} lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite := begin letI := f.to_algebra, exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf end lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := @module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f := @module.finite.finite_type _ _ _ _ f.to_algebra hf end finite namespace finite_type variables (A) lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := @algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf { to_fun := g, commutes' := λ a, rfl, .. g } hg lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type := by { rw ← f.comp_id, exact (id A).comp_surjective hf } lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := @algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type := @algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf end finite_type namespace finite_presentation variables (A) lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.ker.fg) : (g.comp f).finite_presentation := @algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra { to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation := by { rw ← f.comp_id, exact (id A).comp_surjective hf hker} lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation := @algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _ lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := @algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra { smul_assoc := λ a b c, begin simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end } hf hg end finite_presentation end ring_hom namespace alg_hom variables {R A B C : Type*} [comm_ring R] variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra R A] [algebra R B] [algebra R C] /-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism. In other words, if `B` is finitely generated as `A`-module. -/ def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite /-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism. In other words, if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type /-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation namespace finite variables (R A) lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := ring_hom.finite.comp hg hf lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite := ring_hom.finite.of_surjective f hf lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f := ring_hom.finite.finite_type hf end finite namespace finite_type variables (R A) lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := ring_hom.finite_type.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := ring_hom.finite_type.comp_surjective hf hg lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type := ring_hom.finite_type.of_surjective f hf lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type := ring_hom.finite_type.of_finite_presentation hf end finite_type namespace finite_presentation variables (R A) lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp_surjective hf hg hker lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) : f.finite_presentation := ring_hom.finite_presentation.of_surjective f hf hker lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} : f.finite_type ↔ f.finite_presentation := ring_hom.finite_presentation.of_finite_type end finite_presentation end alg_hom section monoid_algebra variables {R : Type*} {M : Type*} namespace add_monoid_algebra open algebra add_submonoid submodule section span section semiring variables [comm_semiring R] [add_monoid M] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) := begin suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : of' R M '' f.support ⊆ ⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support, { intros s hs, exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoin_support f) end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [add_comm_monoid M] /-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `add_monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of'_mem_span [nontrivial R] {m : M} {S : set M} : of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) : m ∈ closure S := begin suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S), { simpa [← to_submonoid_closure] }, rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x), ← monoid_hom.map_mclosure] at h, simpa using of'_mem_span.1 h end end ring end span variables [add_comm_monoid M] /-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra, `add_monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]; refl⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end /-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] : finite_type R (add_monoid_algebra R M) := begin obtain ⟨S, hS⟩ := h.out, exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval (λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS) end /-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M := begin refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩, obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h, refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩, have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule, { simp only [hS, top_to_submodule, submodule.mem_top], }, rw [adjoin_eq_span] at hm, exact mem_closure_of_mem_span_closure hm end /-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] : add_monoid.fg M := finite_type_iff_fg.1 h /-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R G) ↔ add_group.fg G := by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg end add_monoid_algebra namespace monoid_algebra open algebra submonoid submodule section span section semiring variables [comm_semiring R] [monoid M] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoint_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) := begin suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : (of R M) '' f.support ⊆ ⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support, { intros s hs, exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoint_support f) end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [comm_monoid M] /-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} : of R M m ∈ span R (of R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) : m ∈ closure S := begin rw ← monoid_hom.map_mclosure at h, simpa using of_mem_span_of_iff.1 h end end ring end span variables [comm_monoid M] /-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra, `monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end /-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) := add_monoid_algebra.finite_type_of_fg.equiv (to_additive_alg_equiv R M).symm /-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R M) ↔ monoid.fg M := ⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $ to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩ /-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] : monoid.fg M := finite_type_iff_fg.1 h /-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R G) ↔ group.fg G := by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg end monoid_algebra end monoid_algebra
06a9bbe9cdf66220a47844414d5545e0976a98e0
1a61aba1b67cddccce19532a9596efe44be4285f
/tests/lean/hott/614.hlean
bd35214793bae6eacf7b911596574efc78bc1462
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
588
hlean
import hit.circle open circle eq int pi attribute circle.rec [recursor] protected definition my_decode {x : circle} (c : circle.code x) : base = x := begin induction x, { revert c, exact power loop }, { apply arrow_pathover_left, intro b, apply concato_eq, apply pathover_eq_r, rewrite [power_con,transport_code_loop]}, end protected definition my_decode' {x : circle} : circle.code x → base = x := begin induction x, { exact power loop}, { apply arrow_pathover_left, intro b, apply concato_eq, apply pathover_eq_r, rewrite [power_con,transport_code_loop]}, end
6ad0abb78d657a6a9f3df88d2a7cee88304d0562
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/proj.lean
724bdc01e851ad4e271462ce7df39b6be1493f4d
[ "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
341
lean
import logic inductive sigma {A : Type} (B : A → Type) := mk : Π (a : A), B a → sigma B #projections sigma :: proj1 proj2 check sigma.proj1 check sigma.proj2 variables {A : Type} {B : A → Type} variables (a : A) (b : B a) theorem tst1 : sigma.proj1 (sigma.mk a b) = a := rfl theorem tst2 : sigma.proj2 (sigma.mk a b) = b := rfl
fe1e47ff5180c64c363ab780f7dc49814ee72df4
367134ba5a65885e863bdc4507601606690974c1
/src/probability_theory/integration.lean
ecdb312b921ffb8bffa3df02bc71d7ed3353ce62
[ "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
5,750
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Martin Zinkevich -/ import measure_theory.integration import probability_theory.independence /-! # Integration in Probability Theory Integration results for independent random variables. Specifically, for two independent random variables X and Y over the extended non-negative reals, `E[X * Y] = E[X] * E[Y]`, and similar results. -/ noncomputable theory open set measure_theory open_locale ennreal variables {α : Type*} namespace probability_theory /-- This (roughly) proves that if a random variable `f` is independent of an event `T`, then if you restrict the random variable to `T`, then `E[f * indicator T c 0]=E[f] * E[indicator T c 0]`. It is useful for `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space`. -/ lemma lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator {Mf : measurable_space α} [M : measurable_space α] {μ : measure α} (hMf : Mf ≤ M) (c : ℝ≥0∞) {T : set α} (h_meas_T : M.measurable_set' T) (h_ind : indep_sets Mf.measurable_set' {T} μ) {f : α → ℝ≥0∞} (h_meas_f : @measurable α ℝ≥0∞ Mf _ f) : ∫⁻ a, f a * T.indicator (λ _, c) a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, T.indicator (λ _, c) a ∂μ := begin revert f, have h_mul_indicator : ∀ g, measurable g → measurable (λ a, g a * T.indicator (λ x, c) a) := λ g h_mg, h_mg.ennreal_mul (measurable_const.indicator h_meas_T), apply measurable.ennreal_induction, { intros c' s' h_meas_s', simp_rw [← inter_indicator_mul], rw [lintegral_indicator _ (measurable_set.inter (hMf _ h_meas_s') (h_meas_T)), lintegral_indicator _ (hMf _ h_meas_s'), lintegral_indicator _ h_meas_T], simp only [measurable_const, lintegral_const, univ_inter, lintegral_const_mul, measurable_set.univ, measure.restrict_apply], rw h_ind, { ring }, { apply h_meas_s' }, { simp } }, { intros f' g h_univ h_meas_f' h_meas_g h_ind_f' h_ind_g, have h_measM_f' := h_meas_f'.mono hMf le_rfl, have h_measM_g := h_meas_g.mono hMf le_rfl, simp_rw [pi.add_apply, right_distrib], rw [lintegral_add (h_mul_indicator _ h_measM_f') (h_mul_indicator _ h_measM_g), lintegral_add h_measM_f' h_measM_g, right_distrib, h_ind_f', h_ind_g] }, { intros f h_meas_f h_mono_f h_ind_f, have h_measM_f := λ n, (h_meas_f n).mono hMf le_rfl, simp_rw [ennreal.supr_mul], rw [lintegral_supr h_measM_f h_mono_f, lintegral_supr, ennreal.supr_mul], { simp_rw [← h_ind_f] }, { exact λ n, h_mul_indicator _ (h_measM_f n) }, { intros m n h_le a, apply ennreal.mul_le_mul _ le_rfl, apply h_mono_f h_le } }, end /-- This (roughly) proves that if `f` and `g` are independent random variables, then `E[f * g] = E[f] * E[g]`. However, instead of directly using the independence of the random variables, it uses the independence of measurable spaces for the domains of `f` and `g`. This is similar to the sigma-algebra approach to independence. See `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_fn` for a more common variant of the product of independent variables. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space {Mf : measurable_space α} {Mg : measurable_space α} [M : measurable_space α] {μ : measure α} (hMf : Mf ≤ M) (hMg : Mg ≤ M) (h_ind : indep Mf Mg μ) (f g : α → ℝ≥0∞) (h_meas_f : @measurable α ℝ≥0∞ Mf _ f) (h_meas_g : @measurable α ℝ≥0∞ Mg _ g) : ∫⁻ a, f a * g a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, g a ∂μ := begin revert g, have h_meas_Mg : ∀ ⦃f : α → ℝ≥0∞⦄, @measurable α ℝ≥0∞ Mg _ f → measurable f, { intros f' h_meas_f', apply h_meas_f'.mono hMg le_rfl }, have h_measM_f := h_meas_f.mono hMf le_rfl, apply measurable.ennreal_induction, { intros c s h_s, apply lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator hMf _ (hMg _ h_s) _ h_meas_f, apply probability_theory.indep_sets_of_indep_sets_of_le_right h_ind, rw singleton_subset_iff, apply h_s }, { intros f' g h_univ h_measMg_f' h_measMg_g h_ind_f' h_ind_g', have h_measM_f' := h_meas_Mg h_measMg_f', have h_measM_g := h_meas_Mg h_measMg_g, simp_rw [pi.add_apply, left_distrib], rw [lintegral_add h_measM_f' h_measM_g, lintegral_add (measurable.ennreal_mul h_measM_f h_measM_f') (measurable.ennreal_mul h_measM_f h_measM_g), left_distrib, h_ind_f', h_ind_g'] }, { intros f' h_meas_f' h_mono_f' h_ind_f', have h_measM_f' := λ n, h_meas_Mg (h_meas_f' n), simp_rw [ennreal.mul_supr], rw [lintegral_supr, lintegral_supr h_measM_f' h_mono_f', ennreal.mul_supr], { simp_rw [← h_ind_f'] }, { apply λ (n : ℕ), measurable.ennreal_mul h_measM_f (h_measM_f' n) }, { apply λ (n : ℕ) (m : ℕ) (h_le : n ≤ m) a, ennreal.mul_le_mul le_rfl (h_mono_f' h_le a) } } end /-- This proves that if `f` and `g` are independent random variables, then `E[f * g] = E[f] * E[g]`. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun [M : measurable_space α] (μ : measure α) (f g : α → ℝ≥0∞) (h_meas_f : measurable f) (h_meas_g : measurable g) (h_indep_fun : indep_fun (borel ennreal) (borel ennreal) f g μ) : ∫⁻ (a : α), (f * g) a ∂μ = ∫⁻ (a : α), f a ∂μ * ∫⁻ (a : α), g a ∂μ := begin apply lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space (measurable_iff_comap_le.1 h_meas_f) (measurable_iff_comap_le.1 h_meas_g), apply h_indep_fun, repeat { apply measurable.of_comap_le le_rfl }, end end probability_theory
560b85de160befc201ad745fc1c9ff1a170ab325
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/add_torsor_bases.lean
5e162d8f02c820269a316023e0706e0779060608
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,168
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import analysis.normed_space.finite_dimension import analysis.calculus.affine_map import analysis.convex.combination import linear_algebra.affine_space.finite_dimensional /-! # Bases in normed affine spaces. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains results about bases in normed affine spaces. ## Main definitions: * `continuous_barycentric_coord` * `is_open_map_barycentric_coord` * `affine_basis.interior_convex_hull` * `exists_subset_affine_independent_span_eq_top_of_open` * `interior_convex_hull_nonempty_iff_affine_span_eq_top` -/ section barycentric variables {ι 𝕜 E P : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] variables [normed_add_comm_group E] [normed_space 𝕜 E] variables [metric_space P] [normed_add_torsor E P] include E lemma is_open_map_barycentric_coord [nontrivial ι] (b : affine_basis ι 𝕜 P) (i : ι) : is_open_map (b.coord i) := affine_map.is_open_map_linear_iff.mp $ (b.coord i).linear.is_open_map_of_finite_dimensional $ (b.coord i).linear_surjective_iff.mpr (b.surjective_coord i) variables [finite_dimensional 𝕜 E] (b : affine_basis ι 𝕜 P) @[continuity] lemma continuous_barycentric_coord (i : ι) : continuous (b.coord i) := (b.coord i).continuous_of_finite_dimensional lemma smooth_barycentric_coord (b : affine_basis ι 𝕜 E) (i : ι) : cont_diff 𝕜 ⊤ (b.coord i) := (⟨b.coord i, continuous_barycentric_coord b i⟩ : E →A[𝕜] 𝕜).cont_diff end barycentric open set /-- Given a finite-dimensional normed real vector space, the interior of the convex hull of an affine basis is the set of points whose barycentric coordinates are strictly positive with respect to this basis. TODO Restate this result for affine spaces (instead of vector spaces) once the definition of convexity is generalised to this setting. -/ lemma affine_basis.interior_convex_hull {ι E : Type*} [finite ι] [normed_add_comm_group E] [normed_space ℝ E] (b : affine_basis ι ℝ E) : interior (convex_hull ℝ (range b)) = {x | ∀ i, 0 < b.coord i x} := begin casesI subsingleton_or_nontrivial ι, { -- The zero-dimensional case. have : range b = univ, from affine_subspace.eq_univ_of_subsingleton_span_eq_top (subsingleton_range _) b.tot, simp [this] }, { -- The positive-dimensional case. haveI : finite_dimensional ℝ E := b.finite_dimensional, have : convex_hull ℝ (range b) = ⋂ i, (b.coord i)⁻¹' Ici 0, { rw [b.convex_hull_eq_nonneg_coord, set_of_forall], refl }, ext, simp only [this, interior_Inter, ← is_open_map.preimage_interior_eq_interior_preimage (is_open_map_barycentric_coord b _) (continuous_barycentric_coord b _), interior_Ici, mem_Inter, mem_set_of_eq, mem_Ioi, mem_preimage], }, end variables {V P : Type*} [normed_add_comm_group V] [normed_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_map /-- Given a set `s` of affine-independent points belonging to an open set `u`, we may extend `s` to an affine basis, all of whose elements belong to `u`. -/ lemma is_open.exists_between_affine_independent_span_eq_top {s u : set P} (hu : is_open u) (hsu : s ⊆ u) (hne : s.nonempty) (h : affine_independent ℝ (coe : s → P)) : ∃ t : set P, s ⊆ t ∧ t ⊆ u ∧ affine_independent ℝ (coe : t → P) ∧ affine_span ℝ t = ⊤ := begin obtain ⟨q, hq⟩ := hne, obtain ⟨ε, ε0, hεu⟩ := metric.nhds_basis_closed_ball.mem_iff.1 (hu.mem_nhds $ hsu hq), obtain ⟨t, ht₁, ht₂, ht₃⟩ := exists_subset_affine_independent_affine_span_eq_top h, let f : P → P := λ y, line_map q y (ε / dist y q), have hf : ∀ y, f y ∈ u, { refine λ y, hεu _, simp only [f], rw [metric.mem_closed_ball, line_map_apply, dist_vadd_left, norm_smul, real.norm_eq_abs, dist_eq_norm_vsub V y q, abs_div, abs_of_pos ε0, abs_of_nonneg (norm_nonneg _), div_mul_comm], exact mul_le_of_le_one_left ε0.le (div_self_le_one _) }, have hεyq : ∀ y ∉ s, ε / dist y q ≠ 0, from λ y hy, div_ne_zero ε0.ne' (dist_ne_zero.2 (ne_of_mem_of_not_mem hq hy).symm), classical, let w : t → ℝˣ := λ p, if hp : (p : P) ∈ s then 1 else units.mk0 _ (hεyq ↑p hp), refine ⟨set.range (λ (p : t), line_map q p (w p : ℝ)), _, _, _, _⟩, { intros p hp, use ⟨p, ht₁ hp⟩, simp [w, hp], }, { rintros y ⟨⟨p, hp⟩, rfl⟩, by_cases hps : p ∈ s; simp only [w, hps, line_map_apply_one, units.coe_mk0, dif_neg, dif_pos, not_false_iff, units.coe_one, subtype.coe_mk]; [exact hsu hps, exact hf p], }, { exact (ht₂.units_line_map ⟨q, ht₁ hq⟩ w).range, }, { rw [affine_span_eq_affine_span_line_map_units (ht₁ hq) w, ht₃], }, end lemma is_open.exists_subset_affine_independent_span_eq_top {u : set P} (hu : is_open u) (hne : u.nonempty) : ∃ s ⊆ u, affine_independent ℝ (coe : s → P) ∧ affine_span ℝ s = ⊤ := begin rcases hne with ⟨x, hx⟩, rcases hu.exists_between_affine_independent_span_eq_top (singleton_subset_iff.mpr hx) (singleton_nonempty _) (affine_independent_of_subsingleton _ _) with ⟨s, -, hsu, hs⟩, exact ⟨s, hsu, hs⟩ end /-- The affine span of a nonempty open set is `⊤`. -/ lemma is_open.affine_span_eq_top {u : set P} (hu : is_open u) (hne : u.nonempty) : affine_span ℝ u = ⊤ := let ⟨s, hsu, hs, hs'⟩ := hu.exists_subset_affine_independent_span_eq_top hne in top_unique $ hs' ▸ affine_span_mono _ hsu lemma affine_span_eq_top_of_nonempty_interior {s : set V} (hs : (interior $ convex_hull ℝ s).nonempty) : affine_span ℝ s = ⊤ := top_unique $ is_open_interior.affine_span_eq_top hs ▸ (affine_span_mono _ interior_subset).trans_eq (affine_span_convex_hull _) lemma affine_basis.centroid_mem_interior_convex_hull {ι} [fintype ι] (b : affine_basis ι ℝ V) : finset.univ.centroid ℝ b ∈ interior (convex_hull ℝ (range b)) := begin haveI := b.nonempty, simp only [b.interior_convex_hull, mem_set_of_eq, b.coord_apply_centroid (finset.mem_univ _), inv_pos, nat.cast_pos, finset.card_pos, finset.univ_nonempty, forall_true_iff] end lemma interior_convex_hull_nonempty_iff_affine_span_eq_top [finite_dimensional ℝ V] {s : set V} : (interior (convex_hull ℝ s)).nonempty ↔ affine_span ℝ s = ⊤ := begin refine ⟨affine_span_eq_top_of_nonempty_interior, λ h, _⟩, obtain ⟨t, hts, b, hb⟩ := affine_basis.exists_affine_subbasis h, suffices : (interior (convex_hull ℝ (range b))).nonempty, { rw [hb, subtype.range_coe_subtype, set_of_mem_eq] at this, refine this.mono _, mono* }, lift t to finset V using b.finite_set, exact ⟨_, b.centroid_mem_interior_convex_hull⟩ end lemma convex.interior_nonempty_iff_affine_span_eq_top [finite_dimensional ℝ V] {s : set V} (hs : convex ℝ s) : (interior s).nonempty ↔ affine_span ℝ s = ⊤ := by rw [← interior_convex_hull_nonempty_iff_affine_span_eq_top, hs.convex_hull_eq]
5b81d0f24ba46b24134bfb0f537a3381500d3531
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/calcErrors.lean
c83e2edc9eb34744d6d3f0e92328669e96eb4a65
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,566
lean
theorem ex1 (a b c : Nat) (h₁ : a = b) (h₂ : b = c) : a + b = 0 + c + b := calc a + b = b + b := by rw [h₁] _ = 0 + c + b := rfl theorem ex2 (a b c : Nat) (h₁ : a = b) (h₂ : b = c) : a + b = 0 + c + b := calc a + b = b + b := by rw [h₁] 0 + c + b = 0 + c + b := rfl theorem ex3 (a b c : Nat) (h₁ : a = b) (h₂ : b = c) : a + b = 0 + c + b := calc a + b = b + b := by rw [h₁] _ = 0 + b + b := by rw [Nat.zero_add] _ = 0 + c + b := by rw [h₂] theorem ex4 (p : Nat → Prop) (a b : Nat) (h₁ : p a) (h₂ : p b) : p c := calc p a := h₁ _ := h₂ theorem ex5 (p : Nat → Nat → Prop) (a b : Nat) (h₁ : p a b) (h₂ : p b c) : p a c := calc p a b := h₁ p _ c := h₂ infix:50 " ≅ " => HEq instance {α β γ} : Trans (· ≅ · : α → β → Prop) (· ≅ · : β → γ → Prop) (· ≅ · : α → γ → Prop) where trans h₁ h₂ := HEq.trans h₁ h₂ theorem ex6 {a : α} {b : β} {c : γ} (h₁ : HEq a b) (h₂ : b ≅ c) : a ≅ c := calc a ≅ b := h₁ _ ≅ c := h₂ -- Error because the last two arguments of HEq are not explicit abbrev HEqRel {α β} (a : α) (b : β) := HEq a b infix:50 "===" => HEqRel instance {α β γ} : Trans (HEqRel : α → β → Prop) (HEqRel : β → γ → Prop) (HEqRel : α → γ → Prop) where trans h₁ h₂ := HEq.trans h₁ h₂ theorem ex7 {a : α} {b : β} {c : γ} (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := calc a === b := h₁ _ === c := h₂
1c07a78c9dda155704f41f29891a690f284f32be
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/homology/additive.lean
3eb6121fe66855fcdd594290903ec71a140aa0e7
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
8,810
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.homology.homology import algebra.homology.single import category_theory.preadditive.additive_functor /-! # Homology is an additive functor When `V` is preadditive, `homological_complex V c` is also preadditive, and `homology_functor` is additive. TODO: similarly for `R`-linear. -/ universes v u open_locale classical noncomputable theory open category_theory category_theory.limits homological_complex variables {ι : Type*} variables {V : Type u} [category.{v} V] [preadditive V] variables {c : complex_shape ι} {C D E : homological_complex V c} variables (f g : C ⟶ D) (h k : D ⟶ E) (i : ι) namespace homological_complex instance : has_zero (C ⟶ D) := ⟨{ f := λ i, 0 }⟩ instance : has_add (C ⟶ D) := ⟨λ f g, { f := λ i, f.f i + g.f i, }⟩ instance : has_neg (C ⟶ D) := ⟨λ f, { f := λ i, -(f.f i), }⟩ instance : has_sub (C ⟶ D) := ⟨λ f g, { f := λ i, f.f i - g.f i, }⟩ @[simp] lemma zero_f_apply (i : ι) : (0 : C ⟶ D).f i = 0 := rfl @[simp] lemma add_f_apply (f g : C ⟶ D) (i : ι) : (f + g).f i = f.f i + g.f i := rfl @[simp] lemma neg_f_apply (f : C ⟶ D) (i : ι) : (-f).f i = -(f.f i) := rfl @[simp] lemma sub_f_apply (f g : C ⟶ D) (i : ι) : (f - g).f i = f.f i - g.f i := rfl /- TODO(jmc/Scott): the instance below doesn't have the correct defeq for `nsmul` and `gsmul`. We should generalize `function.injective.add_comm_group` and friends. For the `R`-linear version, it will be very convenient to have a good definition of `nsmul` and `gsmul` that matches `smul`. -/ instance : add_comm_group (C ⟶ D) := function.injective.add_comm_group hom.f homological_complex.hom_f_injective (by tidy) (by tidy) (by tidy) (by tidy) instance : preadditive (homological_complex V c) := {} /-- The `i`-th component of a chain map, as an additive map from chain maps to morphisms. -/ @[simps] def hom.f_add_monoid_hom {C₁ C₂ : homological_complex V c} (i : ι) : (C₁ ⟶ C₂) →+ (C₁.X i ⟶ C₂.X i) := add_monoid_hom.mk' (λ f, hom.f f i) (λ _ _, rfl) end homological_complex namespace homological_complex instance eval_additive (i : ι) : (eval V c i).additive := {} variables [has_zero_object V] instance cycles_additive [has_equalizers V] : (cycles_functor V c i).additive := {} variables [has_images V] [has_image_maps V] instance boundaries_additive : (boundaries_functor V c i).additive := {} variables [has_equalizers V] [has_cokernels V] instance homology_additive : (homology_functor V c i).additive := { map_zero' := λ C D, begin dsimp [homology_functor], ext, simp only [limits.cokernel.π_desc, limits.comp_zero, homology.π_map], convert zero_comp, ext, simp, end, map_add' := λ C D f g, begin dsimp [homology_functor], ext, simp only [homology.π_map, preadditive.comp_add, ←preadditive.add_comp], congr, ext, simp, end } end homological_complex namespace category_theory variables {W : Type*} [category W] [preadditive W] /-- An additive functor induces a functor between homological complexes. This is sometimes called the "prolongation". -/ @[simps] def functor.map_homological_complex (F : V ⥤ W) [F.additive] (c : complex_shape ι) : homological_complex V c ⥤ homological_complex W c := { obj := λ C, { X := λ i, F.obj (C.X i), d := λ i j, F.map (C.d i j), shape' := λ i j w, by rw [C.shape _ _ w, F.map_zero], d_comp_d' := λ i j k _ _, by rw [←F.map_comp, C.d_comp_d, F.map_zero], }, map := λ C D f, { f := λ i, F.map (f.f i), comm' := λ i j h, by { dsimp, rw [←F.map_comp, ←F.map_comp, f.comm], }, }, }. instance functor.map_homogical_complex_additive (F : V ⥤ W) [F.additive] (c : complex_shape ι) : (F.map_homological_complex c).additive := {} /-- A natural transformation between functors induces a natural transformation between those functors applied to homological complexes. -/ @[simps] def nat_trans.map_homological_complex {F G : V ⥤ W} [F.additive] [G.additive] (α : F ⟶ G) (c : complex_shape ι) : F.map_homological_complex c ⟶ G.map_homological_complex c := { app := λ C, { f := λ i, α.app _, }, } @[simp] lemma nat_trans.map_homological_complex_id (c : complex_shape ι) (F : V ⥤ W) [F.additive] : nat_trans.map_homological_complex (𝟙 F) c = 𝟙 (F.map_homological_complex c) := by tidy @[simp] lemma nat_trans.map_homological_complex_comp (c : complex_shape ι) {F G H : V ⥤ W} [F.additive] [G.additive] [H.additive] (α : F ⟶ G) (β : G ⟶ H): nat_trans.map_homological_complex (α ≫ β) c = nat_trans.map_homological_complex α c ≫ nat_trans.map_homological_complex β c := by tidy @[simp, reassoc] lemma nat_trans.map_homological_complex_naturality {c : complex_shape ι} {F G : V ⥤ W} [F.additive] [G.additive] (α : F ⟶ G) {C D : homological_complex V c} (f : C ⟶ D) : (F.map_homological_complex c).map f ≫ (nat_trans.map_homological_complex α c).app D = (nat_trans.map_homological_complex α c).app C ≫ (G.map_homological_complex c).map f := by tidy end category_theory variables [has_zero_object V] {W : Type*} [category W] [preadditive W] [has_zero_object W] namespace homological_complex /-- Turning an object into a complex supported at `j` then applying a functor is the same as applying the functor then forming the complex. -/ def single_map_homological_complex (F : V ⥤ W) [F.additive] (c : complex_shape ι) (j : ι): single V c j ⋙ F.map_homological_complex _ ≅ F ⋙ single W c j := nat_iso.of_components (λ X, { hom := { f := λ i, if h : i = j then eq_to_hom (by simp [h]) else 0, }, inv := { f := λ i, if h : i = j then eq_to_hom (by simp [h]) else 0, }, hom_inv_id' := begin ext i, dsimp, split_ifs with h, { simp [h] }, { rw [zero_comp, if_neg h], exact (zero_of_source_iso_zero _ F.map_zero_object).symm, }, end, inv_hom_id' := begin ext i, dsimp, split_ifs with h, { simp [h] }, { rw [zero_comp, if_neg h], simp, }, end, }) (λ X Y f, begin ext i, dsimp, split_ifs with h; simp [h], end). variables (F : V ⥤ W) [functor.additive F] (c) @[simp] lemma single_map_homological_complex_hom_app_self (j : ι) (X : V) : ((single_map_homological_complex F c j).hom.app X).f j = eq_to_hom (by simp) := by simp [single_map_homological_complex] @[simp] lemma single_map_homological_complex_hom_app_ne {i j : ι} (h : i ≠ j) (X : V) : ((single_map_homological_complex F c j).hom.app X).f i = 0 := by simp [single_map_homological_complex, h] @[simp] lemma single_map_homological_complex_inv_app_self (j : ι) (X : V) : ((single_map_homological_complex F c j).inv.app X).f j = eq_to_hom (by simp) := by simp [single_map_homological_complex] @[simp] lemma single_map_homological_complex_inv_app_ne {i j : ι} (h : i ≠ j) (X : V): ((single_map_homological_complex F c j).inv.app X).f i = 0 := by simp [single_map_homological_complex, h] end homological_complex namespace chain_complex -- TODO: dualize to cochain complexes /-- Turning an object into a chain complex supported at zero then applying a functor is the same as applying the functor then forming the complex. -/ def single₀_map_homological_complex (F : V ⥤ W) [F.additive] : single₀ V ⋙ F.map_homological_complex _ ≅ F ⋙ single₀ W := nat_iso.of_components (λ X, { hom := { f := λ i, match i with | 0 := 𝟙 _ | (i+1) := F.map_zero_object.hom end, }, inv := { f := λ i, match i with | 0 := 𝟙 _ | (i+1) := F.map_zero_object.inv end, }, hom_inv_id' := begin ext (_|i), { unfold_aux, simp, }, { unfold_aux, dsimp, simp only [comp_f, id_f, zero_comp], exact (zero_of_source_iso_zero _ F.map_zero_object).symm, } end, inv_hom_id' := by { ext (_|i); { unfold_aux, dsimp, simp, }, }, }) (λ X Y f, by { ext (_|i); { unfold_aux, dsimp, simp, }, }). @[simp] lemma single₀_map_homological_complex_hom_app_zero (F : V ⥤ W) [F.additive] (X : V) : ((single₀_map_homological_complex F).hom.app X).f 0 = 𝟙 _ := rfl @[simp] lemma single₀_map_homological_complex_hom_app_succ (F : V ⥤ W) [F.additive] (X : V) (n : ℕ) : ((single₀_map_homological_complex F).hom.app X).f (n+1) = 0 := rfl @[simp] lemma single₀_map_homological_complex_inv_app_zero (F : V ⥤ W) [F.additive] (X : V) : ((single₀_map_homological_complex F).inv.app X).f 0 = 𝟙 _ := rfl @[simp] lemma single₀_map_homological_complex_inv_app_succ (F : V ⥤ W) [F.additive] (X : V) (n : ℕ) : ((single₀_map_homological_complex F).inv.app X).f (n+1) = 0 := rfl end chain_complex
50305d9ca023b7ea223f011e4725ff3d1e2068a2
96e44fc78cabfc9d646dc37d0e756189b6b79181
/library/init/meta/tactic.lean
d4803e27b54bcdd9f99b39fb6a5f011c65923364
[ "Apache-2.0" ]
permissive
TwoFX/lean
23c73c10a340f5a381f6abf27a27f53f1fb7e2e3
7e3f336714055869690b7309b6bb651fbc67e76e
refs/heads/master
1,612,504,908,183
1,594,641,622,000
1,594,641,622,000
243,750,847
0
0
Apache-2.0
1,582,890,661,000
1,582,890,661,000
null
UTF-8
Lean
false
false
72,322
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.function init.data.option.basic init.util import init.control.combinators init.control.monad init.control.alternative init.control.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad open native meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) /-- Cause the tactic to fail with no error message. -/ meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ meta class executor (m : Type → Type u) [monad m] := (config_type : Type) [inhabited : inhabited config_type] (execute_with : config_type → m unit → tactic unit) attribute [inline] executor.execute_with @[inline] meta def executor.execute_explicit (m : Type → Type u) [monad m] [e : executor m] : m unit → tactic unit := executor.execute_with e.inhabited.default @[inline] meta def executor.execute_with_explicit (m : Type → Type u) [monad m] [executor m] : executor.config_type m → m unit → tactic unit := executor.execute_with /-- Default `executor` instance for `tactic`s themselves -/ meta instance : executor tactic := { config_type := unit, inhabited := ⟨()⟩, execute_with := λ _, id } end interactive namespace tactic open interaction_monad.result variables {α : Type u} /-- Does nothing. -/ meta def skip : tactic unit := success () /-- `try_core t` acts like `t`, but succeeds even if `t` fails. It returns the result of `t` if `t` succeeded and `none` otherwise. -/ meta def try_core (t : tactic α) : tactic (option α) := λ s, match t s with | (exception _ _ _) := success none s | (success a s') := success (some a) s' end /-- `try t` acts like `t`, but succeeds even if `t` fails. -/ meta def try (t : tactic α) : tactic unit := λ s, match t s with | (exception _ _ _) := success () s | (success _ s') := success () s' end meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | success _ s' := try (try_lst tacs) s' | exception e p s' := match try_lst tacs s' with | exception _ _ _ := exception e p s' | r := r end end /-- `fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, match (t s) with | (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end /-- `success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end open nat /-- `iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the result of each successful iteration. -/ meta def iterate_at_most : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do (some a) ← try_core t | pure [], as ← iterate_at_most n t, pure $ a :: as /-- `iterate_at_most' n t` repeats `t` `n` times or until `t` fails. -/ meta def iterate_at_most' : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do (some _) ← try_core t | skip, iterate_at_most' n t /-- `iterate_exactly n t` iterates `t` `n` times, returning the result of each iteration. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do a ← t, as ← iterate_exactly n t, pure $ a ::as /-- `iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly' : nat → tactic unit → tactic unit | 0 t := skip | (n + 1) t := t *> iterate_exactly' n t /-- `iterate t` repeats `t` 100.000 times or until `t` fails, returning the result of each iteration. -/ meta def iterate : tactic α → tactic (list α) := iterate_at_most 100000 /-- `iterate' t` repeats `t` 100.000 times or until `t` fails. -/ meta def iterate' : tactic unit → tactic unit := iterate_at_most' 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg. -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) /-- Set the tactic_state. -/ @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' /-- Get the tactic_state. -/ @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨λ l, to_fmt <$> l.mmap pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta constant get_trace_msg_pos : tactic pos meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant head_zeta : expr → tactic expr /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr /-- Get the `local_const` expr for the given `name`. -/ meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ meta constant rotate_left : nat → tactic unit /-- Gets a list of metavariables, one for each goal. -/ meta constant get_goals : tactic (list expr) /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ meta constant set_goals : list expr → tactic unit /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ meta constant mk_fresh_name : tactic name /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. Note: There is one "new hypothesis" for every constructor argument. These are usually local constants, but due to dependent pattern matching, they can also be arbitrary terms. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ meta constant set_env_core : environment → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- `doc_string env d k` returns the doc string for `d` (if available) -/ meta constant doc_string : name → tactic string /-- Set the docstring for the given declaration. -/ meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ meta constant olean_doc_strings : tactic (list (option string × (list (pos × string)))) /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ meta def module_doc_strings : tactic (list (option name × string)) := do /- Obtain a list of top-level docs in current module. -/ mod_docs ← olean_doc_strings, let mod_docs: list (list (option name × string)) := mod_docs.filter_map (λ d, if d.1.is_none then some (d.2.map (λ pos_doc, ⟨none, pos_doc.2⟩)) else none), let mod_docs := mod_docs.join, /- Obtain list of declarations in current module. -/ e ← get_env, let decls := environment.fold e ([]: list name) (λ d acc, let n := d.to_name in if (environment.decl_olean e n).is_none then n::acc else acc), /- Map declarations to those which have docstrings. -/ decls ← decls.mfoldl (λa n, (doc_string n >>= λ doc, pure $ (some n, doc) :: a) <|> pure a) [], pure (mod_docs ++ decls) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority and whether or not the attribute is persistent. -/ meta constant has_attribute : name → name → tactic (bool × nat) /-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/ meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit := try $ do (p', prio) ← has_attribute attr_name src, let p := p.get_or_else p', set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag : Type := list name /-- Enable/disable goal tagging. -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag /-- By default, Lean only considers local instances in the header of declarations. This has two main benefits. 1- Results produced by the type class resolution procedure can be easily cached. 2- The set of local instances does not have to be recomputed. This approach has the following disadvantages: 1- Frozen local instances cannot be reverted. 2- Local instances defined inside of a declaration are not considered during type class resolution. This tactic resets the set of local instances. After executing this tactic, the set of local instances will be recomputed and the cache will be frequently reset. Note that, the cache is still used when executing a single tactic that may generate many type class resolution problems (e.g., `simp`). -/ meta constant unfreeze_local_instances : tactic unit /-- Freeze the current set of local instances. -/ meta constant freeze_local_instances : tactic unit /- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/ meta constant frozen_local_instances : tactic (option (list expr)) meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. The tactic does not check whether `e` is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/ meta def unsafe_change (e : expr) : tactic unit := change e ff /-- Pi or elet introduction. Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`. Returns the new local constant. Similarly for `elet` expressions. If the target is not a Pi or elet it will try to put it in WHNF. -/ meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n /-- Like `intro` except the name is derived from the bound name in the Π. -/ meta def intro1 : tactic expr := intro `_ /-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction.-/ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end /-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/ meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies. -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- `intron' n` introduces `n` hypotheses and returns the resulting local constants. Fails if there are not at least `n` arguments to introduce. If you do not need the return value, use `intron`. -/ meta def intron' : ℕ → tactic (list expr) | 0 := pure [] | (n + 1) := do h ← intro1, hs ← intron' n, pure $ h :: hs /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q /-- Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta def revert (l : expr) : tactic nat := revert_lst [l] /- Revert "all" hypotheses. Actually, the tactic only reverts hypotheses occurring after the last frozen local instance. Recall that frozen local instances cannot be reverted. We can use `unfreeze_local_instances` to workaround this limitation. -/ meta def revert_all : tactic nat := do lctx ← local_context, lis ← frozen_local_instances, match lis with | none := revert_lst lctx | some [] := revert_lst lctx /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/ | some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) [] end meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. [NOTE] We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) /-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/ meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 {α} (tac : tactic α) : tactic α := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], a ← tac, gs' ← get_goals, match gs' with | [] := set_goals rs >> pure a | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve {α} (ts : list (tactic α)) : tactic α := first $ map solve1 ts private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α) | [] [] rs := set_goals rs *> pure [] | (t::ts) [] rs := fail "focus' tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus' tactic failed, insufficient number of tactics", a ← t, rs' ← get_goals, as ← focus_aux ts gs (rs ++ rs'), pure $ a :: as /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. Returns the results of t_i (one per goal). -/ meta def focus {α} (ts : list (tactic α)) : tactic (list α) := do gs ← get_goals, focus_aux ts gs [] private meta def focus'_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus'_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus'_aux ts gs (rs ++ rs') /-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus' (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus'_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core {α} (tac : tactic α) : list expr → list expr → tactic (list α) | [] ac := set_goals ac *> pure [] | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], a ← tac, new_gs ← get_goals, as ← all_goals_core gs (ac ++ new_gs), pure $ a :: as /-- Apply the given tactic to all goals. Return one result per goal. -/ meta def all_goals {α} (tac : tactic α) : tactic (list α) := do gs ← get_goals, all_goals_core tac gs [] private meta def all_goals'_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals'_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals'_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals'_core tac gs [] private meta def any_goals_core {α} (tac : tactic α) : list expr → list expr → bool → tactic (list (option α)) | [] ac progress := guard progress *> set_goals ac *> pure [] | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], res ← try_core tac, new_gs ← get_goals, ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress), pure $ res :: ress /-- Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac` succeeds for at least one goal. The returned list contains the result of `tac` for each goal: `some a` if tac succeeded, or `none` if it did not. -/ meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) := do gs ← get_goals, any_goals_core tac gs [] ff private meta def any_goals'_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals'_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals'_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies `tac2` to each goal produced by `tac1`. -/ meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← all_goals $ tac2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq' (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals' tac2, gs' ← get_goals, set_goals (gs' ++ gs) /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus'`). -/ meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← focus $ tacs2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus`). -/ meta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq'⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus'⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r /-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} /-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit := do c ← mk_const c, apply c cfg, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute [instance] classical.prop_decidable' is used, all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Postprocess the output of `cases_core`: - The third component of each tuple in the input list (the list of substitutions) is dropped since we don't use it anywhere. - The second component (the list of new hypotheses) is filtered: any expression that is not a local constant is dropped. We only use the new hypotheses for the renaming functionality of `case`, so we want to keep only those "new hypotheses" that are, in fact, local constants. -/ private meta def cases_postprocess (hs : list (name × list expr × list (name × expr))) : list (name × list expr) := hs.map $ λ ⟨n, hs, _⟩, (n, hs.filter (λ h, h.is_local_constant)) /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal and the newly introduced hypotheses. Note that while `cases_core` may return "new hypotheses" that are not local constants, this tactic only returns local constants. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) := if e.is_local_constant then do r ← cases_core e ids md, return $ cases_postprocess r else do n ← revert_kdependencies e dmd, x ← get_unused_name, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 $ do r ← cases_core h ids md, hs' ← all_goals (intron' n), return $ cases_postprocess $ r.map₂ (λ ⟨n, hs, x⟩ hs', (n, hs ++ hs', x)) hs' /-- The same as `exact` except you can add proof holes. -/ meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq' (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs | pure `_, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) /-- add declaration `d` as a protected declaration -/ meta def add_protected_decl (d : declaration) : tactic unit := updateex_env $ λ e, e.add_protected d /-- check if `n` is the name of a protected declaration -/ meta def is_protected_decl (n : name) : tactic bool := do env ← get_env, return $ env.is_protected n /-- `add_defn_equations` adds a definition specified by a list of equations. The arguments: * `lp`: list of universe parameters * `params`: list of parameters (binders before the colon); * `fn`: a local constant giving the name and type of the declaration (with `params` in the local context); * `eqns`: a list of equations, each of which is a list of patterns (constructors applied to new local constants) and the branch expression; * `is_meta`: is the definition meta? `add_defn_equations` can be used as: do my_add ← mk_local_def `my_add `(ℕ → ℕ), a ← mk_local_def `a ℕ, b ← mk_local_def `b ℕ, add_defn_equations [a] my_add [ ([``(nat.zero)], a), ([``(nat.succ %%b)], my_add b) ]) ff -- non-meta to create the following definition: def my_add (a : ℕ) : ℕ → ℕ | nat.zero := a | (nat.succ b) := my_add b -/ meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr) (eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit := do opt ← get_options, updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. If `use_unique_names` is true, the keys of `name_map` should be the unique names of hypotheses to be renamed. Otherwise, the keys should be display names. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. If `use_unique_names` is false and there are multiple hypotheses with the same display name in the context, they are all renamed. -/ meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff) : tactic unit := do let hyp_name : expr → name := if use_unique_names then expr.local_uniq_name else expr.local_pp_name, ctx ← revertible_local_context, -- The part of the context after (but including) the first hypthesis that -- must be renamed. let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none), when strict $ do { let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.join $ (invalid_renames.map to_fmt).intersperse ", " , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ] }, -- The new names for all hypotheses in ctx_suffix. let new_names := ctx_suffix.map $ λ h, (renames.find $ hyp_name h).get_or_else h.local_pp_name, revert_lst ctx_suffix, intro_lst new_names, pure () /-- Rename a local hypothesis. This is a special case of `rename_many`; see there for caveats. -/ meta def rename (curr : name) (new : name) : tactic unit := rename_many (rb_map.of_list [⟨curr, new⟩]) /-- Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does not preserve the order of hypotheses. Its implementation is simpler (and therefore probably faster) than that of `rename`. -/ meta def rename_unstable (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ /-- Try to prove with `iff.refl`.-/ meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact meta def eval_pexpr (α) [reflected α] (e : pexpr) : tactic α := to_expr ``(%%e : %%(reflect α)) ff ff >>= eval_expr α meta def run_simple {α} : tactic_state → tactic α → option α | ts t := match t ts with | (interaction_monad.result.success a ts') := some a | (interaction_monad.result.exception _ _ _) := none end end tactic
f8f858a233214742bb95ba81edc63a3a221f40b7
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/perfection.lean
1555bfd49b631d7f06ad2da26d6836ad6b064853
[ "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
24,280
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p import algebra.ring.pi import analysis.special_functions.pow import field_theory.perfect_closure import ring_theory.localization import ring_theory.subring import ring_theory.valuation.integers /-! # Ring Perfection and Tilt In this file we define the perfection of a ring of characteristic p, and the tilt of a field given a valuation to `ℝ≥0`. ## TODO Define the valuation on the tilt, and define a characteristic predicate for the tilt. -/ universes u₁ u₂ u₃ u₄ open_locale nnreal /-- The perfection of a monoid `M`, defined to be the projective limit of `M` using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as `{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/ def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) := { carrier := { f | ∀ n, f (n + 1) ^ p = f n }, one_mem' := λ n, one_pow _, mul_mem' := λ f g hf hg n, (mul_pow _ _ _).trans $ congr_arg2 _ (hf n) (hg n) } /-- The perfection of a ring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subsemiring (ℕ → R) := { zero_mem' := λ n, zero_pow $ hp.1.pos, add_mem' := λ f g hf hg n, (frobenius_add R p _ _).trans $ congr_arg2 _ (hf n) (hg n), .. monoid.perfection R p } namespace perfection variables (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] include hp /-- The `n`-th coefficient of an element of the perfection. -/ def coeff (n : ℕ) : ring.perfection R p →+* R := { to_fun := λ f, f.1 n, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[ext] lemma ext {f g : ring.perfection R p} (h : ∀ n, coeff R p n f = coeff R p n g) : f = g := subtype.eq $ funext h variables (R p) /-- The `p`-th root of an element of the perfection. -/ def pth_root : ring.perfection R p →+* ring.perfection R p := { to_fun := λ f, ⟨λ n, coeff R p (n + 1) f, λ n, f.2 _⟩, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[simp] lemma coeff_mk (f : ℕ → R) (hf) (n : ℕ) : coeff R p n ⟨f, hf⟩ = f n := rfl lemma coeff_pth_root (f : ring.perfection R p) (n : ℕ) : coeff R p n (pth_root R p f) = coeff R p (n + 1) f := rfl lemma coeff_pow_p (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (f ^ p) = coeff R p n f := by { rw ring_hom.map_pow, exact f.2 n } lemma coeff_pow_p' (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) f ^ p = coeff R p n f := f.2 n lemma coeff_frobenius (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (frobenius _ p f) = coeff R p n f := by apply coeff_pow_p f n -- `coeff_pow_p f n` also works but is slow! lemma coeff_iterate_frobenius (f : ring.perfection R p) (n m : ℕ) : coeff R p (n + m) (frobenius _ p ^[m] f) = coeff R p n f := nat.rec_on m rfl $ λ m ih, by erw [function.iterate_succ_apply', coeff_frobenius, ih] lemma coeff_iterate_frobenius' (f : ring.perfection R p) (n m : ℕ) (hmn : m ≤ n) : coeff R p n (frobenius _ p ^[m] f) = coeff R p (n - m) f := eq.symm $ (coeff_iterate_frobenius _ _ m).symm.trans $ (nat.sub_add_cancel hmn).symm ▸ rfl lemma pth_root_frobenius : (pth_root R p).comp (frobenius _ p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, coeff_pth_root, coeff_frobenius] lemma frobenius_pth_root : (frobenius _ p).comp (pth_root R p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, ring_hom.map_frobenius, coeff_pth_root, ← ring_hom.map_frobenius, coeff_frobenius] lemma coeff_add_ne_zero {f : ring.perfection R p} {n : ℕ} (hfn : coeff R p n f ≠ 0) (k : ℕ) : coeff R p (n + k) f ≠ 0 := nat.rec_on k hfn $ λ k ih h, ih $ by erw [← coeff_pow_p, ring_hom.map_pow, h, zero_pow hp.1.pos] lemma coeff_ne_zero_of_le {f : ring.perfection R p} {m n : ℕ} (hfm : coeff R p m f ≠ 0) (hmn : m ≤ n) : coeff R p n f ≠ 0 := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in hk.symm ▸ coeff_add_ne_zero hfm k variables (R p) instance perfect_ring : perfect_ring (ring.perfection R p) p := { pth_root' := pth_root R p, frobenius_pth_root' := congr_fun $ congr_arg ring_hom.to_fun $ @frobenius_pth_root R _ p _ _, pth_root_frobenius' := congr_fun $ congr_arg ring_hom.to_fun $ @pth_root_frobenius R _ p _ _ } instance ring (R : Type u₁) [comm_ring R] [char_p R p] : ring (ring.perfection R p) := ((ring.perfection R p).to_subring $ λ n, by simp_rw [← frobenius_def, pi.neg_apply, pi.one_apply, ring_hom.map_neg, ring_hom.map_one]).to_ring instance comm_ring (R : Type u₁) [comm_ring R] [char_p R p] : comm_ring (ring.perfection R p) := ((ring.perfection R p).to_subring $ λ n, by simp_rw [← frobenius_def, pi.neg_apply, pi.one_apply, ring_hom.map_neg, ring_hom.map_one]).to_comm_ring /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* perfection S p`. -/ @[simps] def lift (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] : (R →+* S) ≃ (R →+* ring.perfection S p) := { to_fun := λ f, { to_fun := λ r, ⟨λ n, f $ _root_.pth_root R p ^[n] r, λ n, by rw [← f.map_pow, function.iterate_succ_apply', pth_root_pow_p]⟩, map_one' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_one _ _).trans f.map_one, map_mul' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_mul _ _ _ _).trans $ f.map_mul _ _, map_zero' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_zero _ _).trans f.map_zero, map_add' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_add _ _ _ _).trans $ f.map_add _ _ }, inv_fun := ring_hom.comp $ coeff S p 0, left_inv := λ f, ring_hom.ext $ λ r, rfl, right_inv := λ f, ring_hom.ext $ λ r, ext $ λ n, show coeff S p 0 (f (_root_.pth_root R p ^[n] r)) = coeff S p n (f r), by rw [← coeff_iterate_frobenius _ 0 n, zero_add, ← ring_hom.map_iterate_frobenius, right_inverse_pth_root_frobenius.iterate] } lemma hom_ext {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {f g : R →+* ring.perfection S p} (hfg : ∀ x, coeff S p 0 (f x) = coeff S p 0 (g x)) : f = g := (lift p R S).symm.injective $ ring_hom.ext hfg variables {R} {S : Type u₂} [comm_semiring S] [char_p S p] /-- A ring homomorphism `R →+* S` induces `perfection R p →+* perfection S p` -/ @[simps] def map (φ : R →+* S) : ring.perfection R p →+* ring.perfection S p := { to_fun := λ f, ⟨λ n, φ (coeff R p n f), λ n, by rw [← φ.map_pow, coeff_pow_p']⟩, map_one' := subtype.eq $ funext $ λ n, φ.map_one, map_mul' := λ f g, subtype.eq $ funext $ λ n, φ.map_mul _ _, map_zero' := subtype.eq $ funext $ λ n, φ.map_zero, map_add' := λ f g, subtype.eq $ funext $ λ n, φ.map_add _ _ } lemma coeff_map (φ : R →+* S) (f : ring.perfection R p) (n : ℕ) : coeff S p n (map p φ f) = φ (coeff R p n f) := rfl end perfection /-- A perfection map to a ring of characteristic `p` is a map that is isomorphic to its perfection. -/ @[nolint has_inhabited_instance] structure perfection_map (p : ℕ) [fact p.prime] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₂} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* R) : Prop := (injective : ∀ ⦃x y : P⦄, (∀ n, π (pth_root P p ^[n] x) = π (pth_root P p ^[n] y)) → x = y) (surjective : ∀ f : ℕ → R, (∀ n, f (n + 1) ^ p = f n) → ∃ x : P, ∀ n, π (pth_root P p ^[n] x) = f n) namespace perfection_map variables {p : ℕ} [fact p.prime] variables {R : Type u₁} [comm_semiring R] [char_p R p] variables {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] /-- Create a `perfection_map` from an isomorphism to the perfection. -/ @[simps] lemma mk' {f : P →+* R} (g : P ≃+* ring.perfection R p) (hfg : perfection.lift p P R f = g) : perfection_map p f := { injective := λ x y hxy, g.injective $ (ring_hom.ext_iff.1 hfg x).symm.trans $ eq.symm $ (ring_hom.ext_iff.1 hfg y).symm.trans $ perfection.ext $ λ n, (hxy n).symm, surjective := λ y hy, let ⟨x, hx⟩ := g.surjective ⟨y, hy⟩ in ⟨x, λ n, show perfection.coeff R p n (perfection.lift p P R f x) = perfection.coeff R p n ⟨y, hy⟩, by rw [hfg, ← coe_fn_coe_base, hx]⟩ } variables (p R P) /-- The canonical perfection map from the perfection of a ring. -/ lemma of : perfection_map p (perfection.coeff R p 0) := mk' (ring_equiv.refl _) $ (equiv.apply_eq_iff_eq_symm_apply _).2 rfl /-- For a perfect ring, it itself is the perfection. -/ lemma id [perfect_ring R p] : perfection_map p (ring_hom.id R) := { injective := λ x y hxy, hxy 0, surjective := λ f hf, ⟨f 0, λ n, show pth_root R p ^[n] (f 0) = f n, from nat.rec_on n rfl $ λ n ih, injective_pow_p p $ by rw [function.iterate_succ_apply', pth_root_pow_p _, ih, hf]⟩ } variables {p R P} /-- A perfection map induces an isomorphism to the prefection. -/ noncomputable def equiv {π : P →+* R} (m : perfection_map p π) : P ≃+* ring.perfection R p := ring_equiv.of_bijective (perfection.lift p P R π) ⟨λ x y hxy, m.injective $ λ n, (congr_arg (perfection.coeff R p n) hxy : _), λ f, let ⟨x, hx⟩ := m.surjective f.1 f.2 in ⟨x, perfection.ext $ hx⟩⟩ lemma equiv_apply {π : P →+* R} (m : perfection_map p π) (x : P) : m.equiv x = perfection.lift p P R π x := rfl lemma comp_equiv {π : P →+* R} (m : perfection_map p π) (x : P) : perfection.coeff R p 0 (m.equiv x) = π x := rfl lemma comp_equiv' {π : P →+* R} (m : perfection_map p π) : (perfection.coeff R p 0).comp ↑m.equiv = π := ring_hom.ext $ λ x, rfl lemma comp_symm_equiv {π : P →+* R} (m : perfection_map p π) (f : ring.perfection R p) : π (m.equiv.symm f) = perfection.coeff R p 0 f := (m.comp_equiv _).symm.trans $ congr_arg _ $ m.equiv.apply_symm_apply f lemma comp_symm_equiv' {π : P →+* R} (m : perfection_map p π) : π.comp ↑m.equiv.symm = perfection.coeff R p 0 := ring_hom.ext m.comp_symm_equiv variables (p R P) /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`, where `P` is any perfection of `S`. -/ @[simps] noncomputable def lift [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (P : Type u₃) [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) : (R →+* S) ≃ (R →+* P) := { to_fun := λ f, ring_hom.comp ↑m.equiv.symm $ perfection.lift p R S f, inv_fun := λ f, π.comp f, left_inv := λ f, by { simp_rw [← ring_hom.comp_assoc, comp_symm_equiv'], exact (perfection.lift p R S).symm_apply_apply f }, right_inv := λ f, ring_hom.ext $ λ x, m.equiv.injective $ (m.equiv.apply_symm_apply _).trans $ show perfection.lift p R S (π.comp f) x = ring_hom.comp ↑m.equiv f x, from ring_hom.ext_iff.1 ((perfection.lift p R S).apply_eq_iff_eq_symm_apply.2 rfl) _ } variables {R p} lemma hom_ext [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) {f g : R →+* P} (hfg : ∀ x, π (f x) = π (g x)) : f = g := (lift p R S P π m).symm.injective $ ring_hom.ext hfg variables {R P} (p) {S : Type u₂} [comm_semiring S] [char_p S p] variables {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] /-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections. -/ @[nolint unused_arguments] noncomputable def map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : P →+* Q := lift p P S Q σ n $ φ.comp π lemma comp_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : σ.comp (map p m n φ) = φ.comp π := (lift p P S Q σ n).symm_apply_apply _ lemma map_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) (x : P) : σ (map p m n φ x) = φ (π x) := ring_hom.ext_iff.1 (comp_map p m n φ) x -- Why is this slow? lemma map_eq_map (φ : R →+* S) : @map p _ R _ _ _ _ _ _ S _ _ _ _ _ _ _ (of p R) _ (of p S) φ = perfection.map p φ := hom_ext _ (of p S) $ λ f, by rw [map_map, perfection.coeff_map] end perfection_map section perfectoid variables (K : Type u₁) [field K] (v : valuation K ℝ≥0) variables (O : Type u₂) [comm_ring O] [algebra O K] (hv : v.integers O) variables (p : ℕ) include hv /-- `O/(p)` for `O`, ring of integers of `K`. -/ @[nolint unused_arguments has_inhabited_instance] def mod_p := (ideal.span {p} : ideal O).quotient variables [hp : fact p.prime] [hvp : fact (v p ≠ 1)] namespace mod_p instance : comm_ring (mod_p K v O hv p) := ideal.quotient.comm_ring _ include hp hvp instance : char_p (mod_p K v O hv p) p := char_p.quotient O p $ mt hv.one_of_is_unit $ ((algebra_map O K).map_nat_cast p).symm ▸ hvp.1 instance : nontrivial (mod_p K v O hv p) := char_p.nontrivial_of_char_ne_one hp.1.ne_one section classical local attribute [instance] classical.dec omit hp hvp /-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`, a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/ noncomputable def pre_val (x : mod_p K v O hv p) : ℝ≥0 := if x = 0 then 0 else v (algebra_map O K x.out') variables {K v O hv p} lemma pre_val_mk {x : O} (hx : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0) : pre_val K v O hv p (ideal.quotient.mk _ x) = v (algebra_map O K x) := begin obtain ⟨r, hr⟩ := ideal.mem_span_singleton'.1 (ideal.quotient.eq.1 $ quotient.sound' $ @quotient.mk_out' O (ideal.span {p} : ideal O).quotient_rel x), refine (if_neg hx).trans (v.map_eq_of_sub_lt $ lt_of_not_ge' _), erw [← ring_hom.map_sub, ← hr, hv.le_iff_dvd], exact λ hprx, hx (ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ dvd_of_mul_left_dvd hprx), end lemma pre_val_zero : pre_val K v O hv p 0 = 0 := if_pos rfl lemma pre_val_mul {x y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) : pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y := begin have hx0 : x ≠ 0 := mt (by { rintro rfl, rw zero_mul }) hxy0, have hy0 : y ≠ 0 := mt (by { rintro rfl, rw mul_zero }) hxy0, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_mul at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_mul, v.map_mul] end lemma pre_val_add (x y : mod_p K v O hv p) : pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) := begin by_cases hx0 : x = 0, { rw [hx0, zero_add], exact le_max_right _ _ }, by_cases hy0 : y = 0, { rw [hy0, add_zero], exact le_max_left _ _ }, by_cases hxy0 : x + y = 0, { rw [hxy0, pre_val_zero], exact zero_le _ }, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_add at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_add], exact v.map_add _ _ end lemma v_p_lt_pre_val {x : mod_p K v O hv p} : v p < pre_val K v O hv p x ↔ x ≠ 0 := begin refine ⟨λ h hx, by { rw [hx, pre_val_zero] at h, exact not_lt_zero' h }, λ h, lt_of_not_ge' $ λ hp, h _⟩, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, rw [pre_val_mk h, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd] at hp, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton], exact hp end lemma pre_val_eq_zero {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 := ⟨λ hvx, classical.by_contradiction $ λ hx0 : x ≠ 0, by { rw [← v_p_lt_pre_val, hvx] at hx0, exact not_lt_zero' hx0 }, λ hx, hx.symm ▸ pre_val_zero⟩ variables (hv hvp) lemma v_p_lt_val {x : O} : v p < v (algebra_map O K x) ↔ (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := by rw [lt_iff_not_ge', not_iff_not, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd, ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton] open nnreal variables {hv} [hvp] include hp lemma mul_ne_zero_of_pow_p_ne_zero {x y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := begin obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, have h1p : (0 : ℝ) < 1 / p := one_div_pos.2 (nat.cast_pos.2 hp.1.pos), rw ← ring_hom.map_mul, rw ← ring_hom.map_pow at hx hy, rw ← v_p_lt_val hv at hx hy ⊢, rw [ring_hom.map_pow, v.map_pow, ← rpow_lt_rpow_iff h1p, ← rpow_nat_cast, ← rpow_mul, mul_one_div_cancel (nat.cast_ne_zero.2 hp.1.ne_zero : (p : ℝ) ≠ 0), rpow_one] at hx hy, rw [ring_hom.map_mul, v.map_mul], refine lt_of_le_of_lt _ (mul_lt_mul'''' hx hy), by_cases hvp : v p = 0, { rw hvp, exact zero_le _ }, replace hvp := zero_lt_iff.2 hvp, conv_lhs { rw ← rpow_one (v p) }, rw ← rpow_add (ne_of_gt hvp), refine rpow_le_rpow_of_exponent_ge hvp ((algebra_map O K).map_nat_cast p ▸ hv.2 _) _, rw [← add_div, div_le_one (nat.cast_pos.2 hp.1.pos : 0 < (p : ℝ))], exact_mod_cast hp.1.two_le end end classical end mod_p include hp hvp /-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/ @[nolint has_inhabited_instance] def pre_tilt := ring.perfection (mod_p K v O hv p) p namespace pre_tilt instance : comm_ring (pre_tilt K v O hv p) := perfection.comm_ring p _ section classical local attribute [instance] classical.dec open perfection /-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val_aux (f : pre_tilt K v O hv p) : ℝ≥0 := if h : ∃ n, coeff _ _ n f ≠ 0 then mod_p.pre_val K v O hv p (coeff _ _ (nat.find h) f) ^ (p ^ nat.find h) else 0 variables {K v O hv p} lemma coeff_nat_find_add_ne_zero {f : pre_tilt K v O hv p} {h : ∃ n, coeff _ _ n f ≠ 0} (k : ℕ) : coeff _ _ (nat.find h + k) f ≠ 0 := coeff_add_ne_zero (nat.find_spec h) k lemma val_aux_eq {f : pre_tilt K v O hv p} {n : ℕ} (hfn : coeff _ _ n f ≠ 0) : val_aux K v O hv p f = mod_p.pre_val K v O hv p (coeff _ _ n f) ^ (p ^ n) := begin have h : ∃ n, coeff _ _ n f ≠ 0 := ⟨n, hfn⟩, rw [val_aux, dif_pos h], obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le (nat.find_min' h hfn), induction k with k ih, { refl }, obtain ⟨x, hx⟩ := ideal.quotient.mk_surjective (coeff _ _ (nat.find h + k + 1) f), have h1 : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := hx.symm ▸ hfn, have h2 : (ideal.quotient.mk _ (x ^ p) : mod_p K v O hv p) ≠ 0, by { erw [ring_hom.map_pow, hx, ← ring_hom.map_pow, coeff_pow_p], exact coeff_nat_find_add_ne_zero k }, erw [ih (coeff_nat_find_add_ne_zero k), ← hx, ← coeff_pow_p, ring_hom.map_pow, ← hx, ← ring_hom.map_pow, mod_p.pre_val_mk h1, mod_p.pre_val_mk h2, ring_hom.map_pow, v.map_pow, ← pow_mul, pow_succ], refl end lemma val_aux_zero : val_aux K v O hv p 0 = 0 := dif_neg $ λ ⟨n, hn⟩, hn rfl lemma val_aux_one : val_aux K v O hv p 1 = 1 := (val_aux_eq $ by exact one_ne_zero).trans $ by { rw [pow_zero, pow_one, ring_hom.map_one, ← (ideal.quotient.mk _).map_one, mod_p.pre_val_mk, ring_hom.map_one, v.map_one], exact @one_ne_zero (mod_p K v O hv p) _ _ } lemma val_aux_mul (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g := begin by_cases hf : f = 0, { rw [hf, zero_mul, val_aux_zero, zero_mul] }, by_cases hg : g = 0, { rw [hg, mul_zero, val_aux_zero, mul_zero] }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, replace hm := coeff_ne_zero_of_le hm (le_max_left m n), replace hn := coeff_ne_zero_of_le hn (le_max_right m n), have hfg : coeff _ _ (max m n + 1) (f * g) ≠ 0, { rw ring_hom.map_mul, refine mod_p.mul_ne_zero_of_pow_p_ne_zero _ _; rw [← ring_hom.map_pow, coeff_pow_p]; assumption }, rw [val_aux_eq (coeff_add_ne_zero hm 1), val_aux_eq (coeff_add_ne_zero hn 1), val_aux_eq hfg], rw ring_hom.map_mul at hfg ⊢, rw [mod_p.pre_val_mul hfg, mul_pow] end lemma val_aux_add (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) := begin by_cases hf : f = 0, { rw [hf, zero_add, val_aux_zero, max_eq_right], exact zero_le _ }, by_cases hg : g = 0, { rw [hg, add_zero, val_aux_zero, max_eq_left], exact zero_le _ }, by_cases hfg : f + g = 0, { rw [hfg, val_aux_zero], exact zero_le _ }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), replace hfg : ∃ n, coeff _ _ n (f + g) ≠ 0 := not_forall.1 (λ h, hfg $ perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, obtain ⟨k, hk⟩ := hfg, replace hm := coeff_ne_zero_of_le hm (le_trans (le_max_left m n) (le_max_left _ k)), replace hn := coeff_ne_zero_of_le hn (le_trans (le_max_right m n) (le_max_left _ k)), replace hk := coeff_ne_zero_of_le hk (le_max_right (max m n) k), rw [val_aux_eq hm, val_aux_eq hn, val_aux_eq hk, ring_hom.map_add], cases le_max_iff.1 (mod_p.pre_val_add (coeff _ _ (max (max m n) k) f) (coeff _ _ (max (max m n) k) g)) with h h, { exact le_max_left_of_le (canonically_ordered_semiring.pow_le_pow_of_le_left h _) }, { exact le_max_right_of_le (canonically_ordered_semiring.pow_le_pow_of_le_left h _) } end variables (K v O hv p) /-- The valuation `Perfection(O/(p)) → ℝ≥0`. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val : valuation (pre_tilt K v O hv p) ℝ≥0 := { to_fun := val_aux K v O hv p, map_one' := val_aux_one, map_mul' := val_aux_mul, map_zero' := val_aux_zero, map_add' := val_aux_add } variables {K v O hv p} lemma map_eq_zero {f : pre_tilt K v O hv p} : val K v O hv p f = 0 ↔ f = 0 := begin by_cases hf0 : f = 0, { rw hf0, exact iff_of_true (valuation.map_zero _) rfl }, obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf0 $ perfection.ext h), show val_aux K v O hv p f = 0 ↔ f = 0, refine iff_of_false (λ hvf, hn _) hf0, rw val_aux_eq hn at hvf, replace hvf := pow_eq_zero hvf, rwa mod_p.pre_val_eq_zero at hvf end end classical instance : integral_domain (pre_tilt K v O hv p) := { exists_pair_ne := (char_p.nontrivial_of_char_ne_one hp.1.ne_one).1, eq_zero_or_eq_zero_of_mul_eq_zero := λ f g hfg, by { simp_rw ← map_eq_zero at hfg ⊢, contrapose! hfg, rw valuation.map_mul, exact mul_ne_zero hfg.1 hfg.2 }, .. (infer_instance : comm_ring (pre_tilt K v O hv p)) } end pre_tilt /-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in [scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`, this is implemented as the fraction field of the perfection of `O/(p)`. -/ @[nolint has_inhabited_instance] def tilt := fraction_ring (pre_tilt K v O hv p) namespace tilt noncomputable instance : field (tilt K v O hv p) := fraction_ring.field end tilt end perfectoid
b9612fc2b04dfd2c45fdad6f73ea6935528c5ee4
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/analysis/special_functions/exp_log.lean
2ea61436da3b327da5fb57994ad0a8ee9fb0845e
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,774
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import data.complex.exponential import analysis.complex.basic import analysis.calculus.mean_value import measure_theory.borel_space /-! # Complex and real exponential, real logarithm ## Main statements This file establishes the basic analytical properties of the complex and real exponential functions (continuity, differentiability, computation of the derivative). It also contains the definition of the real logarithm function (as the inverse of the exponential on `(0, +∞)`, extended to `ℝ` by setting `log (-x) = log x`) and its basic properties (continuity, differentiability, formula for the derivative). The complex logarithm is *not* defined in this file as it relies on trigonometric functions. See instead `trigonometric.lean`. ## Tags exp, log -/ noncomputable theory open finset filter metric asymptotics open_locale classical topological_space namespace complex /-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/ lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x := begin rw has_deriv_at_iff_is_o_nhds_zero, have : (1 : ℕ) < 2 := by norm_num, refine (is_O.of_bound (∥exp x∥) _).trans_is_o (is_o_pow_id this), have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) := metric.ball_mem_nhds 0 zero_lt_one, apply filter.mem_sets_of_superset this (λz hz, _), simp only [metric.mem_ball, dist_zero_right] at hz, simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow, zero_add, set.mem_set_of_eq], calc ∥exp (x + z) - exp x - z * exp x∥ = ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring } ... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _ ... ≤ ∥exp x∥ * ∥z∥^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _) end lemma differentiable_exp : differentiable ℂ exp := λx, (has_deriv_at_exp x).differentiable_at lemma differentiable_at_exp {x : ℂ} : differentiable_at ℂ exp x := differentiable_exp x @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous lemma times_cont_diff_exp : ∀ {n}, times_cont_diff ℂ n exp := begin refine times_cont_diff_all_iff_nat.2 (λ n, _), induction n with n ihn, { exact times_cont_diff_zero.2 continuous_exp }, { rw times_cont_diff_succ_iff_deriv, use differentiable_exp, rwa deriv_exp } end lemma measurable_exp : measurable exp := continuous_exp.measurable end complex section variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} lemma has_deriv_at.cexp (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x := (complex.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.cexp (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') s x := (complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cexp (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.exp (f x)) s x = complex.exp (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cexp.deriv_within hxs @[simp] lemma deriv_cexp (hc : differentiable_at ℂ f x) : deriv (λx, complex.exp (f x)) x = complex.exp (f x) * (deriv f x) := hc.has_deriv_at.cexp.deriv end section variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E} {s : set E} lemma measurable.cexp {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable (λ x, complex.exp (f x)) := complex.measurable_exp.comp hf lemma has_fderiv_within_at.cexp (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') s x := (complex.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf lemma has_fderiv_at.cexp (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') x := has_fderiv_within_at_univ.1 $ hf.has_fderiv_within_at.cexp lemma differentiable_within_at.cexp (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.exp (f x)) s x := hf.has_fderiv_within_at.cexp.differentiable_within_at @[simp] lemma differentiable_at.cexp (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.exp (f x)) x := hc.has_fderiv_at.cexp.differentiable_at lemma differentiable_on.cexp (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.exp (f x)) s := λx h, (hc x h).cexp @[simp] lemma differentiable.cexp (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.exp (f x)) := λx, (hc x).cexp lemma times_cont_diff.cexp {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.exp (f x)) := complex.times_cont_diff_exp.comp h lemma times_cont_diff_at.cexp {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.exp (f x)) x := complex.times_cont_diff_exp.times_cont_diff_at.comp x hf lemma times_cont_diff_on.cexp {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.exp (f x)) s := complex.times_cont_diff_exp.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.cexp {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.exp (f x)) s x := complex.times_cont_diff_exp.times_cont_diff_at.comp_times_cont_diff_within_at x hf end namespace real variables {x y z : ℝ} lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x := (complex.has_deriv_at_exp x).real_of_complex lemma times_cont_diff_exp {n} : times_cont_diff ℝ n exp := complex.times_cont_diff_exp.real_of_complex lemma differentiable_exp : differentiable ℝ exp := λx, (has_deriv_at_exp x).differentiable_at lemma differentiable_at_exp : differentiable_at ℝ exp x := differentiable_exp x @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous lemma measurable_exp : measurable exp := continuous_exp.measurable end real section /-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} lemma has_deriv_at.exp (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x := (real.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.exp (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.exp (f x)) (real.exp (f x) * f') s x := (real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf lemma deriv_within_exp (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.exp (f x)) s x = real.exp (f x) * (deriv_within f s x) := hf.has_deriv_within_at.exp.deriv_within hxs @[simp] lemma deriv_exp (hc : differentiable_at ℝ f x) : deriv (λx, real.exp (f x)) x = real.exp (f x) * (deriv f x) := hc.has_deriv_at.exp.deriv end section /-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable function, for standalone use and use with `simp`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ} {x : E} {s : set E} lemma measurable.exp {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.exp (f x)) := real.measurable_exp.comp hf lemma times_cont_diff.exp {n} (hf : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.exp (f x)) := real.times_cont_diff_exp.comp hf lemma times_cont_diff_at.exp {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.exp (f x)) x := real.times_cont_diff_exp.times_cont_diff_at.comp x hf lemma times_cont_diff_on.exp {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.exp (f x)) s := real.times_cont_diff_exp.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.exp {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.exp (f x)) s x := real.times_cont_diff_exp.times_cont_diff_at.comp_times_cont_diff_within_at x hf lemma has_fderiv_within_at.exp (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.exp (f x)) (real.exp (f x) • f') s x := begin convert (has_deriv_at_iff_has_fderiv_at.1 $ real.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf, ext y, simp [mul_comm] end lemma has_fderiv_at.exp (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.exp (f x)) (real.exp (f x) • f') x := has_fderiv_within_at_univ.1 $ hf.has_fderiv_within_at.exp lemma differentiable_within_at.exp (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.exp (f x)) s x := hf.has_fderiv_within_at.exp.differentiable_within_at @[simp] lemma differentiable_at.exp (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.exp (f x)) x := hc.has_fderiv_at.exp.differentiable_at lemma differentiable_on.exp (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.exp (f x)) s := λx h, (hc x h).exp @[simp] lemma differentiable.exp (hc : differentiable ℝ f) : differentiable ℝ (λx, real.exp (f x)) := λx, (hc x).exp lemma fderiv_within_exp (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.exp (f x)) s x = real.exp (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.exp.fderiv_within hxs @[simp] lemma fderiv_exp (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.exp (f x)) x = real.exp (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.exp.fderiv end namespace real variables {x y z : ℝ} lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp, from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp ⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩, match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := this hx1 end /-- The real logarithm function, equal to the inverse of the exponential for `x > 0`, to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to `(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and the derivative of `log` is `1/x` away from `0`. -/ @[pp_nodot] noncomputable def log (x : ℝ) : ℝ := if hx : x ≠ 0 then classical.some (exists_exp_eq_of_pos (abs_pos.mpr hx)) else 0 lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = abs x := by { rw [log, dif_pos hx], exact classical.some_spec (exists_exp_eq_of_pos ((abs_pos.mpr hx))) } lemma exp_log (hx : 0 < x) : exp (log x) = x := by { rw exp_log_eq_abs (ne_of_gt hx), exact abs_of_pos hx } lemma range_exp : set.range exp = {x | 0 < x} := set.ext $ λ x, ⟨by { rintro ⟨x, rfl⟩, exact exp_pos x }, λ hx, ⟨log x, exp_log hx⟩⟩ lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x := by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx } @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) lemma log_surjective : function.surjective log := λ x, ⟨exp x, log_exp x⟩ @[simp] lemma range_log : set.range log = set.univ := log_surjective.range_eq @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] @[simp] lemma log_abs (x : ℝ) : log (abs x) = log x := begin by_cases h : x = 0, { simp [h] }, { apply exp_injective, rw [exp_log_eq_abs h, exp_log_eq_abs, abs_abs], simp [h] } end @[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x := by rw [← log_abs x, ← log_abs (-x), abs_neg] lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul] @[simp] lemma log_inv (x : ℝ) : log (x⁻¹) = -log x := begin by_cases hx : x = 0, { simp [hx] }, apply eq_neg_of_add_eq_zero, rw [← log_mul (inv_ne_zero hx) hx, inv_mul_cancel hx, log_one] end lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x := by { rw ← log_one, exact log_lt_log_iff (by norm_num) hx } lemma log_pos (hx : 1 < x) : 0 < log x := (log_pos_iff (lt_trans zero_lt_one hx)).2 hx lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg_iff (hx : 0 < x) : 0 ≤ log x ↔ 1 ≤ x := by rw [← not_lt, log_neg_iff hx, not_lt] lemma log_nonneg (hx : 1 ≤ x) : 0 ≤ log x := (log_nonneg_iff (zero_lt_one.trans_le hx)).2 hx lemma log_nonpos_iff (hx : 0 < x) : log x ≤ 0 ↔ x ≤ 1 := by rw [← not_lt, log_pos_iff hx, not_lt] lemma log_nonpos_iff' (hx : 0 ≤ x) : log x ≤ 0 ↔ x ≤ 1 := begin rcases hx.eq_or_lt with (rfl|hx), { simp [le_refl, zero_le_one] }, exact log_nonpos_iff hx end lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 := (log_nonpos_iff' hx).2 h'x section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos (le_of_lt this) hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos.2 x.2) y.2), have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul (ne_of_gt x.2) (ne_of_gt h.2), simp only [this, log_mul (ne_of_gt x.2) one_ne_zero, log_one], exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_coe), have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos.2 x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_coe, suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` are provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma has_deriv_at_log_of_pos (hx : 0 < x) : has_deriv_at log x⁻¹ x := have has_deriv_at log (exp $ log x)⁻¹ x, from (has_deriv_at_exp $ log x).of_local_left_inverse (continuous_at_log hx) (ne_of_gt $ exp_pos _) $ eventually.mono (mem_nhds_sets is_open_Ioi hx) @exp_log, by rwa [exp_log hx] at this lemma has_deriv_at_log (hx : x ≠ 0) : has_deriv_at log x⁻¹ x := begin by_cases h : 0 < x, { exact has_deriv_at_log_of_pos h }, push_neg at h, convert ((has_deriv_at_log_of_pos (neg_pos.mpr (lt_of_le_of_ne h hx))) .comp x (has_deriv_at_id x).neg), { ext y, exact (log_neg_eq_log y).symm }, { field_simp [hx] } end lemma measurable_log : measurable log := measurable_of_measurable_on_compl_singleton 0 $ continuous.measurable $ continuous_iff_continuous_at.2 $ λ x, (real.has_deriv_at_log x.2).continuous_at.comp continuous_at_subtype_coe end real section log_differentiable open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} lemma measurable.log (hf : measurable f) : measurable (λ x, log (f x)) := measurable_log.comp hf lemma has_deriv_within_at.log (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, log (f y)) (f' / (f x)) s x := begin convert (has_deriv_at_log hx).comp_has_deriv_within_at x hf, field_simp end lemma has_deriv_at.log (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, log (f y)) (f' / f x) x := begin rw ← has_deriv_within_at_univ at *, exact hf.log hx end lemma differentiable_within_at.log (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, log (f x)) s x := (hf.has_deriv_within_at.log hx).differentiable_within_at @[simp] lemma differentiable_at.log (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, log (f x)) x := (hf.has_deriv_at.log hx).differentiable_at lemma differentiable_on.log (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, log (f x)) s := λx h, (hf x h).log (hx x h) @[simp] lemma differentiable.log (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, log (f x)) := λx, (hf x).log (hx x) lemma deriv_within_log' (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, log (f x)) s x = (deriv_within f s x) / (f x) := (hf.has_deriv_within_at.log hx).deriv_within hxs @[simp] lemma deriv_log' (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, log (f x)) x = (deriv f x) / (f x) := (hf.has_deriv_at.log hx).deriv end log_differentiable namespace real /-- The real exponential function tends to `+∞` at `+∞`. -/ lemma tendsto_exp_at_top : tendsto exp at_top at_top := begin have A : tendsto (λx:ℝ, x + 1) at_top at_top := tendsto_at_top_add_const_right at_top 1 tendsto_id, have B : ∀ᶠ x in at_top, x + 1 ≤ exp x := eventually_at_top.2 ⟨0, λx hx, add_one_le_exp_of_nonneg hx⟩, exact tendsto_at_top_mono' at_top B A end /-- The real exponential function tends to `0` at `-∞` or, equivalently, `exp(-x)` tends to `0` at `+∞` -/ lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm) /-- The real exponential function tends to `1` at `0`. -/ lemma tendsto_exp_nhds_0_nhds_1 : tendsto exp (𝓝 0) (𝓝 1) := by { convert continuous_exp.tendsto 0, simp } /-- The function `exp(x)/x^n` tends to `+∞` at `+∞`, for any natural number `n` -/ lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top := begin have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n, have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos, have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n, { assume x hx, let y := x / (n+1), have y_pos : 0 < y := div_pos hx n_pos, have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc exp y = exp y * 1 : by simp ... ≤ exp y * (exp y / y)^n : begin apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)), rw one_le_div y_pos, apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)), exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one) end ... = exp y * exp (n * y) / y^n : by rw [div_pow, exp_nat_mul, mul_div_assoc] ... = exp ((n + 1) * y) / y^n : by rw [← exp_add, add_mul, one_mul, add_comm] ... = exp x / (x / (n+1))^n : by { dsimp [y], rw mul_div_cancel' _ n_ne_zero } ... = (n+1)^n * (exp x / x^n) : by rw [← mul_div_assoc, div_pow, div_div_eq_mul_div, mul_comm], rwa div_le_iff' (pow_pos n_pos n) }, have B : ∀ᶠ x in at_top, exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n := mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩, have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top := tendsto_at_top_div (pow_pos n_pos n) (tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)), exact tendsto_at_top_mono' at_top B C end /-- The function `x^n * exp(-x)` tends to `0` at `+∞`, for any natural number `n`. -/ lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx, by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg] /-- The function `(b * exp x + c) / (x ^ n)` tends to `+∞` at `+∞`, for any positive natural number `n` and any real numbers `b` and `c` such that `b` is positive. -/ lemma tendsto_mul_exp_add_div_pow_at_top (b c : ℝ) (n : ℕ) (hb : 0 < b) (hn : 1 ≤ n) : tendsto (λ x, (b * (exp x) + c) / (x^n)) at_top at_top := begin refine tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) _) (tendsto_at_top_add_tendsto_right (tendsto_at_top_mul_left hb (tendsto_exp_div_pow_at_top n)) ((tendsto_pow_neg_at_top hn).mul (@tendsto_const_nhds _ _ _ c _))), intros x hx, simp only [fpow_neg x n], ring, end /-- The function `(x ^ n) / (b * exp x + c)` tends to `0` at `+∞`, for any positive natural number `n` and any real numbers `b` and `c` such that `b` is nonzero. -/ lemma tendsto_div_pow_mul_exp_add_at_top (b c : ℝ) (n : ℕ) (hb : 0 ≠ b) (hn : 1 ≤ n) : tendsto (λ x, x^n / (b * (exp x) + c)) at_top (𝓝 0) := begin have H : ∀ d e, 0 < d → tendsto (λ (x:ℝ), x^n / (d * (exp x) + e)) at_top (𝓝 0), { intros b' c' h, convert tendsto.inv_tendsto_at_top (tendsto_mul_exp_add_div_pow_at_top b' c' n h hn), ext x, simpa only [pi.inv_apply] using inv_div.symm }, cases lt_or_gt_of_ne hb, { exact H b c h }, { convert (H (-b) (-c) (neg_pos.mpr h)).neg, { ext x, field_simp, rw [← neg_add (b * exp x) c, neg_div_neg_eq] }, { exact neg_zero.symm } }, end /-- The real logarithm function tends to `+∞` at `+∞`. -/ lemma tendsto_log_at_top : tendsto log at_top at_top := begin rw tendsto_at_top_at_top, intro b, use exp b, intros a hab, rw [← exp_le_exp, exp_log_eq_abs (ne_of_gt $ lt_of_lt_of_le (exp_pos b) hab)], exact le_trans hab (le_abs_self a) end open_locale big_operators /-- A crude lemma estimating the difference between `log (1-x)` and its Taylor series at `0`, where the main point of the bound is that it tends to `0`. The goal is to deduce the series expansion of the logarithm, in `has_sum_pow_div_log_of_abs_lt_1`. -/ lemma abs_log_sub_add_sum_range_le {x : ℝ} (h : abs x < 1) (n : ℕ) : abs ((∑ i in range n, x^(i+1)/(i+1)) + log (1-x)) ≤ (abs x)^(n+1) / (1 - abs x) := begin /- For the proof, we show that the derivative of the function to be estimated is small, and then apply the mean value inequality. -/ let F : ℝ → ℝ := λ x, ∑ i in range n, x^(i+1)/(i+1) + log (1-x), -- First step: compute the derivative of `F` have A : ∀ y ∈ set.Ioo (-1 : ℝ) 1, deriv F y = - (y^n) / (1 - y), { assume y hy, have : (∑ i in range n, (↑i + 1) * y ^ i / (↑i + 1)) = (∑ i in range n, y ^ i), { congr' with i, have : (i : ℝ) + 1 ≠ 0 := ne_of_gt (nat.cast_add_one_pos i), field_simp [this, mul_comm] }, field_simp [F, this, ← geom_series_def, geom_sum (ne_of_lt hy.2), sub_ne_zero_of_ne (ne_of_gt hy.2), sub_ne_zero_of_ne (ne_of_lt hy.2)], ring }, -- second step: show that the derivative of `F` is small have B : ∀ y ∈ set.Icc (-abs x) (abs x), abs (deriv F y) ≤ (abs x)^n / (1 - abs x), { assume y hy, have : y ∈ set.Ioo (-(1 : ℝ)) 1 := ⟨lt_of_lt_of_le (neg_lt_neg h) hy.1, lt_of_le_of_lt hy.2 h⟩, calc abs (deriv F y) = abs (-(y^n) / (1 - y)) : by rw [A y this] ... ≤ (abs x)^n / (1 - abs x) : begin have : abs y ≤ abs x := abs_le.2 hy, have : 0 < 1 - abs x, by linarith, have : 1 - abs x ≤ abs (1 - y) := le_trans (by linarith [hy.2]) (le_abs_self _), simp only [← pow_abs, abs_div, abs_neg], apply_rules [div_le_div, pow_nonneg, abs_nonneg, pow_le_pow_of_le_left] end }, -- third step: apply the mean value inequality have C : ∥F x - F 0∥ ≤ ((abs x)^n / (1 - abs x)) * ∥x - 0∥, { have : ∀ y ∈ set.Icc (- abs x) (abs x), differentiable_at ℝ F y, { assume y hy, have : 1 - y ≠ 0 := sub_ne_zero_of_ne (ne_of_gt (lt_of_le_of_lt hy.2 h)), simp [F, this] }, apply convex.norm_image_sub_le_of_norm_deriv_le this B (convex_Icc _ _) _ _, { simpa using abs_nonneg x }, { simp [le_abs_self x, neg_le.mp (neg_le_abs_self x)] } }, -- fourth step: conclude by massaging the inequality of the third step simpa [F, norm_eq_abs, div_mul_eq_mul_div, pow_succ'] using C end /-- Power series expansion of the logarithm around `1`. -/ theorem has_sum_pow_div_log_of_abs_lt_1 {x : ℝ} (h : abs x < 1) : has_sum (λ (n : ℕ), x ^ (n + 1) / (n + 1)) (-log (1 - x)) := begin rw summable.has_sum_iff_tendsto_nat, show tendsto (λ (n : ℕ), ∑ (i : ℕ) in range n, x ^ (i + 1) / (i + 1)) at_top (𝓝 (-log (1 - x))), { rw [tendsto_iff_norm_tendsto_zero], simp only [norm_eq_abs, sub_neg_eq_add], refine squeeze_zero (λ n, abs_nonneg _) (abs_log_sub_add_sum_range_le h) _, suffices : tendsto (λ (t : ℕ), abs x ^ (t + 1) / (1 - abs x)) at_top (𝓝 (abs x * 0 / (1 - abs x))), by simpa, simp only [pow_succ], refine (tendsto_const_nhds.mul _).div_const, exact tendsto_pow_at_top_nhds_0_of_lt_1 (abs_nonneg _) h }, show summable (λ (n : ℕ), x ^ (n + 1) / (n + 1)), { refine summable_of_norm_bounded _ (summable_geometric_of_lt_1 (abs_nonneg _) h) (λ i, _), calc ∥x ^ (i + 1) / (i + 1)∥ = abs x ^ (i+1) / (i+1) : begin have : (0 : ℝ) ≤ i + 1 := le_of_lt (nat.cast_add_one_pos i), rw [norm_eq_abs, abs_div, ← pow_abs, abs_of_nonneg this], end ... ≤ abs x ^ (i+1) / (0 + 1) : begin apply_rules [div_le_div_of_le_left, pow_nonneg, abs_nonneg, add_le_add_right, i.cast_nonneg], norm_num, end ... ≤ abs x ^ i : by simpa [pow_succ'] using mul_le_of_le_one_right (pow_nonneg (abs_nonneg x) i) (le_of_lt h) } end end real
e918f7dbbc7dc4ab6a5068d0550d34ea3ebedfef
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/special_functions/bernstein.lean
9965481e753404db10801a8701ae1b3f7f35d5db
[ "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
12,949
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.order.field import ring_theory.polynomial.bernstein import topology.continuous_function.polynomial /-! # Bernstein approximations and Weierstrass' theorem We prove that the Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. Our proof follows [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D. The original proof, due to [Bernstein](bernstein1912) in 1912, is probabilistic, and relies on Bernoulli's theorem, which gives bounds for how quickly the observed frequencies in a Bernoulli trial approach the underlying probability. The proof here does not directly rely on Bernoulli's theorem, but can also be given a probabilistic account. * Consider a weighted coin which with probability `x` produces heads, and with probability `1-x` produces tails. * The value of `bernstein n k x` is the probability that such a coin gives exactly `k` heads in a sequence of `n` tosses. * If such an appearance of `k` heads results in a payoff of `f(k / n)`, the `n`-th Bernstein approximation for `f` evaluated at `x` is the expected payoff. * The main estimate in the proof bounds the probability that the observed frequency of heads differs from `x` by more than some `δ`, obtaining a bound of `(4 * n * δ^2)⁻¹`, irrespective of `x`. * This ensures that for `n` large, the Bernstein approximation is (uniformly) close to the payoff function `f`. (You don't need to think in these terms to follow the proof below: it's a giant `calc` block!) This result proves Weierstrass' theorem that polynomials are dense in `C([0,1], ℝ)`, although we defer an abstract statement of this until later. -/ noncomputable theory open_locale classical open_locale big_operators open_locale bounded_continuous_function open_locale unit_interval /-- The Bernstein polynomials, as continuous functions on `[0,1]`. -/ def bernstein (n ν : ℕ) : C(I, ℝ) := (bernstein_polynomial ℝ n ν).to_continuous_map_on I @[simp] lemma bernstein_apply (n ν : ℕ) (x : I) : bernstein n ν x = n.choose ν * x^ν * (1-x)^(n-ν) := begin dsimp [bernstein, polynomial.to_continuous_map_on, polynomial.to_continuous_map, bernstein_polynomial], simp, end lemma bernstein_nonneg {n ν : ℕ} {x : I} : 0 ≤ bernstein n ν x := begin simp only [bernstein_apply], exact mul_nonneg (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (by unit_interval) _)) (pow_nonneg (by unit_interval) _), end /-! We now give a slight reformulation of `bernstein_polynomial.variance`. -/ namespace bernstein /-- Send `k : fin (n+1)` to the equally spaced points `k/n` in the unit interval. -/ def z {n : ℕ} (k : fin (n+1)) : I := ⟨(k : ℝ) / n, begin cases n, { norm_num }, { have h₁ : 0 < (n.succ : ℝ) := by exact_mod_cast (nat.succ_pos _), have h₂ : ↑k ≤ n.succ := by exact_mod_cast (fin.le_last k), rw [set.mem_Icc, le_div_iff h₁, div_le_iff h₁], norm_cast, simp [h₂], }, end⟩ local postfix `/ₙ`:90 := z lemma probability (n : ℕ) (x : I) : ∑ k : fin (n+1), bernstein n k x = 1 := begin have := bernstein_polynomial.sum ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range] at this, exact this, end lemma variance {n : ℕ} (h : 0 < (n : ℝ)) (x : I) : ∑ k : fin (n+1), (x - k/ₙ : ℝ)^2 * bernstein n k x = x * (1-x) / n := begin have h' : (n : ℝ) ≠ 0 := ne_of_gt h, apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', dsimp, conv_lhs { simp only [finset.sum_mul, z], }, conv_rhs { rw div_mul_cancel _ h', }, have := bernstein_polynomial.variance ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range, ←polynomial.nat_cast_mul] at this, convert this using 1, { congr' 1, funext k, rw [mul_comm _ (n : ℝ), mul_comm _ (n : ℝ), ←mul_assoc, ←mul_assoc], congr' 1, field_simp [h], ring, }, { ring, }, end end bernstein open bernstein local postfix `/ₙ`:2000 := z /-- The `n`-th approximation of a continuous function on `[0,1]` by Bernstein polynomials, given by `∑ k, f (k/n) * bernstein n k x`. -/ def bernstein_approximation (n : ℕ) (f : C(I, ℝ)) : C(I, ℝ) := ∑ k : fin (n+1), f k/ₙ • bernstein n k /-! We now set up some of the basic machinery of the proof that the Bernstein approximations converge uniformly. A key player is the set `S f ε h n x`, for some function `f : C(I, ℝ)`, `h : 0 < ε`, `n : ℕ` and `x : I`. This is the set of points `k` in `fin (n+1)` such that `k/n` is within `δ` of `x`, where `δ` is the modulus of uniform continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. We show that if `k ∉ S`, then `1 ≤ δ^-2 * (x - k/n)^2`. -/ namespace bernstein_approximation @[simp] lemma apply (n : ℕ) (f : C(I, ℝ)) (x : I) : bernstein_approximation n f x = ∑ k : fin (n+1), f k/ₙ * bernstein n k x := by simp [bernstein_approximation] /-- The modulus of (uniform) continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. -/ def δ (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) : ℝ := f.modulus (ε/2) (half_pos h) lemma δ_pos {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} : 0 < δ f ε h := f.modulus_pos /-- The set of points `k` so `k/n` is within `δ` of `x`. -/ def S (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) (n : ℕ) (x : I) : finset (fin (n+1)) := { k : fin (n+1) | dist k/ₙ x < δ f ε h }.to_finset /-- If `k ∈ S`, then `f(k/n)` is close to `f x`. -/ lemma lt_of_mem_S {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ S f ε h n x) : |f k/ₙ - f x| < ε/2 := begin apply f.dist_lt_of_dist_lt_modulus (ε/2) (half_pos h), simpa [S] using m, end /-- If `k ∉ S`, then as `δ ≤ |x - k/n|`, we have the inequality `1 ≤ δ^-2 * (x - k/n)^2`. This particular formulation will be helpful later. -/ lemma le_of_mem_S_compl {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ (S f ε h n x)ᶜ) : (1 : ℝ) ≤ (δ f ε h)^(-2 : ℤ) * (x - k/ₙ) ^ 2 := begin simp only [finset.mem_compl, not_lt, set.mem_to_finset, set.mem_set_of_eq, S] at m, erw [zpow_neg, ← div_eq_inv_mul, one_le_div (pow_pos δ_pos 2), sq_le_sq, abs_of_pos δ_pos], rwa [dist_comm] at m end end bernstein_approximation open bernstein_approximation open bounded_continuous_function open filter open_locale topological_space /-- The Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. This is the proof given in [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D, and reproduced on wikipedia. -/ theorem bernstein_approximation_uniform (f : C(I, ℝ)) : tendsto (λ n : ℕ, bernstein_approximation n f) at_top (𝓝 f) := begin simp only [metric.nhds_basis_ball.tendsto_right_iff, metric.mem_ball, dist_eq_norm], intros ε h, let δ := δ f ε h, have nhds_zero := tendsto_const_div_at_top_nhds_0_nat (2 * ∥f∥ * δ ^ (-2 : ℤ)), filter_upwards [nhds_zero.eventually (gt_mem_nhds (half_pos h)), eventually_gt_at_top 0] with n nh npos', have npos : 0 < (n:ℝ) := by exact_mod_cast npos', -- Two easy inequalities we'll need later: have w₁ : 0 ≤ 2 * ∥f∥ := mul_nonneg (by norm_num) (norm_nonneg f), have w₂ : 0 ≤ 2 * ∥f∥ * δ^(-2 : ℤ) := mul_nonneg w₁ pow_minus_two_nonneg, -- As `[0,1]` is compact, it suffices to check the inequality pointwise. rw (continuous_map.norm_lt_iff _ h), intro x, -- The idea is to split up the sum over `k` into two sets, -- `S`, where `x - k/n < δ`, and its complement. let S := S f ε h n x, calc |(bernstein_approximation n f - f) x| = |bernstein_approximation n f x - f x| : rfl ... = |bernstein_approximation n f x - f x * 1| : by rw mul_one ... = |bernstein_approximation n f x - f x * (∑ k : fin (n+1), bernstein n k x)| : by rw bernstein.probability ... = |∑ k : fin (n+1), (f k/ₙ - f x) * bernstein n k x| : by simp [bernstein_approximation, finset.mul_sum, sub_mul] ... ≤ ∑ k : fin (n+1), |(f k/ₙ - f x) * bernstein n k x| : finset.abs_sum_le_sum_abs _ _ ... = ∑ k : fin (n+1), |f k/ₙ - f x| * bernstein n k x : by simp_rw [abs_mul, abs_eq_self.mpr bernstein_nonneg] ... = ∑ k in S, |f k/ₙ - f x| * bernstein n k x + ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x : (S.sum_add_sum_compl _).symm -- We'll now deal with the terms in `S` and the terms in `Sᶜ` in separate calc blocks. ... < ε/2 + ε/2 : add_lt_add_of_le_of_lt _ _ ... = ε : add_halves ε, { -- We now work on the terms in `S`: uniform continuity and `bernstein.probability` -- quickly give us a bound. calc ∑ k in S, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in S, ε/2 * bernstein n k x : finset.sum_le_sum (λ k m, (mul_le_mul_of_nonneg_right (le_of_lt (lt_of_mem_S m)) bernstein_nonneg)) ... = ε/2 * ∑ k in S, bernstein n k x : by rw finset.mul_sum -- In this step we increase the sum over `S` back to a sum over all of `fin (n+1)`, -- so that we can use `bernstein.probability`. ... ≤ ε/2 * ∑ k : fin (n+1), bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, bernstein_nonneg)) (le_of_lt (half_pos h)) ... = ε/2 : by rw [bernstein.probability, mul_one] }, { -- We now turn to working on `Sᶜ`: we control the difference term just using `∥f∥`, -- and then insert a `δ^(-2) * (x - k/n)^2` factor -- (which is at least one because we are not in `S`). calc ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in Sᶜ, (2 * ∥f∥) * bernstein n k x : finset.sum_le_sum (λ k m, mul_le_mul_of_nonneg_right (f.dist_le_two_norm _ _) bernstein_nonneg) ... = (2 * ∥f∥) * ∑ k in Sᶜ, bernstein n k x : by rw finset.mul_sum ... ≤ (2 * ∥f∥) * ∑ k in Sᶜ, δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_sum (λ k m, begin conv_lhs { rw ←one_mul (bernstein _ _ _), }, exact mul_le_mul_of_nonneg_right (le_of_mem_S_compl m) bernstein_nonneg, end)) w₁ -- Again enlarging the sum from `Sᶜ` to all of `fin (n+1)` ... ≤ (2 * ∥f∥) * ∑ k : fin (n+1), δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, mul_nonneg (mul_nonneg pow_minus_two_nonneg (sq_nonneg _)) bernstein_nonneg)) w₁ ... = (2 * ∥f∥) * δ^(-2 : ℤ) * ∑ k : fin (n+1), (x - k/ₙ)^2 * bernstein n k x : by conv_rhs { rw [mul_assoc, finset.mul_sum], simp only [←mul_assoc], } -- `bernstein.variance` and `x ∈ [0,1]` gives the uniform bound ... = (2 * ∥f∥) * δ^(-2 : ℤ) * x * (1-x) / n : by { rw variance npos, ring, } ... ≤ (2 * ∥f∥) * δ^(-2 : ℤ) / n : (div_le_div_right npos).mpr begin apply mul_nonneg_le_one_le w₂, apply mul_nonneg_le_one_le w₂ le_rfl, all_goals { unit_interval, }, end ... < ε/2 : nh, } end
ae154ddbbac95a2da8379b4b238c27f00cedb70a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/bitvec/basic.lean
2b7cc5a1f1cfb2332edd78762727bd010a8c6906
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,679
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.bitvec.core import data.fin import tactic.norm_num import tactic.monotonicity namespace bitvec instance (n : ℕ) : preorder (bitvec n) := preorder.lift bitvec.to_nat /-- convert `fin` to `bitvec` -/ def of_fin {n : ℕ} (i : fin $ 2^n) : bitvec n := bitvec.of_nat _ i.val lemma of_fin_val {n : ℕ} (i : fin $ 2^n) : (of_fin i).to_nat = i.val := by rw [of_fin,to_nat_of_nat,nat.mod_eq_of_lt]; apply i.is_lt /-- convert `bitvec` to `fin` -/ def to_fin {n : ℕ} (i : bitvec n) : fin $ 2^n := @fin.of_nat' _ ⟨pow_pos (by norm_num) _⟩ i.to_nat lemma add_lsb_eq_twice_add_one {x b} : add_lsb x b = 2 * x + cond b 1 0 := by simp [add_lsb,two_mul] lemma to_nat_eq_foldr_reverse {n : ℕ} (v : bitvec n) : v.to_nat = v.to_list.reverse.foldr (flip add_lsb) 0 := by rw [list.foldr_reverse, flip]; refl lemma to_nat_lt {n : ℕ} (v : bitvec n) : v.to_nat < 2^n := begin suffices : v.to_nat + 1 ≤ 2 ^ n, { simpa }, rw to_nat_eq_foldr_reverse, cases v with xs h, dsimp [bitvec.to_nat,bits_to_nat], rw ← list.length_reverse at h, generalize_hyp : xs.reverse = ys at ⊢ h, clear xs, induction ys generalizing n, { simp [← h] }, { simp only [←h, pow_add, flip, list.length, list.foldr, pow_one], rw [add_lsb_eq_twice_add_one], transitivity 2 * list.foldr (λ (x : bool) (y : ℕ), add_lsb y x) 0 ys_tl + 2 * 1, { ac_mono, rw two_mul, mono, cases ys_hd; simp }, { rw ← left_distrib, ac_mono, norm_num, apply ys_ih, refl } }, end lemma add_lsb_div_two {x b} : add_lsb x b / 2 = x := by cases b; simp only [nat.add_mul_div_left, add_lsb, ←two_mul, add_comm, nat.succ_pos', nat.mul_div_right, gt_iff_lt, zero_add, cond]; norm_num lemma to_bool_add_lsb_mod_two {x b} : to_bool (add_lsb x b % 2 = 1) = b := by cases b; simp only [to_bool_iff, nat.add_mul_mod_self_left, add_lsb, ←two_mul, add_comm, bool.to_bool_false, nat.mul_mod_right, zero_add, cond, zero_ne_one]; norm_num lemma of_nat_to_nat {n : ℕ} (v : bitvec n) : bitvec.of_nat _ v.to_nat = v := begin cases v with xs h, ext1, change vector.to_list _ = xs, dsimp [bitvec.to_nat,bits_to_nat], rw ← list.length_reverse at h, rw [← list.reverse_reverse xs,list.foldl_reverse], generalize_hyp : xs.reverse = ys at ⊢ h, clear xs, induction ys generalizing n, { cases h, simp [bitvec.of_nat] }, { simp only [←nat.succ_eq_add_one, list.length] at h, subst n, simp only [bitvec.of_nat, vector.to_list_cons, vector.to_list_nil, list.reverse_cons, vector.to_list_append, list.foldr], erw [add_lsb_div_two, to_bool_add_lsb_mod_two], congr, apply ys_ih, refl } end lemma to_fin_val {n : ℕ} (v : bitvec n) : (to_fin v : ℕ) = v.to_nat := by rw [to_fin, fin.coe_of_nat_eq_mod', nat.mod_eq_of_lt]; apply to_nat_lt lemma to_fin_le_to_fin_of_le {n} {v₀ v₁ : bitvec n} (h : v₀ ≤ v₁) : v₀.to_fin ≤ v₁.to_fin := show (v₀.to_fin : ℕ) ≤ v₁.to_fin, by rw [to_fin_val,to_fin_val]; exact h lemma of_fin_le_of_fin_of_le {n : ℕ} {i j : fin (2^n)} (h : i ≤ j) : of_fin i ≤ of_fin j := show (bitvec.of_nat n i).to_nat ≤ (bitvec.of_nat n j).to_nat, by { simp only [to_nat_of_nat, nat.mod_eq_of_lt, fin.is_lt], exact h } lemma to_fin_of_fin {n} (i : fin $ 2^n) : (of_fin i).to_fin = i := fin.eq_of_veq (by simp [to_fin_val, of_fin, to_nat_of_nat, nat.mod_eq_of_lt, i.is_lt]) lemma of_fin_to_fin {n} (v : bitvec n) : of_fin (to_fin v) = v := by dsimp [of_fin]; rw [to_fin_val, of_nat_to_nat] end bitvec
5699b395840f7bcaad00475c5aeeabd86a802790
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/group_theory/sylow.lean
249864b8cddcfa8bd5a784227d1c26bf92311442
[ "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
11,385
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action group_theory.quotient_group import group_theory.order_of_element data.zmod.basic open equiv fintype finset mul_action function open equiv.perm is_subgroup list quotient_group universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 0] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] {p n : ℕ} (hp : nat.prime p) (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (equiv_fib (@quotient.mk' _ (orbit_rel G α))) ... = univ.sum (λ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a}) : card_sigma _ ... ≡ (@univ (fixed_points G α) _).sum (λ _, 1) [MOD p] : begin rw [← zmodp.eq_iff_modeq_nat hp, sum_nat_cast, sum_nat_cast], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)]; exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [nat.pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmodp.eq_iff_modeq_nat hp, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (nat.pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, nat.pow_zero]⟩, mem_univ _, by simp [zero_ne_one], rfl⟩ } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : set G) [is_subgroup s] (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ :: v lemma mk_vector_prod_eq_one_inj (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_right_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ+) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.1, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ+) : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := λ v, subtype.eq $ vector.eq _ _ $ rotate_zero v.1.to_list, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.add_val, rotate_rotate, ← rotate_mod _ (b.1 + a.1), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ+) : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ by haveI : nonempty G := ⟨1⟩; exact rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- Cauchy's theorem -/ lemma exists_prime_order_of_dvd_card [fintype G] {p : ℕ} (hp : nat.prime p) (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.gt_one⟩ in let p' : ℕ+ := ⟨p, hp.pos⟩ in have hn : p' = n + 1 := subtype.eq (nat.succ_sub hp.pos), have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_inj _), card_vector], have hzmod : fintype.card (multiplicative (zmod p')) = (p' : ℕ) ^ 1 := (nat.pow_one p').symm ▸ card_fin _, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p')) (vectors_prod_eq_one G p') _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa nat.pow_one ... ∣ card G ^ (n : ℕ) : nat.pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p')) (vectors_prod_eq_one G p')) := nat.dvd_of_mod_eq_zero (hmodeq ▸ hn.symm ▸ nat.mod_eq_zero_of_dvd hdvdcard), have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p')) (vectors_prod_eq_one G p')) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p', one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p')) (vectors_prod_eq_one G p')) := calc (1 : ℕ) < p' : hp.gt_one ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_card_gt_one hlt ⟨_, one_mem_fixed_points_rotate p'⟩ in have hx : x ≠ list.repeat (1 : G) p', from λ h, by simpa [h, vector.repeat] using hx₄, have nG : nonempty G, from ⟨1⟩, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p').val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p'))), by rwa [zmod.val_cast_nat, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open is_subgroup is_submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : set G} [is_subgroup H] [fintype H] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (mem_normalizer_fintype (λ n hn, have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, inv_mem hn⟩)), by simpa only [mul_inv_rev, inv_inv] using this)), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_right H (inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ lemma fixed_points_mul_left_cosets_equiv_quotient (H : set G) [is_subgroup H] [fintype H] : fixed_points H (quotient H) ≃ quotient (subtype.val ⁻¹' H : set (normalizer H)) := @subtype_quotient_equiv_quotient_subtype G (normalizer H) (id _) (id _) (fixed_points _ _) (λ a, mem_fixed_points_mul_left_cosets_iff_mem_normalizer.symm) (by intros; refl) local attribute [instance] set_fintype lemma exists_subgroup_card_pow_prime [fintype G] {p : ℕ} : ∀ {n : ℕ} (hp : nat.prime p) (hdvd : p ^ n ∣ card G), ∃ H : set G, is_subgroup H ∧ fintype.card H = p ^ n | 0 := λ _ _, ⟨trivial G, by apply_instance, by simp⟩ | (n+1) := λ hp hdvd, let ⟨H, ⟨hH1, hH2⟩⟩ := exists_subgroup_card_pow_prime hp (dvd.trans (nat.pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in by exactI have hcard : card (quotient H) = s * p := (nat.mul_right_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, is_submonoid.one_mem H⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup, hH2, hs, nat.pow_succ, mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subtype.val ⁻¹' H : set (normalizer H))) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ card_modeq_card_fixed_points hp hH2, have hm' : p ∣ card (quotient (subtype.val ⁻¹' H : set (normalizer H))) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.group _) _ _ hp hm' in have hxcard : ∀ {f : fintype (gpowers x)}, card (gpowers x) = p, from λ f, by rw [← hx, order_eq_card_gpowers]; congr, have is_subgroup (mk ⁻¹' gpowers x), from is_group_hom.preimage _ _, have fintype (mk ⁻¹' gpowers x), by apply_instance, have hequiv : H ≃ (subtype.val ⁻¹' H : set (normalizer H)):= ⟨λ a, ⟨⟨a.1, subset_normalizer _ a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, ⟨subtype.val '' (mk ⁻¹' gpowers x), by apply_instance, by rw [set.card_image_of_injective (mk ⁻¹' gpowers x) subtype.val_injective, nat.pow_succ, ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod]; exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _)⟩ end sylow
970f5779fa0f4c5c3581c33331a449f1e6d6d989
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.44.lean
d565171c28ab01036fd95afe39953afce20464ca
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
243
lean
/- page 92 -/ import standard namespace hide inductive eq {A : Type} (a : A) : A → Prop := refl : eq a a -- BEGIN theorem subst {A : Type} {a b : A} {P : A → Prop} (H₁ : eq a b) (H₂ : P a) : P b := eq.rec H₂ H₁ -- END end hide
9f73db18641603941b430194a1a5ed70cd3f77d8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/986.lean
3f88415f8622a2009bf2a10a8c3721ac21abd932
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
133
lean
attribute [simp] Array.insertionSort.swapLoop #check @Array.insertionSort.swapLoop._eq_1 #check @Array.insertionSort.swapLoop._eq_2
b30f4fe5d428f41b249944dbdf56baf4d25780ba
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/unzip_error.lean
25fb95ce239b81d2b90ffd7a726aebb2f4216ad9
[ "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
364
lean
import data.examples.vector open nat vector prod variables {A B : Type} definition unzip : Π {n : nat}, vector (A × B) n → vector A n × vector B n | unzip nil := (nil, nil) | unzip ((a, b) :: v) := match unzip v with (va, vb) := (a :: va, b :: vb) end example : unzip ((1, 20) :: (2, 30) :: nil) = (1 :: 2 :: nil, 20 :: 30 :: nil) := rfl
f5015aaff2daff6f1085d103fc3ab1253841b108
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/PrettyPrinter/Delaborator/Builtins.lean
7d5fcda18b5406021d11495a0224426b96aaf974
[ "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
31,987
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.PrettyPrinter.Delaborator.Basic import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.PrettyPrinter.Delaborator.TopDownAnalyze import Lean.Parser namespace Lean.PrettyPrinter.Delaborator open Lean.Meta open Lean.Parser.Term open SubExpr def maybeAddBlockImplicit (ident : Syntax) : DelabM Syntax := do if ← getPPOption getPPAnalysisBlockImplicit then `(@$ident:ident) else ident def unfoldMDatas : Expr → Expr | Expr.mdata _ e _ => unfoldMDatas e | e => e @[builtinDelab fvar] def delabFVar : Delab := do let Expr.fvar id _ ← getExpr | unreachable! try let l ← getLocalDecl id maybeAddBlockImplicit (mkIdent l.userName) catch _ => -- loose free variable, use internal name maybeAddBlockImplicit $ mkIdent id.name -- loose bound variable, use pseudo syntax @[builtinDelab bvar] def delabBVar : Delab := do let Expr.bvar idx _ ← getExpr | unreachable! pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx @[builtinDelab mvar] def delabMVar : Delab := do let Expr.mvar n _ ← getExpr | unreachable! let mvarDecl ← getMVarDecl n let n := match mvarDecl.userName with | Name.anonymous => n.name.replacePrefix `_uniq `m | n => n `(?$(mkIdent n)) @[builtinDelab sort] def delabSort : Delab := do let Expr.sort l _ ← getExpr | unreachable! match l with | Level.zero _ => `(Prop) | Level.succ (Level.zero _) _ => `(Type) | _ => match l.dec with | some l' => `(Type $(Level.quote l' max_prec)) | none => `(Sort $(Level.quote l max_prec)) def unresolveNameGlobal (n₀ : Name) : DelabM Name := do if n₀.hasMacroScopes then return n₀ if (← getPPOption getPPFullNames) then match (← resolveGlobalName n₀) with | [(potentialMatch, _)] => if potentialMatch == n₀ then return n₀ else return rootNamespace ++ n₀ | _ => return n₀ -- if can't resolve, return the original let mut initialNames := (getRevAliases (← getEnv) n₀).toArray initialNames := initialNames.push (rootNamespace ++ n₀) for initialName in initialNames do match (← unresolveNameCore initialName) with | none => continue | some n => return n return n₀ -- if can't resolve, return the original where unresolveNameCore (n : Name) : DelabM (Option Name) := do let mut revComponents := n.components' let mut candidate := Name.anonymous for i in [:revComponents.length] do match revComponents with | [] => return none | cmpt::rest => candidate := cmpt ++ candidate; revComponents := rest match (← resolveGlobalName candidate) with | [(potentialMatch, _)] => if potentialMatch == n₀ then return some candidate else continue | _ => continue return none -- NOTE: not a registered delaborator, as `const` is never called (see [delab] description) def delabConst : Delab := do let Expr.const c₀ ls _ ← getExpr | unreachable! let ctx ← read let c₀ := if (← getPPOption getPPPrivateNames) then c₀ else (privateToUserName? c₀).getD c₀ let mut c ← unresolveNameGlobal c₀ let stx ← if ls.isEmpty || !(← getPPOption getPPUniverses) then if (← getLCtx).usesUserName c then -- `c` is also a local declaration if c == c₀ && !(← read).inPattern then -- `c` is the fully qualified named. So, we append the `_root_` prefix c := `_root_ ++ c else c := c₀ return mkIdent c else `($(mkIdent c).{$[$(ls.toArray.map quote)],*}) maybeAddBlockImplicit stx structure ParamKind where name : Name bInfo : BinderInfo defVal : Option Expr := none isAutoParam : Bool := false def ParamKind.isRegularExplicit (param : ParamKind) : Bool := param.bInfo.isExplicit && !param.isAutoParam && param.defVal.isNone /-- Return array with n-th element set to kind of n-th parameter of `e`. -/ partial def getParamKinds : DelabM (Array ParamKind) := do let e ← getExpr try withTransparency TransparencyMode.all do forallTelescopeArgs e.getAppFn e.getAppArgs fun params _ => do params.mapM fun param => do let l ← getLocalDecl param.fvarId! pure { name := l.userName, bInfo := l.binderInfo, defVal := l.type.getOptParamDefault?, isAutoParam := l.type.isAutoParam } catch _ => pure #[] -- recall that expr may be nonsensical where forallTelescopeArgs f args k := do forallBoundedTelescope (← inferType f) args.size fun xs b => if xs.isEmpty || xs.size == args.size then -- we still want to consider optParams forallTelescopeReducing b fun ys b => k (xs ++ ys) b else forallTelescopeArgs (mkAppN f $ args.shrink xs.size) (args.extract xs.size args.size) fun ys b => k (xs ++ ys) b @[builtinDelab app] def delabAppExplicit : Delab := whenPPOption getPPExplicit do let paramKinds ← getParamKinds let (fnStx, _, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let needsExplicit := paramKinds.any (fun param => !param.isRegularExplicit) && stx.getKind != `Lean.Parser.Term.explicit let stx ← if needsExplicit then `(@$stx) else pure stx pure (stx, paramKinds.toList, #[])) (fun ⟨fnStx, paramKinds, argStxs⟩ => do let isInstImplicit := match paramKinds with | [] => false | param :: _ => param.bInfo == BinderInfo.instImplicit let argStx ← if ← getPPOption getPPAnalysisHole then `(_) else if isInstImplicit == true then let stx ← if ← getPPOption getPPInstances then delab else `(_) if ← getPPOption getPPInstanceTypes then let typeStx ← withType delab `(($stx : $typeStx)) else stx else delab pure (fnStx, paramKinds.tailD [], argStxs.push argStx)) Syntax.mkApp fnStx argStxs def shouldShowMotive (motive : Expr) (opts : Options) : MetaM Bool := do getPPMotivesAll opts <||> (← getPPMotivesPi opts <&&> returnsPi motive) <||> (← getPPMotivesNonConst opts <&&> isNonConstFun motive) def withMDataOptions [Inhabited α] (x : DelabM α) : DelabM α := do match ← getExpr with | Expr.mdata m .. => let mut posOpts := (← read).optionsPerPos let pos ← getPos for (k, v) in m do if (`pp).isPrefixOf k then let opts := posOpts.find? pos |>.getD {} posOpts := posOpts.insert pos (opts.insert k v) withReader ({ · with optionsPerPos := posOpts }) $ withMDataExpr x | _ => x partial def withMDatasOptions [Inhabited α] (x : DelabM α) : DelabM α := do if (← getExpr).isMData then withMDataOptions (withMDatasOptions x) else x def isRegularApp : DelabM Bool := do let e ← getExpr if not (unfoldMDatas e.getAppFn).isConst then return false if ← withNaryFn (withMDatasOptions (getPPOption getPPUniverses <||> getPPOption getPPAnalysisBlockImplicit)) then return false for i in [:e.getAppNumArgs] do if ← withNaryArg i (getPPOption getPPAnalysisNamedArg) then return false return true def unexpandRegularApp (stx : Syntax) : Delab := do let Expr.const c .. ← pure (unfoldMDatas (← getExpr).getAppFn) | unreachable! let fs ← appUnexpanderAttribute.getValues (← getEnv) c fs.firstM fun f => match f stx |>.run () with | EStateM.Result.ok stx _ => pure stx | _ => failure -- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β -- abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a def unexpandCoe (stx : Syntax) : Delab := whenPPOption getPPCoercions do if not (← isCoe (← getExpr)) then failure let e ← getExpr match stx with | `($fn $arg) => arg | `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*) | _ => failure def unexpandStructureInstance (stx : Syntax) : Delab := whenPPOption getPPStructureInstances do let env ← getEnv let e ← getExpr let some s ← pure $ e.isConstructorApp? env | failure guard $ isStructure env s.induct; /- If implicit arguments should be shown, and the structure has parameters, we should not pretty print using { ... }, because we will not be able to see the parameters. -/ let fieldNames := getStructureFields env s.induct let mut fields := #[] guard $ fieldNames.size == stx[1].getNumArgs let args := e.getAppArgs let fieldVals := args.extract s.numParams args.size for idx in [:fieldNames.size] do let fieldName := fieldNames[idx] let fieldId := mkIdent fieldName let fieldPos ← nextExtraPos let fieldId := annotatePos fieldPos fieldId addFieldInfo fieldPos (s.induct ++ fieldName) fieldName fieldId fieldVals[idx] let field ← `(structInstField|$fieldId:ident := $(stx[1][idx]):term) fields := fields.push field let tyStx ← withType do if (← getPPOption getPPStructureInstanceType) then delab >>= pure ∘ some else pure none if fields.isEmpty then `({ $[: $tyStx]? }) else let lastField := fields.back fields := fields.pop `({ $[$fields, ]* $lastField $[: $tyStx]? }) @[builtinDelab app] def delabAppImplicit : Delab := do -- TODO: always call the unexpanders, make them guard on the right # args? let paramKinds ← getParamKinds if ← getPPOption getPPExplicit then if paramKinds.any (fun param => !param.isRegularExplicit) then failure let (fnStx, _, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab pure (stx, paramKinds.toList, #[])) (fun (fnStx, paramKinds, argStxs) => do let arg ← getExpr let opts ← getOptions let mkNamedArg (name : Name) (argStx : Syntax) : DelabM Syntax := do `(Parser.Term.namedArgument| ($(← mkIdent name):ident := $argStx:term)) let argStx? : Option Syntax ← if ← getPPOption getPPAnalysisSkip then pure none else if ← getPPOption getPPAnalysisHole then `(_) else match paramKinds with | [] => delab | param :: rest => if param.defVal.isSome && rest.isEmpty then let v := param.defVal.get! if !v.hasLooseBVars && v == arg then none else delab else if !param.isRegularExplicit && param.defVal.isNone then if ← getPPOption getPPAnalysisNamedArg <||> (param.name == `motive <&&> shouldShowMotive arg opts) then mkNamedArg param.name (← delab) else none else delab let argStxs := match argStx? with | none => argStxs | some stx => argStxs.push stx pure (fnStx, paramKinds.tailD [], argStxs)) let stx := Syntax.mkApp fnStx argStxs if ← isRegularApp then (guard (← getPPOption getPPNotation) *> unexpandRegularApp stx) <|> (guard (← getPPOption getPPStructureInstances) *> unexpandStructureInstance stx) <|> (guard (← getPPOption getPPNotation) *> unexpandCoe stx) <|> pure stx else pure stx /-- State for `delabAppMatch` and helpers. -/ structure AppMatchState where info : MatcherInfo matcherTy : Expr params : Array Expr := #[] motive : Option (Syntax × Expr) := none motiveNamed : Bool := false discrs : Array Syntax := #[] varNames : Array (Array Name) := #[] rhss : Array Syntax := #[] -- additional arguments applied to the result of the `match` expression moreArgs : Array Syntax := #[] /-- Extract arguments of motive applications from the matcher type. For the example below: `#[#[`([])], #[`(a::as)]]` -/ private partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) := withReader (fun ctx => { ctx with inPattern := true, optionsPerPos := {} }) do let ty ← instantiateForall st.matcherTy st.params forallTelescope ty fun params _ => do -- skip motive and discriminators let alts := Array.ofSubarray params[1 + st.discrs.size:] alts.mapIdxM fun idx alt => do let ty ← inferType alt -- TODO: this is a hack; we are accessing the expression out-of-sync with the position -- Currently, we reset `optionsPerPos` at the beginning of `delabPatterns` to avoid -- incorrectly considering annotations. withTheReader SubExpr ({ · with expr := ty }) $ usingNames st.varNames[idx] do withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (← delab)) where usingNames {α} (varNames : Array Name) (x : DelabM α) : DelabM α := usingNamesAux 0 varNames x usingNamesAux {α} (i : Nat) (varNames : Array Name) (x : DelabM α) : DelabM α := if i < varNames.size then withBindingBody varNames[i] <| usingNamesAux (i+1) varNames x else x /-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/ private partial def skippingBinders {α} (numParams : Nat) (x : Array Name → DelabM α) : DelabM α := loop numParams #[] where loop : Nat → Array Name → DelabM α | 0, varNames => x varNames | n+1, varNames => do let rec visitLambda : DelabM α := do let varName ← (← getExpr).bindingName!.eraseMacroScopes -- Pattern variables cannot shadow each other if varNames.contains varName then let varName := (← getLCtx).getUnusedName varName withBindingBody varName do loop n (varNames.push varName) else withBindingBodyUnusedName fun id => do loop n (varNames.push id.getId) let e ← getExpr if e.isLambda then visitLambda else -- eta expand `e` let e ← forallTelescopeReducing (← inferType e) fun xs _ => do if xs.size == 1 && (← inferType xs[0]).isConstOf ``Unit then -- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable. -- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable. -- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure -- it adds an annotation to distinguish these two cases. mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit)) else mkLambdaFVars xs (mkAppN e xs) withTheReader SubExpr (fun ctx => { ctx with expr := e }) visitLambda /-- Delaborate applications of "matchers" such as ``` List.map.match_1 : {α : Type _} → (motive : List α → Sort _) → (x : List α) → (Unit → motive List.nil) → ((a : α) → (as : List α) → motive (a :: as)) → motive x ``` -/ @[builtinDelab app] def delabAppMatch : Delab := whenPPOption getPPNotation <| whenPPOption getPPMatch do -- incrementally fill `AppMatchState` from arguments let st ← withAppFnArgs (do let (Expr.const c us _) ← getExpr | failure let (some info) ← getMatcherInfo? c | failure { matcherTy := (← getConstInfo c).instantiateTypeLevelParams us, info := info : AppMatchState }) (fun st => do if st.params.size < st.info.numParams then pure { st with params := st.params.push (← getExpr) } else if st.motive.isNone then -- store motive argument separately let lamMotive ← getExpr let piMotive ← lambdaTelescope lamMotive fun xs body => mkForallFVars xs body -- TODO: pp.analyze has not analyzed `piMotive`, only `lamMotive` -- Thus the binder types won't have any annotations let piStx ← withTheReader SubExpr (fun cfg => { cfg with expr := piMotive }) delab let named ← getPPOption getPPAnalysisNamedArg pure { st with motive := (piStx, lamMotive), motiveNamed := named } else if st.discrs.size < st.info.numDiscrs then pure { st with discrs := st.discrs.push (← delab) } else if st.rhss.size < st.info.altNumParams.size then /- We save the variables names here to be able to implement safe_shadowing. The pattern delaboration must use the names saved here. -/ let (varNames, rhs) ← skippingBinders st.info.altNumParams[st.rhss.size] fun varNames => do let rhs ← delab return (varNames, rhs) pure { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames } else pure { st with moreArgs := st.moreArgs.push (← delab) }) if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then -- underapplied failure match st.discrs, st.rhss with | #[discr], #[] => let stx ← `(nomatch $discr) Syntax.mkApp stx st.moreArgs | _, #[] => failure | _, _ => let pats ← delabPatterns st let stx ← do let (piStx, lamMotive) := st.motive.get! let opts ← getOptions -- TODO: disable the match if other implicits are needed? if ← st.motiveNamed <||> shouldShowMotive lamMotive opts then `(match $[$st.discrs:term],* : $piStx with $[| $pats,* => $st.rhss]*) else `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*) Syntax.mkApp stx st.moreArgs /-- Delaborate applications of the form `(fun x => b) v` as `let_fun x := v; b` -/ def delabLetFun : Delab := do let stxV ← withAppArg delab withAppFn do let Expr.lam n t b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxB ← withBindingBody n delab if ← getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then let stxT ← withBindingDomain delab `(let_fun $(mkIdent n) : $stxT := $stxV; $stxB) else `(let_fun $(mkIdent n) := $stxV; $stxB) @[builtinDelab mdata] def delabMData : Delab := do if let some _ := inaccessible? (← getExpr) then let s ← withMDataExpr delab if (← read).inPattern then `(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns else return s else if isLetFun (← getExpr) && getPPNotation (← getOptions) then withMDataExpr <| delabLetFun else if let some _ := isLHSGoal? (← getExpr) then withMDataExpr <| withAppFn <| withAppArg <| delab else withMDataOptions delab /-- Check for a `Syntax.ident` of the given name anywhere in the tree. This is usually a bad idea since it does not check for shadowing bindings, but in the delaborator we assume that bindings are never shadowed. -/ partial def hasIdent (id : Name) : Syntax → Bool | Syntax.ident _ _ id' _ => id == id' | Syntax.node _ _ args => args.any (hasIdent id) | _ => false /-- Return `true` iff current binder should be merged with the nested binder, if any, into a single binder group: * both binders must have same binder info and domain * they cannot be inst-implicit (`[a b : A]` is not valid syntax) * `pp.binderTypes` must be the same value for both terms * prefer `fun a b` over `fun (a b)` -/ private def shouldGroupWithNext : DelabM Bool := do let e ← getExpr let ppEType ← getPPOption (getPPBinderTypes e) let go (e' : Expr) := do let ppE'Type ← withBindingBody `_ $ getPPOption (getPPBinderTypes e) pure $ e.binderInfo == e'.binderInfo && e.bindingDomain! == e'.bindingDomain! && e'.binderInfo != BinderInfo.instImplicit && ppEType == ppE'Type && (e'.binderInfo != BinderInfo.default || ppE'Type) match e with | Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e' | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e' | _ => pure false where getPPBinderTypes (e : Expr) := if e.isForall then getPPPiBinderTypes else getPPFunBinderTypes private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types. | curNames => do if ← shouldGroupWithNext then -- group with nested binder => recurse immediately withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN) else -- don't group => delab body and prepend current binder group let (stx, stxN) ← withBindingBodyUnusedName fun stxN => do (← delab, stxN) delabGroup (curNames.push stxN) stx @[builtinDelab lam] def delabLam : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let stxT ← withBindingDomain delab let ppTypes ← getPPOption getPPFunBinderTypes let expl ← getPPOption getPPExplicit let usedDownstream ← curNames.any (fun n => hasIdent n.getId stxBody) -- leave lambda implicit if possible -- TODO: for now we just always block implicit lambdas when delaborating. We can revisit. -- Note: the current issue is that it requires state, i.e. if *any* previous binder was implicit, -- it doesn't seem like we can leave a subsequent binder implicit. let blockImplicitLambda := true /- let blockImplicitLambda := expl || e.binderInfo == BinderInfo.default || -- Note: the following restriction fixes many issues with roundtripping, -- but this condition may still not be perfectly in sync with the elaborator. e.binderInfo == BinderInfo.instImplicit || Elab.Term.blockImplicitLambda stxBody || usedDownstream -/ if !blockImplicitLambda then pure stxBody else let group ← match e.binderInfo, ppTypes with | BinderInfo.default, true => -- "default" binder group is the only one that expects binder names -- as a term, i.e. a single `Syntax.ident` or an application thereof let stxCurNames ← if curNames.size > 1 then `($(curNames.get! 0) $(curNames.eraseIdx 0)*) else pure $ curNames.get! 0; `(funBinder| ($stxCurNames : $stxT)) | BinderInfo.default, false => pure curNames.back -- here `curNames.size == 1` | BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT}) | BinderInfo.implicit, false => `(funBinder| {$curNames*}) | BinderInfo.strictImplicit, true => `(funBinder| ⦃$curNames* : $stxT⦄) | BinderInfo.strictImplicit, false => `(funBinder| ⦃$curNames*⦄) | BinderInfo.instImplicit, _ => if usedDownstream then `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1` else `(funBinder| [$stxT]) | _ , _ => unreachable!; match stxBody with | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody) | _ => `(fun $group => $stxBody) @[builtinDelab forallE] def delabForall : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let prop ← try isProp e catch _ => false let stxT ← withBindingDomain delab let group ← match e.binderInfo with | BinderInfo.implicit => `(bracketedBinderF|{$curNames* : $stxT}) | BinderInfo.strictImplicit => `(bracketedBinderF|⦃$curNames* : $stxT⦄) -- here `curNames.size == 1` | BinderInfo.instImplicit => `(bracketedBinderF|[$curNames.back : $stxT]) | _ => -- heuristic: use non-dependent arrows only if possible for whole group to avoid -- noisy mix like `(α : Type) → Type → (γ : Type) → ...`. let dependent := curNames.any $ fun n => hasIdent n.getId stxBody -- NOTE: non-dependent arrows are available only for the default binder info if dependent then if prop && !(← getPPOption getPPPiBinderTypes) then return ← `(∀ $curNames:ident*, $stxBody) else `(bracketedBinderF|($curNames* : $stxT)) else return ← curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody if prop then match stxBody with | `(∀ $groups*, $stxBody) => `(∀ $group $groups*, $stxBody) | _ => `(∀ $group, $stxBody) else `($group:bracketedBinder → $stxBody) @[builtinDelab letE] def delabLetE : Delab := do let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxV ← descend v 1 delab let stxB ← withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 delab if ← getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then let stxT ← descend t 0 delab `(let $(mkIdent n) : $stxT := $stxV; $stxB) else `(let $(mkIdent n) := $stxV; $stxB) @[builtinDelab lit] def delabLit : Delab := do let Expr.lit l _ ← getExpr | unreachable! match l with | Literal.natVal n => pure $ quote n | Literal.strVal s => pure $ quote s -- `@OfNat.ofNat _ n _` ~> `n` @[builtinDelab app.OfNat.ofNat] def delabOfNat : Delab := whenPPOption getPPCoercions do let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) ← getExpr | failure return quote n -- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true` @[builtinDelab app.OfScientific.ofScientific] def delabOfScientific : Delab := whenPPOption getPPCoercions do let expr ← getExpr guard <| expr.getAppNumArgs == 5 let Expr.lit (Literal.natVal m) _ ← pure (expr.getArg! 2) | failure let Expr.lit (Literal.natVal e) _ ← pure (expr.getArg! 4) | failure let s ← match expr.getArg! 3 with | Expr.const `Bool.true _ _ => pure true | Expr.const `Bool.false _ _ => pure false | _ => failure let str := toString m if s && e == str.length then return Syntax.mkScientificLit ("0." ++ str) else if s && e < str.length then let mStr := str.extract 0 (str.length - e) let eStr := str.extract (str.length - e) str.length return Syntax.mkScientificLit (mStr ++ "." ++ eStr) else return Syntax.mkScientificLit (str ++ "e" ++ (if s then "-" else "") ++ toString e) /-- Delaborate a projection primitive. These do not usually occur in user code, but are pretty-printed when e.g. `#print`ing a projection function. -/ @[builtinDelab proj] def delabProj : Delab := do let Expr.proj _ idx _ _ ← getExpr | unreachable! let e ← withProj delab -- not perfectly authentic: elaborates to the `idx`-th named projection -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual -- `proj`. let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1)); `($(e).$idx:fieldIdx) /-- Delaborate a call to a projection function such as `Prod.fst`. -/ @[builtinDelab app] def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do let e@(Expr.app fn _ _) ← getExpr | failure let Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure let env ← getEnv let some info ← pure $ env.getProjectionFnInfo? c | failure -- can't use with classes since the instance parameter is implicit guard $ !info.fromClass -- projection function should be fully applied (#struct params + 1 instance parameter) -- TODO: support over-application guard $ e.getAppNumArgs == info.numParams + 1 -- If pp.explicit is true, and the structure has parameters, we should not -- use field notation because we will not be able to see the parameters. let expl ← getPPOption getPPExplicit guard $ !expl || info.numParams == 0 let appStx ← withAppArg delab `($(appStx).$(mkIdent f):ident) @[builtinDelab app.dite] def delabDIte : Delab := whenPPOption getPPNotation do -- Note: we keep this as a delaborator for now because it actually accesses the expression. guard $ (← getExpr).getAppNumArgs == 5 let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab let (t, h) ← withAppFn $ withAppArg $ delabBranch none let (e, _) ← withAppArg $ delabBranch h `(if $(mkIdent h):ident : $c then $t else $e) where delabBranch (h? : Option Name) : DelabM (Syntax × Name) := do let e ← getExpr guard e.isLambda let h ← match h? with | some h => return (← withBindingBody h delab, h) | none => withBindingBodyUnusedName fun h => do return (← delab, h.getId) @[builtinDelab app.namedPattern] def delabNamedPattern : Delab := do -- Note: we keep this as a delaborator because it accesses the DelabM context guard (← read).inPattern guard $ (← getExpr).getAppNumArgs == 3 let x ← withAppFn $ withAppArg delab let p ← withAppArg delab guard x.isIdent `($x:ident@$p:term) -- Sigma and PSigma delaborators def delabSigmaCore (sigma : Bool) : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 2 guard $ (← getExpr).appArg!.isLambda withAppArg do let α ← withBindingDomain delab let bodyExpr := (← getExpr).bindingBody! withBindingBodyUnusedName fun n => do let b ← delab if bodyExpr.hasLooseBVars then if sigma then `(($n:ident : $α) × $b) else `(($n:ident : $α) ×' $b) else if sigma then `((_ : $α) × $b) else `((_ : $α) ×' $b) @[builtinDelab app.Sigma] def delabSigma : Delab := delabSigmaCore (sigma := true) @[builtinDelab app.PSigma] def delabPSigma : Delab := delabSigmaCore (sigma := false) partial def delabDoElems : DelabM (List Syntax) := do let e ← getExpr if e.isAppOfArity `Bind.bind 6 then -- Bind.bind.{u, v} : {m : Type u → Type v} → [self : Bind m] → {α β : Type u} → m α → (α → m β) → m β let α := e.getAppArgs[2] let ma ← withAppFn $ withAppArg delab withAppArg do match (← getExpr) with | Expr.lam _ _ body _ => withBindingBodyUnusedName fun n => do if body.hasLooseBVars then prependAndRec `(doElem|let $n:term ← $ma:term) else if α.isConstOf `Unit || α.isConstOf `PUnit then prependAndRec `(doElem|$ma:term) else prependAndRec `(doElem|let _ ← $ma:term) | _ => failure else if e.isLet then let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxT ← descend t 0 delab let stxV ← descend v 1 delab withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 $ prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV) else let stx ← delab [←`(doElem|$stx:term)] where prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems @[builtinDelab app.Bind.bind] def delabDo : Delab := whenPPOption getPPNotation do guard <| (← getExpr).isAppOfArity `Bind.bind 6 let elems ← delabDoElems let items ← elems.toArray.mapM (`(doSeqItem|$(·):doElem)) `(do $items:doSeqItem*) def reifyName : Expr → DelabM Name | Expr.const ``Lean.Name.anonymous .. => Name.anonymous | Expr.app (Expr.app (Expr.const ``Lean.Name.mkStr ..) n _) (Expr.lit (Literal.strVal s) _) _ => do (← reifyName n).mkStr s | Expr.app (Expr.app (Expr.const ``Lean.Name.mkNum ..) n _) (Expr.lit (Literal.natVal i) _) _ => do (← reifyName n).mkNum i | _ => failure @[builtinDelab app.Lean.Name.mkStr] def delabNameMkStr : Delab := whenPPOption getPPNotation do let n ← reifyName (← getExpr) -- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!"`{n}"] @[builtinDelab app.Lean.Name.mkNum] def delabNameMkNum : Delab := delabNameMkStr end Lean.PrettyPrinter.Delaborator
e1b6c3975fcfb116ab432987c53113bd9985250d
c777c32c8e484e195053731103c5e52af26a25d1
/counterexamples/linear_order_with_pos_mul_pos_eq_zero.lean
6e08c5f9f847f451787435f5987042be48c19607
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
2,190
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Damiano Testa, Kevin Buzzard -/ import algebra.order.monoid.defs import algebra.order.monoid.with_zero.defs /-! An example of a `linear_ordered_comm_monoid_with_zero` in which the product of two positive elements vanishes. This is the monoid with 3 elements `0, ε, 1` where `ε ^ 2 = 0` and everything else is forced. The order is `0 < ε < 1`. Since `ε ^ 2 = 0`, the product of strictly positive elements can vanish. Relevant Zulip chat: https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/mul_pos -/ /-- The three element monoid. -/ @[derive [decidable_eq]] inductive foo | zero | eps | one namespace foo instance inhabited : inhabited foo := ⟨zero⟩ instance : has_zero foo := ⟨zero⟩ instance : has_one foo := ⟨one⟩ local notation `ε` := eps /-- The order on `foo` is the one induced by the natural order on the image of `aux1`. -/ def aux1 : foo → ℕ | 0 := 0 | ε := 1 | 1 := 2 /-- A tactic to prove facts by cases. -/ meta def boom : tactic unit := `[repeat {rintro ⟨⟩}; dec_trivial] lemma aux1_inj : function.injective aux1 := by boom instance : linear_order foo := linear_order.lift' aux1 aux1_inj /-- Multiplication on `foo`: the only external input is that `ε ^ 2 = 0`. -/ def mul : foo → foo → foo | 1 x := x | x 1 := x | _ _ := 0 instance : comm_monoid foo := { mul := mul, one := 1, one_mul := by boom, mul_one := by boom, mul_comm := by boom, mul_assoc := by boom } instance : linear_ordered_comm_monoid_with_zero foo := { zero := 0, zero_mul := by boom, mul_zero := by boom, mul_le_mul_left := by { rintro ⟨⟩ ⟨⟩ h ⟨⟩; revert h; dec_trivial }, zero_le_one := dec_trivial, .. foo.linear_order, .. foo.comm_monoid } lemma not_mul_pos : ¬ ∀ {M : Type} [linear_ordered_comm_monoid_with_zero M], by exactI ∀ (a b : M) (ha : 0 < a) (hb : 0 < b), 0 < a * b := begin intros h, specialize h ε ε (by boom) (by boom), exact (lt_irrefl 0 (h.trans_le (by boom))).elim, end example : 0 < ε ∧ ε * ε = 0 := by boom end foo
cbb1699ea004d10086a3951e78e605eec5da6a77
9dc8cecdf3c4634764a18254e94d43da07142918
/counterexamples/linear_order_with_pos_mul_pos_eq_zero.lean
8484b0d9cf9172ffb3611f5dc0daca8a8b2fe9ac
[ "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
2,136
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Damiano Testa, Kevin Buzzard -/ import algebra.order.monoid /-! An example of a `linear_ordered_comm_monoid_with_zero` in which the product of two positive elements vanishes. This is the monoid with 3 elements `0, ε, 1` where `ε ^ 2 = 0` and everything else is forced. The order is `0 < ε < 1`. Since `ε ^ 2 = 0`, the product of strictly positive elements can vanish. Relevant Zulip chat: https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/mul_pos -/ /-- The three element monoid. -/ @[derive [decidable_eq]] inductive foo | zero | eps | one namespace foo instance inhabited : inhabited foo := ⟨zero⟩ instance : has_zero foo := ⟨zero⟩ instance : has_one foo := ⟨one⟩ notation `ε` := eps /-- The order on `foo` is the one induced by the natural order on the image of `aux1`. -/ def aux1 : foo → ℕ | 0 := 0 | ε := 1 | 1 := 2 /-- A tactic to prove facts by cases. -/ meta def boom : tactic unit := `[repeat {rintro ⟨⟩}; dec_trivial] lemma aux1_inj : function.injective aux1 := by boom instance : linear_order foo := linear_order.lift' aux1 aux1_inj /-- Multiplication on `foo`: the only external input is that `ε ^ 2 = 0`. -/ def mul : foo → foo → foo | 1 x := x | x 1 := x | _ _ := 0 instance : comm_monoid foo := { mul := mul, one := 1, one_mul := by boom, mul_one := by boom, mul_comm := by boom, mul_assoc := by boom } instance : linear_ordered_comm_monoid_with_zero foo := { zero := 0, zero_mul := by boom, mul_zero := by boom, mul_le_mul_left := by { rintro ⟨⟩ ⟨⟩ h ⟨⟩; revert h; dec_trivial }, zero_le_one := dec_trivial, .. foo.linear_order, .. foo.comm_monoid } lemma not_mul_pos : ¬ ∀ {M : Type} [linear_ordered_comm_monoid_with_zero M], by exactI ∀ (a b : M) (ha : 0 < a) (hb : 0 < b), 0 < a * b := begin intros h, specialize h ε ε (by boom) (by boom), exact (lt_irrefl 0 (h.trans_le (by boom))).elim, end example : 0 < ε ∧ ε * ε = 0 := by boom end foo
9d40f45f80273b5e726a5f77f50cff948b9417d3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/eisenstein_criterion.lean
9dcce2f4139fe98a522dccba21746f271deacbd8
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
5,397
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.ideal.operations import data.polynomial.ring_division import tactic.apply_fun import ring_theory.prime /-! # Eisenstein's criterion A proof of a slight generalisation of Eisenstein's criterion for the irreducibility of a polynomial over an integral domain. -/ open polynomial ideal.quotient variables {R : Type*} [integral_domain R] namespace polynomial namespace eisenstein_criterion_aux /- Section for auxiliary lemmas used in the proof of `irreducible_of_eisenstein_criterion`-/ lemma map_eq_C_mul_X_pow_of_forall_coeff_mem {f : polynomial R} {P : ideal R} (hfP : ∀ (n : ℕ), ↑n < f.degree → f.coeff n ∈ P) (hf0 : f ≠ 0) : map (mk P) f = C ((mk P) f.leading_coeff) * X ^ f.nat_degree := polynomial.ext (λ n, begin rcases lt_trichotomy ↑n (degree f) with h | h | h, { erw [coeff_map, eq_zero_iff_mem.2 (hfP n h), coeff_C_mul, coeff_X_pow, if_neg, mul_zero], rintro rfl, exact not_lt_of_ge degree_le_nat_degree h }, { have : nat_degree f = n, from nat_degree_eq_of_degree_eq_some h.symm, rw [coeff_C_mul, coeff_X_pow, if_pos this.symm, mul_one, leading_coeff, this, coeff_map] }, { rw [coeff_eq_zero_of_degree_lt, coeff_eq_zero_of_degree_lt], { refine lt_of_le_of_lt (degree_C_mul_X_pow_le _ _) _, rwa ← degree_eq_nat_degree hf0 }, { exact lt_of_le_of_lt (degree_map_le _) h } } end) lemma le_nat_degree_of_map_eq_mul_X_pow {n : ℕ} {P : ideal R} (hP : P.is_prime) {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hc0 : c.degree = 0) : n ≤ q.nat_degree := with_bot.coe_le_coe.1 (calc ↑n = degree (q.map (mk P)) : by rw [hq, degree_mul, hc0, zero_add, degree_pow, degree_X, nsmul_one, nat.cast_with_bot] ... ≤ degree q : degree_map_le _ ... ≤ nat_degree q : degree_le_nat_degree) lemma eval_zero_mem_ideal_of_eq_mul_X_pow {n : ℕ} {P : ideal R} {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hn0 : 0 < n) : eval 0 q ∈ P := by rw [← coeff_zero_eq_eval_zero, ← eq_zero_iff_mem, ← coeff_map, coeff_zero_eq_eval_zero, hq, eval_mul, eval_pow, eval_X, zero_pow hn0, mul_zero] lemma is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit {p q : polynomial R} (hu : ∀ (x : R), C x ∣ p * q → is_unit x) (hpm : p.nat_degree = 0) : is_unit p := begin rw [eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm), is_unit_C], refine hu _ _, rw [← eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm)], exact dvd_mul_right _ _ end end eisenstein_criterion_aux open eisenstein_criterion_aux /-- If `f` is a non constant polynomial with coefficients in `R`, and `P` is a prime ideal in `R`, then if every coefficient in `R` except the leading coefficient is in `P`, and the trailing coefficient is not in `P^2` and no non units in `R` divide `f`, then `f` is irreducible. -/ theorem irreducible_of_eisenstein_criterion {f : polynomial R} {P : ideal R} (hP : P.is_prime) (hfl : f.leading_coeff ∉ P) (hfP : ∀ n : ℕ, ↑n < degree f → f.coeff n ∈ P) (hfd0 : 0 < degree f) (h0 : f.coeff 0 ∉ P^2) (hu : ∀ x : R, C x ∣ f → is_unit x) : irreducible f := have hf0 : f ≠ 0, from λ _, by simp only [*, not_true, submodule.zero_mem, coeff_zero] at *, have hf : f.map (mk P) = C (mk P (leading_coeff f)) * X ^ nat_degree f, from map_eq_C_mul_X_pow_of_forall_coeff_mem hfP hf0, have hfd0 : 0 < f.nat_degree, from with_bot.coe_lt_coe.1 (lt_of_lt_of_le hfd0 degree_le_nat_degree), ⟨mt degree_eq_zero_of_is_unit (λ h, by simp only [*, lt_irrefl] at *), begin rintros p q rfl, rw [map_mul] at hf, rcases mul_eq_mul_prime_pow (show prime (X : polynomial (ideal.quotient P)), from prime_of_degree_eq_one_of_monic degree_X monic_X) hf with ⟨m, n, b, c, hmnd, hbc, hp, hq⟩, have hmn : 0 < m → 0 < n → false, { assume hm0 hn0, refine h0 _, rw [coeff_zero_eq_eval_zero, eval_mul, pow_two], exact ideal.mul_mem_mul (eval_zero_mem_ideal_of_eq_mul_X_pow hp hm0) (eval_zero_mem_ideal_of_eq_mul_X_pow hq hn0) }, have hpql0 : (mk P) (p * q).leading_coeff ≠ 0, { rwa [ne.def, eq_zero_iff_mem] }, have hp0 : p ≠ 0, from λ h, by simp only [*, zero_mul, eq_self_iff_true, not_true, ne.def] at *, have hq0 : q ≠ 0, from λ h, by simp only [*, eq_self_iff_true, not_true, ne.def, mul_zero] at *, have hbc0 : degree b = 0 ∧ degree c = 0, { apply_fun degree at hbc, rwa [degree_C hpql0, degree_mul, eq_comm, nat.with_bot.add_eq_zero_iff] at hbc }, have hmp : m ≤ nat_degree p, from le_nat_degree_of_map_eq_mul_X_pow hP hp hbc0.1, have hnq : n ≤ nat_degree q, from le_nat_degree_of_map_eq_mul_X_pow hP hq hbc0.2, have hpmqn : p.nat_degree = m ∧ q.nat_degree = n, { rw [nat_degree_mul hp0 hq0] at hmnd, clear_except hmnd hmp hnq, omega }, obtain rfl | rfl : m = 0 ∨ n = 0, { rwa [nat.pos_iff_ne_zero, nat.pos_iff_ne_zero, imp_false, not_not, ← or_iff_not_imp_left] at hmn }, { exact or.inl (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit hu hpmqn.1) }, { exact or.inr (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit (by simpa only [mul_comm] using hu) hpmqn.2) } end⟩ end polynomial
8960748776ab7c0f649ddce21bef6ef2bbb49bbc
4fa118f6209450d4e8d058790e2967337811b2b5
/src/sheaves/f_map.lean
488dfc5fa39d1a5608056993029a97bcd1aa3c34
[ "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
10,099
lean
import for_mathlib.open_embeddings import sheaves.sheaf_of_topological_rings import sheaves.stalk_of_rings universe variable u open topological_space variables {X : Type u} {Y : Type u} {Z : Type u} variables [topological_space X] [topological_space Y] [topological_space Z] namespace presheaf_of_rings variables {F : presheaf_of_rings X} {G : presheaf_of_rings Y} {H : presheaf_of_rings Z} structure f_map (F : presheaf_of_rings X) (G : presheaf_of_rings Y) := (f : X → Y) (hf : continuous f) (f_flat : ∀ V : opens Y, G V → F (hf.comap V)) (f_flat_is_ring_hom : ∀ V : opens Y, is_ring_hom (f_flat V)) (presheaf_f_flat : ∀ V W : opens Y, ∀ (hWV : W ⊆ V), ∀ s : G V, F.res _ _ (hf.comap_mono hWV) (f_flat V s) = f_flat W (G.res V W hWV s)) attribute [instance] f_map.f_flat_is_ring_hom def f_map_id (F : presheaf_of_rings X) : presheaf_of_rings.f_map F F := { f := λ x, x, hf := continuous_id, f_flat := λ U, F.res _ _ (λ _ hx, hx), f_flat_is_ring_hom := λ U, presheaf_of_rings.res_is_ring_hom _ _ _ _, presheaf_f_flat := λ U V hVU s, begin rw ←F.to_presheaf.Hcomp', rw ←F.to_presheaf.Hcomp', end } def f_map.comp (a : presheaf_of_rings.f_map F G) (b : presheaf_of_rings.f_map G H) : presheaf_of_rings.f_map F H := { f := λ x, b.f (a.f x), hf := b.hf.comp a.hf, f_flat := λ V s, (a.f_flat (b.hf.comap V)) ((b.f_flat V) s), f_flat_is_ring_hom := λ V, show (is_ring_hom ((a.f_flat (b.hf.comap V)) ∘ (b.f_flat V))), from is_ring_hom.comp _ _, presheaf_f_flat := λ V W hWV s, begin rw ←b.presheaf_f_flat V W hWV s, rw ←a.presheaf_f_flat (b.hf.comap V) (b.hf.comap W) (b.hf.comap_mono hWV), refl, end } @[simp] lemma f_map.id_comp (a : presheaf_of_rings.f_map F G) : (presheaf_of_rings.f_map_id F).comp a = a := begin cases a, delta presheaf_of_rings.f_map_id presheaf_of_rings.f_map.comp, congr, funext V s, dsimp, show _ = id _, apply congr_fun, exact F.to_presheaf.Hid _, end @[simp] lemma f_map.comp_id (a : presheaf_of_rings.f_map F G) : a.comp (presheaf_of_rings.f_map_id G) = a := begin cases a with f hf f_flat f_flat_is_ring_hom presheaf_f_flat, delta presheaf_of_rings.f_map_id presheaf_of_rings.f_map.comp, congr, funext V s, dsimp, rw ← presheaf_f_flat, show _ = id _, apply congr_fun, exact F.to_presheaf.Hid _, end end presheaf_of_rings namespace presheaf_of_topological_rings variables {F : presheaf_of_topological_rings X} {G : presheaf_of_topological_rings Y} {H : presheaf_of_topological_rings Z} structure f_map (F : presheaf_of_topological_rings X) (G : presheaf_of_topological_rings Y) := (f : X → Y) (hf : continuous f) (f_flat : ∀ V : opens Y, G V → F (hf.comap V)) [f_flat_is_ring_hom : ∀ V : opens Y, is_ring_hom (f_flat V)] (cont_f_flat : ∀ V : opens Y, continuous (f_flat V)) (presheaf_f_flat : ∀ V W : opens Y, ∀ (hWV : W ⊆ V), ∀ s : G V, F.res _ _ (hf.comap_mono hWV) (f_flat V s) = f_flat W (G.res V W hWV s)) instance f_map_flat.is_ring_hom (f : presheaf_of_topological_rings.f_map F G) (V : opens Y) : is_ring_hom (f.f_flat V) := f.f_flat_is_ring_hom V attribute [instance] presheaf_of_topological_rings.f_map.f_flat_is_ring_hom def f_map.to_presheaf_of_rings_f_map {X : Type u} [topological_space X] {Y : Type u} [topological_space Y] {F : presheaf_of_topological_rings X} {G : presheaf_of_topological_rings Y} (f : presheaf_of_topological_rings.f_map F G) : presheaf_of_rings.f_map F.to_presheaf_of_rings G.to_presheaf_of_rings := { ..f} @[ext] lemma presheaf_of_topological_rings.f_map.ext {X : Type u} [topological_space X] {Y : Type u} [topological_space Y] {F : presheaf_of_topological_rings X} {G : presheaf_of_topological_rings Y} (a b : F.f_map G) (h : a.to_presheaf_of_rings_f_map = b.to_presheaf_of_rings_f_map) : a = b := begin cases a, cases b, dsimp [f_map.to_presheaf_of_rings_f_map] at h, injections, simp [*] end @[simp] lemma f_map.to_presheaf_of_rings_f_map_f (f : presheaf_of_topological_rings.f_map F G) : f.to_presheaf_of_rings_f_map.f = f.f := rfl def f_map_id (F : presheaf_of_topological_rings X) : presheaf_of_topological_rings.f_map F F := { cont_f_flat := λ U, begin show continuous (((F.to_presheaf_of_rings).to_presheaf).res U (continuous.comap continuous_id U) _), convert continuous_id, { simp [continuous.comap_id U] }, { simp [continuous.comap_id U] }, convert heq_of_eq (F.Hid U), rw continuous.comap_id U, exact continuous.comap_id U, end, ..presheaf_of_rings.f_map_id F.to_presheaf_of_rings } @[simp] lemma f_map.to_presheaf_of_rings_f_map_id (F : presheaf_of_topological_rings X) : (presheaf_of_topological_rings.f_map_id F).to_presheaf_of_rings_f_map = presheaf_of_rings.f_map_id F.to_presheaf_of_rings := rfl @[simp] lemma f_map_id_apply (F : presheaf_of_topological_rings X) (x : X) : (presheaf_of_topological_rings.f_map_id F).f x = x := rfl def f_map.comp (a : presheaf_of_topological_rings.f_map F G) (b : presheaf_of_topological_rings.f_map G H) : presheaf_of_topological_rings.f_map F H := { cont_f_flat := λ V, (a.cont_f_flat _).comp (b.cont_f_flat _), .. a.to_presheaf_of_rings_f_map.comp b.to_presheaf_of_rings_f_map } @[simp] lemma f_map.comp_f (a : presheaf_of_topological_rings.f_map F G) (b : presheaf_of_topological_rings.f_map G H) : (a.comp b).f = b.f ∘ a.f := rfl @[simp] lemma f_map.comp_to_presheaf_of_rings_f_map (a : presheaf_of_topological_rings.f_map F G) (b : presheaf_of_topological_rings.f_map G H) : (a.comp b).to_presheaf_of_rings_f_map = a.to_presheaf_of_rings_f_map.comp b.to_presheaf_of_rings_f_map := rfl @[simp] lemma f_map.id_comp (a : presheaf_of_topological_rings.f_map F G) : (presheaf_of_topological_rings.f_map_id F).comp a = a := by ext; simp @[simp] lemma f_map.comp_id (a : presheaf_of_topological_rings.f_map F G) : a.comp (presheaf_of_topological_rings.f_map_id G) = a := by ext; simp end presheaf_of_topological_rings open_locale classical /-- The map on stalks induced from an f-map -/ noncomputable def stalk_map {F : presheaf_of_rings X} {G : presheaf_of_rings Y} (f : F.f_map G) (x : X) : stalk_of_rings G (f.f x) → stalk_of_rings F x := to_stalk.rec G (f.f x) (stalk_of_rings F x) (λ V hfx s, ⟦⟨f.hf.comap V, hfx, f.f_flat V s⟩⟧) (λ V W H r hfx, quotient.sound begin use [f.hf.comap V, hfx, set.subset.refl _, f.hf.comap_mono H], erw F.to_presheaf.Hid, symmetry, apply f.presheaf_f_flat end ) namespace stalk_map variables {F : presheaf_of_rings X} {G : presheaf_of_rings Y} {H : presheaf_of_rings Z} variables (f : F.f_map G) (g : G.f_map H) instance (F : presheaf_of_rings X) (x : X) : comm_ring (quotient (stalk.setoid (F.to_presheaf) x)) := stalk_of_rings_is_comm_ring F x instance f_flat_is_ring_hom (x : X) (V : opens Y) (hfx : f.f x ∈ V) : is_ring_hom (λ (s : G.F V), (⟦⟨f.hf.comap V, hfx, f.f_flat V s⟩⟧ : stalk_of_rings F x)) := begin show is_ring_hom ((to_stalk F x (f.hf.comap V) hfx) ∘ (f.f_flat V)), refine is_ring_hom.comp _ _, end instance (x : X) : is_ring_hom (stalk_map f x) := to_stalk.rec_is_ring_hom _ _ _ _ _ @[simp] lemma stalk_map_id (F : presheaf_of_rings X) (x : X) (s : stalk_of_rings F x) : stalk_map (presheaf_of_rings.f_map_id F) x s = s := begin induction s, apply quotient.sound, use s.U, use s.HxU, use (le_refl s.U), use (le_refl s.U), symmetry, convert (F.to_presheaf.Hcomp' _ _ _ _ _ s.s), refl, end @[simp] lemma stalk_map_id' (F : presheaf_of_rings X) (x : X) : stalk_map (presheaf_of_rings.f_map_id F) x = id := by ext; apply stalk_map_id lemma stalk_map_comp (x : X) (s : stalk_of_rings H (g.f (f.f x))) : stalk_map (f.comp g) x s = stalk_map f x (stalk_map g (f.f x) s) := begin induction s, apply quotient.sound, use f.hf.comap (g.hf.comap s.U), use s.HxU, existsi _, swap, intros t ht, exact ht, existsi _, swap, intros t ht, exact ht, refl, refl, end @[simp] lemma stalk_map_comp' (x : X) : stalk_map (f.comp g) x = (stalk_map f x) ∘ (stalk_map g (f.f x)) := by ext; apply stalk_map_comp end stalk_map namespace presheaf_of_rings def restrict (U : opens X) (G : presheaf_of_rings X) : presheaf_of_rings U := { F := λ V, G.F (topological_space.opens.map U V), res := λ V W HWV, G.res _ _ (topological_space.opens.map_mono HWV), Hid := λ V, G.Hid (topological_space.opens.map U V), Hcomp := λ V₁ V₂ V₃ H12 H23, G.Hcomp (topological_space.opens.map U V₁) (topological_space.opens.map U V₂) (topological_space.opens.map U V₃) (topological_space.opens.map_mono H12) (topological_space.opens.map_mono H23), Fring := λ V, G.Fring (topological_space.opens.map U V), res_is_ring_hom := λ V W HWV, G.res_is_ring_hom (topological_space.opens.map U V) (topological_space.opens.map U W) (topological_space.opens.map_mono HWV) } variables {U : opens X} (G : presheaf_of_rings X) (u : U) noncomputable def restrict_stalk_map : stalk_of_rings (G.restrict U) u → stalk_of_rings G u := to_stalk.rec (G.restrict U) u (stalk_of_rings G u) (λ V hu, to_stalk G u (topological_space.opens.map U V) ( opens.map_mem_of_mem hu)) (λ W V HWV s huW, quotient.sound (begin use [(topological_space.opens.map U W), opens.map_mem_of_mem huW], use [(set.subset.refl (topological_space.opens.map U W)), topological_space.opens.map_mono HWV], rw G.Hid (topological_space.opens.map U W), refl, end)) instance : is_ring_hom (G.restrict_stalk_map u) := by delta restrict_stalk_map; apply_instance end presheaf_of_rings def presheaf_of_topological_rings.restrict (U : opens X) (G : presheaf_of_topological_rings X) : presheaf_of_topological_rings U := { Ftop := λ V, G.Ftop (topological_space.opens.map U V), Ftop_ring := λ V, G.Ftop_ring (topological_space.opens.map U V), res_continuous := λ V W HWV, G.res_continuous (topological_space.opens.map U V) (topological_space.opens.map U W) (topological_space.opens.map_mono HWV), ..presheaf_of_rings.restrict U G.to_presheaf_of_rings }
594c219cb039bdeb202e45741287c48a5a11d625
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/category_theory/limits/functor_category.lean
d077e795c172673fc3bfd7aaff0260e509e880dc
[ "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
4,788
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.products import category_theory.limits.preserves open category_theory category_theory.category namespace category_theory.limits universes u v variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 variables {J K : Type v} [small_category J] [small_category K] @[simp] lemma cone.functor_w {F : J ⥤ (K ⥤ C)} (c : cone F) {j j' : J} (f : j ⟶ j') (k : K) : (c.π.app j).app k ≫ (F.map f).app k = (c.π.app j').app k := by convert ←nat_trans.congr_app (c.π.naturality f).symm k; apply id_comp @[simp] lemma cocone.functor_w {F : J ⥤ (K ⥤ C)} (c : cocone F) {j j' : J} (f : j ⟶ j') (k : K) : (F.map f).app k ≫ (c.ι.app j').app k = (c.ι.app j).app k := by convert ←nat_trans.congr_app (c.ι.naturality f) k; apply comp_id @[simp] def functor_category_limit_cone [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) : cone F := { X := F.flip ⋙ lim, π := { app := λ j, { app := λ k, limit.π (F.flip.obj k) j }, naturality' := λ j j' f, by ext k; convert (limit.w (F.flip.obj k) _).symm using 1; apply id_comp } } @[simp] def functor_category_colimit_cocone [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) : cocone F := { X := F.flip ⋙ colim, ι := { app := λ j, { app := λ k, colimit.ι (F.flip.obj k) j }, naturality' := λ j j' f, by ext k; convert (colimit.w (F.flip.obj k) _) using 1; apply comp_id } } @[simp] def evaluate_functor_category_limit_cone [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : ((evaluation K C).obj k).map_cone (functor_category_limit_cone F) ≅ limit.cone (F.flip.obj k) := cones.ext (iso.refl _) (by tidy) @[simp] def evaluate_functor_category_colimit_cocone [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : ((evaluation K C).obj k).map_cocone (functor_category_colimit_cocone F) ≅ colimit.cocone (F.flip.obj k) := cocones.ext (iso.refl _) (by tidy) def functor_category_is_limit_cone [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) : is_limit (functor_category_limit_cone F) := { lift := λ s, { app := λ k, limit.lift (F.flip.obj k) (((evaluation K C).obj k).map_cone s), naturality' := λ k k' f, by ext; dsimp; simpa using (s.π.app j).naturality f }, uniq' := λ s m w, begin ext1 k, exact is_limit.uniq _ (((evaluation K C).obj k).map_cone s) (m.app k) (λ j, nat_trans.congr_app (w j) k) end } def functor_category_is_colimit_cocone [has_colimits_of_shape.{u v} J C] (F : J ⥤ K ⥤ C) : is_colimit (functor_category_colimit_cocone F) := { desc := λ s, { app := λ k, colimit.desc (F.flip.obj k) (((evaluation K C).obj k).map_cocone s), naturality' := λ k k' f, begin ext, rw [←assoc, ←assoc], dsimp [functor.flip], simpa using (s.ι.app j).naturality f end }, uniq' := λ s m w, begin ext1 k, exact is_colimit.uniq _ (((evaluation K C).obj k).map_cocone s) (m.app k) (λ j, nat_trans.congr_app (w j) k) end } instance functor_category_has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (K ⥤ C) := λ F, { cone := functor_category_limit_cone F, is_limit := functor_category_is_limit_cone F } instance functor_category_has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (K ⥤ C) := λ F, { cocone := functor_category_colimit_cocone F, is_colimit := functor_category_is_colimit_cocone F } instance functor_category_has_limits [has_limits C] : has_limits (K ⥤ C) := λ J 𝒥, by resetI; apply_instance instance functor_category_has_colimits [has_colimits C] : has_colimits (K ⥤ C) := λ J 𝒥, by resetI; apply_instance instance evaluation_preserves_limits_of_shape [has_limits_of_shape J C] (k : K) : preserves_limits_of_shape J ((evaluation K C).obj k) := λ F, preserves_limit_of_preserves_limit_cone (limit.is_limit _) $ is_limit.of_iso_limit (limit.is_limit _) (evaluate_functor_category_limit_cone F k).symm instance evaluation_preserves_colimits_of_shape [has_colimits_of_shape J C] (k : K) : preserves_colimits_of_shape J ((evaluation K C).obj k) := λ F, preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit _) $ is_colimit.of_iso_colimit (colimit.is_colimit _) (evaluate_functor_category_colimit_cocone F k).symm instance evaluation_preserves_limits [has_limits C] (k : K) : preserves_limits ((evaluation K C).obj k) := λ J 𝒥, by resetI; apply_instance instance evaluation_preserves_colimits [has_colimits C] (k : K) : preserves_colimits ((evaluation K C).obj k) := λ J 𝒥, by resetI; apply_instance end category_theory.limits
64110e384ba30dc38ff9d651a1e3d922dc4cab67
2d34dfb0a1cc250584282618dc10ea03d3fa858e
/src/for_mathlib/add_monoid_hom.lean
44bcce7198410d803aceef30b26d0f3fcbfeec1e
[]
no_license
zeta1999/lean-liquid
61e294ec5adae959d8ee1b65d015775484ff58c2
96bb0fa3afc3b451bcd1fb7d974348de2f290541
refs/heads/master
1,676,579,150,248
1,610,771,445,000
1,610,771,445,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
815
lean
import algebra.group.hom import algebra.big_operators open_locale big_operators namespace add_monoid_hom variables {M₁ M₂ : Type*} section variables [add_monoid M₁] [add_comm_monoid M₂] @[simp] lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → (M₁ →+ M₂)) (m : M₁) : (∑ i in s, f i) m = ∑ i in s, (f i m) := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty, zero_apply] }, { intros i s his IH, simp only [his, IH, finset.sum_insert, not_false_iff, add_apply] } end end section variables [add_monoid M₁] [add_comm_group M₂] @[simp] lemma gsmul_apply (n : ℤ) (f : (M₁ →+ M₂)) (m : M₁) : (n •ℤ f) m = n •ℤ (f m) := show eval m (n •ℤ f) = n •ℤ eval m f, from add_monoid_hom.map_gsmul _ _ _ end end add_monoid_hom
0705441c73e04dbc341c7758a02438917853dabd
5883d9218e6f144e20eee6ca1dab8529fa1a97c0
/src/aeq/id.lean
1ebcdbdadd3ac37af5cd244f29c2092c25a90d0f
[]
no_license
spl/alpha-conversion-is-easy
0d035bc570e52a6345d4890e4d0c9e3f9b8126c1
ed937fe85d8495daffd9412a5524c77b9fcda094
refs/heads/master
1,607,649,280,020
1,517,380,240,000
1,517,380,240,000
52,174,747
4
0
null
1,456,052,226,000
1,456,001,163,000
Lean
UTF-8
Lean
false
false
1,853
lean
/- This file contains declarations related to `aeq` identity or reflexivity. -/ import .equiv namespace acie ----------------------------------------------------------------- namespace aeq ------------------------------------------------------------------ variables {V : Type} [decidable_eq V] -- Type of variable names variables {vs : Type → Type} [vset vs V] -- Type of variable name sets variables {X : vs V} -- Variable name sets -- Identity `aeq` with an implicit `vset`. @[inline, reducible] protected def id : exp X → exp X → Prop := aeq (vrel.id X) -- Notation for `aeq.id`. infix ` ≡α `:50 := aeq.id namespace id ------------------------------------------------------------------- -- Paper: Corollary 3 -- Reflexivity of `aeq.id` @[refl] protected theorem refl : ∀ (e : exp X), aeq (vrel.id X) e e := aeq.refl -- Symmetry of `aeq.id` @[symm] protected theorem symm ⦃e₁ e₂ : exp X⦄ : aeq (vrel.id X) e₁ e₂ → aeq (vrel.id X) e₂ e₁ := λ a, map.simple (λ x₁ x₂, vrel.inv.of_id) (aeq.symm a) -- Transitivity of `aeq.id` @[trans] protected theorem trans ⦃e₁ e₂ e₃ : exp X⦄ : aeq (vrel.id X) e₁ e₂ → aeq (vrel.id X) e₂ e₃ → aeq (vrel.id X) e₁ e₃ := λ a₁ a₂, map.simple (λ x₁ x₂, vrel.id.of_comp) (aeq.trans a₁ a₂) -- Equivalence protected theorem equiv (X : vs V) : equivalence (aeq (vrel.id X)) := mk_equivalence (aeq (vrel.id X)) (@id.refl _ _ _ _ X) (@id.symm _ _ _ _ X) (@id.trans _ _ _ _ X) -- Setoid instance setoid (X : vs V) : setoid (exp X) := setoid.mk (aeq (vrel.id X)) (id.equiv X) end /- namespace -/ id --------------------------------------------------------- end /- namespace -/ aeq -------------------------------------------------------- end /- namespace -/ acie -------------------------------------------------------
776c32829432509c8de622912bd3a436d6178183
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/struct1.lean
f6cc3037f4e9b21fd7485df6dc19822abaef0959
[ "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
983
lean
-- structure A (α : Type) := (x : α) structure B (α : Type) := (x : α) structure S : Nat := -- error expected Type (x : Nat) structure S extends Nat → Nat := -- error expected structure (x : Nat) set_option structureDiamondWarning true in structure S' extends A Nat, A Bool := -- error field toA already declared (x : Nat) structure S extends A Nat, B Bool := -- error field `x` from `B` has already been declared (x : Nat) structure S1 := (_x : Nat) structure S2 := (x _y : Nat) structure S := (x : Nat) (x : Nat) -- error structure S extends A Nat := (x : Nat) -- error structure S extends A Nat := (x := true) -- error type mismatch structure S extends A Nat := (x : Bool := true) -- error omit type structure S := (x : Nat := true) -- error type mismatch private structure S := private mk :: (x : Nat) private structure S := protected mk :: (x : Nat) private structure S := protected (x : Nat) private structure S := mk2 :: (x : Nat) #check S #check S.mk2
8bc69d36aa0c03cc0f2c217cbe71138cb9540584
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/InfoTree/Main.lean
bad0d0a48ffc22c6cc5a5a9802ef3d2f38225802
[ "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
15,844
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Leonardo de Moura, Sebastian Ullrich -/ import Lean.Meta.PPGoal namespace Lean.Elab.ContextInfo variable [Monad m] [MonadEnv m] [MonadMCtx m] [MonadOptions m] [MonadResolveName m] [MonadNameGenerator m] def saveNoFileMap : m ContextInfo := return { env := (← getEnv) fileMap := default mctx := (← getMCtx) options := (← getOptions) currNamespace := (← getCurrNamespace) openDecls := (← getOpenDecls) ngen := (← getNGen) } def save [MonadFileMap m] : m ContextInfo := do let ctx ← saveNoFileMap return { ctx with fileMap := (← getFileMap) } end ContextInfo def CompletionInfo.stx : CompletionInfo → Syntax | dot i .. => i.stx | id stx .. => stx | dotId stx .. => stx | fieldId stx .. => stx | namespaceId stx => stx | option stx => stx | endSection stx .. => stx | tactic stx .. => stx def CustomInfo.format : CustomInfo → Format | i => f!"CustomInfo({i.value.typeName})" instance : ToFormat CustomInfo := ⟨CustomInfo.format⟩ partial def InfoTree.findInfo? (p : Info → Bool) (t : InfoTree) : Option Info := match t with | context _ t => findInfo? p t | node i ts => if p i then some i else ts.findSome? (findInfo? p) | _ => none /-- Instantiate the holes on the given `tree` with the assignment table. (analoguous to instantiating the metavariables in an expression) -/ partial def InfoTree.substitute (tree : InfoTree) (assignment : PersistentHashMap MVarId InfoTree) : InfoTree := match tree with | node i c => node i <| c.map (substitute · assignment) | context i t => context i (substitute t assignment) | hole id => match assignment.find? id with | none => hole id | some tree => substitute tree assignment def ContextInfo.runMetaM (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : IO α := do let x := x.run { lctx := lctx } { mctx := info.mctx } /- We must execute `x` using the `ngen` stored in `info`. Otherwise, we may create `MVarId`s and `FVarId`s that have been used in `lctx` and `info.mctx`. -/ let ((a, _), _) ← x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls, fileName := "<InfoTree>", fileMap := default } { env := info.env, ngen := info.ngen } return a def ContextInfo.toPPContext (info : ContextInfo) (lctx : LocalContext) : PPContext := { env := info.env, mctx := info.mctx, lctx := lctx, opts := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } def ContextInfo.ppSyntax (info : ContextInfo) (lctx : LocalContext) (stx : Syntax) : IO Format := do ppTerm (info.toPPContext lctx) ⟨stx⟩ -- HACK: might not be a term private def formatStxRange (ctx : ContextInfo) (stx : Syntax) : Format := let pos := stx.getPos?.getD 0 let endPos := stx.getTailPos?.getD pos f!"{fmtPos pos stx.getHeadInfo}-{fmtPos endPos stx.getTailInfo}" where fmtPos pos info := let pos := format <| ctx.fileMap.toPosition pos match info with | .original .. => pos | .synthetic (canonical := true) .. => f!"{pos}†!" | _ => f!"{pos}†" private def formatElabInfo (ctx : ContextInfo) (info : ElabInfo) : Format := if info.elaborator.isAnonymous then formatStxRange ctx info.stx else f!"{formatStxRange ctx info.stx} @ {info.elaborator}" def TermInfo.runMetaM (info : TermInfo) (ctx : ContextInfo) (x : MetaM α) : IO α := ctx.runMetaM info.lctx x def TermInfo.format (ctx : ContextInfo) (info : TermInfo) : IO Format := do info.runMetaM ctx do let ty : Format ← try Meta.ppExpr (← Meta.inferType info.expr) catch _ => pure "<failed-to-infer-type>" return f!"{← Meta.ppExpr info.expr} {if info.isBinder then "(isBinder := true) " else ""}: {ty} @ {formatElabInfo ctx info.toElabInfo}" def CompletionInfo.format (ctx : ContextInfo) (info : CompletionInfo) : IO Format := match info with | .dot i (expectedType? := expectedType?) .. => return f!"[.] {← i.format ctx} : {expectedType?}" | .id stx _ _ lctx expectedType? => ctx.runMetaM lctx do return f!"[.] {stx} : {expectedType?} @ {formatStxRange ctx info.stx}" | _ => return f!"[.] {info.stx} @ {formatStxRange ctx info.stx}" def CommandInfo.format (ctx : ContextInfo) (info : CommandInfo) : IO Format := do return f!"command @ {formatElabInfo ctx info.toElabInfo}" def OptionInfo.format (ctx : ContextInfo) (info : OptionInfo) : IO Format := do return f!"option {info.optionName} @ {formatStxRange ctx info.stx}" def FieldInfo.format (ctx : ContextInfo) (info : FieldInfo) : IO Format := do ctx.runMetaM info.lctx do return f!"{info.fieldName} : {← Meta.ppExpr (← Meta.inferType info.val)} := {← Meta.ppExpr info.val} @ {formatStxRange ctx info.stx}" def ContextInfo.ppGoals (ctx : ContextInfo) (goals : List MVarId) : IO Format := if goals.isEmpty then return "no goals" else ctx.runMetaM {} (return Std.Format.prefixJoin "\n" (← goals.mapM (Meta.ppGoal ·))) def TacticInfo.format (ctx : ContextInfo) (info : TacticInfo) : IO Format := do let ctxB := { ctx with mctx := info.mctxBefore } let ctxA := { ctx with mctx := info.mctxAfter } let goalsBefore ← ctxB.ppGoals info.goalsBefore let goalsAfter ← ctxA.ppGoals info.goalsAfter return f!"Tactic @ {formatElabInfo ctx info.toElabInfo}\n{info.stx}\nbefore {goalsBefore}\nafter {goalsAfter}" def MacroExpansionInfo.format (ctx : ContextInfo) (info : MacroExpansionInfo) : IO Format := do let stx ← ctx.ppSyntax info.lctx info.stx let output ← ctx.ppSyntax info.lctx info.output return f!"Macro expansion\n{stx}\n===>\n{output}" def UserWidgetInfo.format (info : UserWidgetInfo) : Format := f!"UserWidget {info.widgetId}\n{Std.ToFormat.format info.props}" def FVarAliasInfo.format (info : FVarAliasInfo) : Format := f!"FVarAlias {info.userName.eraseMacroScopes}" def FieldRedeclInfo.format (ctx : ContextInfo) (info : FieldRedeclInfo) : Format := f!"FieldRedecl @ {formatStxRange ctx info.stx}" def Info.format (ctx : ContextInfo) : Info → IO Format | ofTacticInfo i => i.format ctx | ofTermInfo i => i.format ctx | ofCommandInfo i => i.format ctx | ofMacroExpansionInfo i => i.format ctx | ofOptionInfo i => i.format ctx | ofFieldInfo i => i.format ctx | ofCompletionInfo i => i.format ctx | ofUserWidgetInfo i => pure <| i.format | ofCustomInfo i => pure <| Std.ToFormat.format i | ofFVarAliasInfo i => pure <| i.format | ofFieldRedeclInfo i => pure <| i.format ctx def Info.toElabInfo? : Info → Option ElabInfo | ofTacticInfo i => some i.toElabInfo | ofTermInfo i => some i.toElabInfo | ofCommandInfo i => some i.toElabInfo | ofMacroExpansionInfo _ => none | ofOptionInfo _ => none | ofFieldInfo _ => none | ofCompletionInfo _ => none | ofUserWidgetInfo _ => none | ofCustomInfo _ => none | ofFVarAliasInfo _ => none | ofFieldRedeclInfo _ => none /-- Helper function for propagating the tactic metavariable context to its children nodes. We need this function because we preserve `TacticInfo` nodes during backtracking *and* their children. Moreover, we backtrack the metavariable context to undo metavariable assignments. `TacticInfo` nodes save the metavariable context before/after the tactic application, and can be pretty printed without any extra information. This is not the case for `TermInfo` nodes. Without this function, the formatting method would often fail when processing `TermInfo` nodes that are children of `TacticInfo` nodes that have been preserved during backtracking. Saving the metavariable context at `TermInfo` nodes is also not a good option because at `TermInfo` creation time, the metavariable context often miss information, e.g., a TC problem has not been resolved, a postponed subterm has not been elaborated, etc. See `Term.SavedState.restore`. -/ def Info.updateContext? : Option ContextInfo → Info → Option ContextInfo | some ctx, ofTacticInfo i => some { ctx with mctx := i.mctxAfter } | ctx?, _ => ctx? partial def InfoTree.format (tree : InfoTree) (ctx? : Option ContextInfo := none) : IO Format := do match tree with | hole id => return .nestD f!"• ?{toString id.name}" | context i t => format t i | node i cs => match ctx? with | none => return "• <context-not-available>" | some ctx => let fmt ← i.format ctx if cs.size == 0 then return .nestD f!"• {fmt}" else let ctx? := i.updateContext? ctx? return .nestD f!"• {fmt}{Std.Format.prefixJoin .line (← cs.toList.mapM fun c => format c ctx?)}" section variable [Monad m] [MonadInfoTree m] @[inline] private def modifyInfoTrees (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit := modifyInfoState fun s => { s with trees := f s.trees } /-- Returns the current array of InfoTrees and resets it to an empty array. -/ def getResetInfoTrees : m (PersistentArray InfoTree) := do let trees := (← getInfoState).trees modifyInfoTrees fun _ => {} return trees def pushInfoTree (t : InfoTree) : m Unit := do if (← getInfoState).enabled then modifyInfoTrees fun ts => ts.push t def pushInfoLeaf (t : Info) : m Unit := do if (← getInfoState).enabled then pushInfoTree <| InfoTree.node (children := {}) t def addCompletionInfo (info : CompletionInfo) : m Unit := do pushInfoLeaf <| Info.ofCompletionInfo info def addConstInfo [MonadEnv m] [MonadError m] (stx : Syntax) (n : Name) (expectedType? : Option Expr := none) : m Unit := do pushInfoLeaf <| .ofTermInfo { elaborator := .anonymous lctx := .empty expr := (← mkConstWithLevelParams n) stx expectedType? } /-- This does the same job as `resolveGlobalConstNoOverload`; resolving an identifier syntax to a unique fully resolved name or throwing if there are ambiguities. But also adds this resolved name to the infotree. This means that when you hover over a name in the sourcefile you will see the fully resolved name in the hover info.-/ def resolveGlobalConstNoOverloadWithInfo [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m Name := do let n ← resolveGlobalConstNoOverload id if (← getInfoState).enabled then -- we do not store a specific elaborator since identifiers are special-cased by the server anyway addConstInfo id n expectedType? return n /-- Similar to `resolveGlobalConstNoOverloadWithInfo`, except if there are multiple name resolutions then it returns them as a list. -/ def resolveGlobalConstWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m (List Name) := do let ns ← resolveGlobalConst id if (← getInfoState).enabled then for n in ns do addConstInfo id n expectedType? return ns /-- Similar to `resolveGlobalName`, but it also adds the resolved name to the info tree. -/ def resolveGlobalNameWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (ref : Syntax) (id : Name) : m (List (Name × List String)) := do let ns ← resolveGlobalName id if (← getInfoState).enabled then for (n, _) in ns do addConstInfo ref n return ns /-- Use this to descend a node on the infotree that is being built. It saves the current list of trees `t₀` and resets it and then runs `x >>= mkInfo`, producing either an `i : Info` or a hole id. Running `x >>= mkInfo` will modify the trees state and produce a new list of trees `t₁`. In the `i : Info` case, `t₁` become the children of a node `node i t₁` that is appended to `t₀`. -/ def withInfoContext' [MonadFinally m] (x : m α) (mkInfo : α → m (Sum Info MVarId)) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => do match a? with | none => modifyInfoTrees fun _ => treesSaved | some a => let info ← mkInfo a modifyInfoTrees fun trees => match info with | Sum.inl info => treesSaved.push <| InfoTree.node info trees | Sum.inr mvarId => treesSaved.push <| InfoTree.hole mvarId else x /-- Saves the current list of trees `t₀`, runs `x` to produce a new tree list `t₁` and runs `mkInfoTree t₁` to get `n : InfoTree` and then restores the trees to be `t₀ ++ [n]`.-/ def withInfoTreeContext [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let tree ← mkInfoTree st.trees modifyInfoTrees fun _ => treesSaved.push tree else x /-- Run `x` as a new child infotree node with header given by `mkInfo`. -/ @[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α := do withInfoTreeContext x (fun trees => do return InfoTree.node (← mkInfo) trees) /-- Resets the trees state `t₀`, runs `x` to produce a new trees state `t₁` and sets the state to be `t₀ ++ (InfoTree.context Γ <$> t₁)` where `Γ` is the context derived from the monad state. -/ def withSaveInfoContext [MonadNameGenerator m] [MonadFinally m] [MonadEnv m] [MonadOptions m] [MonadMCtx m] [MonadResolveName m] [MonadFileMap m] (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let trees ← st.trees.mapM fun tree => do let tree := tree.substitute st.assignment pure <| InfoTree.context (← ContextInfo.save) tree modifyInfoTrees fun _ => treesSaved ++ trees else x def getInfoHoleIdAssignment? (mvarId : MVarId) : m (Option InfoTree) := return (← getInfoState).assignment[mvarId] def assignInfoHoleId (mvarId : MVarId) (infoTree : InfoTree) : m Unit := do assert! (← getInfoHoleIdAssignment? mvarId).isNone modifyInfoState fun s => { s with assignment := s.assignment.insert mvarId infoTree } end def withMacroExpansionInfo [MonadFinally m] [Monad m] [MonadInfoTree m] [MonadLCtx m] (stx output : Syntax) (x : m α) : m α := let mkInfo : m Info := do return Info.ofMacroExpansionInfo { lctx := (← getLCtx) stx, output } withInfoContext x mkInfo @[inline] def withInfoHole [MonadFinally m] [Monad m] [MonadInfoTree m] (mvarId : MVarId) (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => modifyInfoState fun s => if h : s.trees.size > 0 then have : s.trees.size - 1 < s.trees.size := Nat.sub_lt h (by decide) { s with trees := treesSaved, assignment := s.assignment.insert mvarId s.trees[s.trees.size - 1] } else { s with trees := treesSaved } else x def enableInfoTree [MonadInfoTree m] (flag := true) : m Unit := modifyInfoState fun s => { s with enabled := flag } def withEnableInfoTree [Monad m] [MonadInfoTree m] [MonadFinally m] (flag : Bool) (x : m α) : m α := do let saved := (← getInfoState).enabled try enableInfoTree flag x finally enableInfoTree saved def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) := return (← getInfoState).trees end Lean.Elab
b6b5ce4e410ab6f0f7330b2c752b81127ff1a530
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/yoneda.lean
65dd54a9e3b4489fb63e383b005e7413ea5afa87
[ "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
5,498
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.functor_category import tactic.assert_exists /-! # Limit properties relating to the (co)yoneda embedding. We calculate the colimit of `Y ↦ (X ⟶ Y)`, which is just `punit`. (This is used in characterising cofinal functors.) We also show the (co)yoneda embeddings preserve limits and jointly reflect them. -/ open opposite open category_theory open category_theory.limits universes w v u namespace category_theory namespace coyoneda variables {C : Type v} [small_category C] /-- The colimit cocone over `coyoneda.obj X`, with cocone point `punit`. -/ @[simps] def colimit_cocone (X : Cᵒᵖ) : cocone (coyoneda.obj X) := { X := punit, ι := { app := by tidy, } } /-- The proposed colimit cocone over `coyoneda.obj X` is a colimit cocone. -/ @[simps] def colimit_cocone_is_colimit (X : Cᵒᵖ) : is_colimit (colimit_cocone X) := { desc := λ s x, s.ι.app (unop X) (𝟙 _), fac' := λ s Y, by { ext f, convert congr_fun (s.w f).symm (𝟙 (unop X)), simp, }, uniq' := λ s m w, by { ext ⟨⟩, rw ← w, simp, } } instance (X : Cᵒᵖ) : has_colimit (coyoneda.obj X) := has_colimit.mk { cocone := _, is_colimit := colimit_cocone_is_colimit X } /-- The colimit of `coyoneda.obj X` is isomorphic to `punit`. -/ noncomputable def colimit_coyoneda_iso (X : Cᵒᵖ) : colimit (coyoneda.obj X) ≅ punit := colimit.iso_colimit_cocone { cocone := _, is_colimit := colimit_cocone_is_colimit X } end coyoneda variables {C : Type u} [category.{v} C] open limits /-- The yoneda embedding `yoneda.obj X : Cᵒᵖ ⥤ Type v` for `X : C` preserves limits. -/ instance yoneda_preserves_limits (X : C) : preserves_limits (yoneda.obj X) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ K, { preserves := λ c t, { lift := λ s x, quiver.hom.unop (t.lift ⟨op X, λ j, (s.π.app j x).op, λ j₁ j₂ α, _⟩), fac' := λ s j, funext $ λ x, quiver.hom.op_inj (t.fac _ _), uniq' := λ s m w, funext $ λ x, begin refine quiver.hom.op_inj (t.uniq ⟨op X, _, _⟩ _ (λ j, _)), { dsimp, simp [← s.w α] }, -- See library note [dsimp, simp] { exact quiver.hom.unop_inj (congr_fun (w j) x) }, end } } } } /-- The coyoneda embedding `coyoneda.obj X : C ⥤ Type v` for `X : Cᵒᵖ` preserves limits. -/ instance coyoneda_preserves_limits (X : Cᵒᵖ) : preserves_limits (coyoneda.obj X) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ K, { preserves := λ c t, { lift := λ s x, t.lift ⟨unop X, λ j, s.π.app j x, λ j₁ j₂ α, by { dsimp, simp [← s.w α]}⟩, -- See library note [dsimp, simp] fac' := λ s j, funext $ λ x, t.fac _ _, uniq' := λ s m w, funext $ λ x, begin refine (t.uniq ⟨unop X, _⟩ _ (λ j, _)), exact congr_fun (w j) x, end } } } } /-- The yoneda embeddings jointly reflect limits. -/ def yoneda_jointly_reflects_limits (J : Type w) [small_category J] (K : J ⥤ Cᵒᵖ) (c : cone K) (t : Π (X : C), is_limit ((yoneda.obj X).map_cone c)) : is_limit c := let s' : Π (s : cone K), cone (K ⋙ yoneda.obj s.X.unop) := λ s, ⟨punit, λ j _, (s.π.app j).unop, λ j₁ j₂ α, funext $ λ _, quiver.hom.op_inj (s.w α).symm⟩ in { lift := λ s, ((t s.X.unop).lift (s' s) punit.star).op, fac' := λ s j, quiver.hom.unop_inj (congr_fun ((t s.X.unop).fac (s' s) j) punit.star), uniq' := λ s m w, begin apply quiver.hom.unop_inj, suffices : (λ (x : punit), m.unop) = (t s.X.unop).lift (s' s), { apply congr_fun this punit.star }, apply (t _).uniq (s' s) _ (λ j, _), ext, exact quiver.hom.op_inj (w j), end } /-- The coyoneda embeddings jointly reflect limits. -/ def coyoneda_jointly_reflects_limits (J : Type w) [small_category J] (K : J ⥤ C) (c : cone K) (t : Π (X : Cᵒᵖ), is_limit ((coyoneda.obj X).map_cone c)) : is_limit c := let s' : Π (s : cone K), cone (K ⋙ coyoneda.obj (op s.X)) := λ s, ⟨punit, λ j _, s.π.app j, λ j₁ j₂ α, funext $ λ _, (s.w α).symm⟩ in { lift := λ s, (t (op s.X)).lift (s' s) punit.star, fac' := λ s j, congr_fun ((t _).fac (s' s) j) punit.star, uniq' := λ s m w, begin suffices : (λ (x : punit), m) = (t _).lift (s' s), { apply congr_fun this punit.star }, apply (t _).uniq (s' s) _ (λ j, _), ext, exact (w j), end } variables {D : Type u} [small_category D] instance yoneda_functor_preserves_limits : preserves_limits (@yoneda D _) := begin apply preserves_limits_of_evaluation, intro K, change preserves_limits (coyoneda.obj K), apply_instance end instance coyoneda_functor_preserves_limits : preserves_limits (@coyoneda D _) := begin apply preserves_limits_of_evaluation, intro K, change preserves_limits (yoneda.obj K), apply_instance end instance yoneda_functor_reflects_limits : reflects_limits (@yoneda D _) := limits.fully_faithful_reflects_limits _ instance coyoneda_functor_reflects_limits : reflects_limits (@coyoneda D _) := limits.fully_faithful_reflects_limits _ end category_theory -- We don't need to have developed any algebra or set theory to reach (at least) this point -- in the category theory hierarchy. assert_not_exists set.range assert_not_exists add_comm_monoid
e06b994e6443a23c0b0285da4ec2228534dbb0a9
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/witt_vector/witt_polynomial.lean
5d2ba835a6a6d59559841072a8bf7806b977fcce
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
10,592
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import algebra.invertible import data.mv_polynomial.variables import data.mv_polynomial.comm_ring import data.mv_polynomial.expand import data.zmod.basic open mv_polynomial open finset (hiding map) open finsupp (single) open_locale big_operators local attribute [-simp] coe_eval₂_hom variables (p : ℕ) variables (R : Type*) [comm_ring R] /-! # Witt polynomials To endow `witt_vector p R` with a ring structure, we need to study the so-called Witt polynomials. Fix a base value `p : ℕ`. The `p`-adic Witt polynomials are an infinite family of polynomials indexed by a natural number `n`, taking values in an arbitrary ring `R`. The variables of these polynomials are represented by natural numbers. The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`, with exactly these variables when `R` has characteristic `0`. These polynomials are used to define the addition and multiplication operators on the type of Witt vectors. (While this type itself is not complicated, the ring operations are what make it interesting.) When the base `p` is invertible in `R`, the `p`-adic Witt polynomials form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis. ## Main declarations * `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R` * `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial, which upon being bound to the Witt polynomials yields `X n`. * `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that `bind₁ (X_in_terms_of_W p R) (W_ R n) = X n` * `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement ## Notation In this file we use the following notation * `p` is a natural number, typically assumed to be prime. * `R` and `S` are commutative rings * `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial -/ /-- `witt_polynomial p R n` is the `n`-th Witt polynomial with respect to a prime `p` with coefficients in a commutative ring `R`. It is defined as: `∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/ noncomputable def witt_polynomial (n : ℕ) : mv_polynomial ℕ R := ∑ i in range (n+1), monomial (single i (p ^ (n - i))) (p ^ i) lemma witt_polynomial_eq_sum_C_mul_X_pow (n : ℕ) : witt_polynomial p R n = ∑ i in range (n+1), C (p ^ i : R) * X i ^ (p ^ (n - i)) := begin apply sum_congr rfl, rintro i -, rw [monomial_eq, finsupp.prod_single_index], rw pow_zero, end /-! We set up notation locally to this file, to keep statements short and comprehensible. This allows us to simply write `W n` or `W_ ℤ n`. -/ -- Notation with ring of coefficients explicit localized "notation `W_` := witt_polynomial p" in witt -- Notation with ring of coefficients implicit localized "notation `W` := witt_polynomial p _" in witt open_locale witt open mv_polynomial /- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring. If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial over the target ring. -/ section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map_witt_polynomial (f : R →+* S) (n : ℕ) : map f (W n) = W n := begin rw [witt_polynomial, ring_hom.map_sum, witt_polynomial, sum_congr rfl], intros i hi, rw [map_monomial, ring_hom.map_pow, ring_hom.map_nat_cast], end variables (R) @[simp] lemma constant_coeff_witt_polynomial [hp : fact p.prime] (n : ℕ) : constant_coeff (witt_polynomial p R n) = 0 := begin simp only [witt_polynomial, ring_hom.map_sum, constant_coeff_monomial], rw [sum_eq_zero], rintro i hi, rw [if_neg], rw [finsupp.single_eq_zero], exact ne_of_gt (pow_pos hp.pos _) end @[simp] lemma witt_polynomial_zero : witt_polynomial p R 0 = X 0 := by simp only [witt_polynomial, X, sum_singleton, range_one, pow_zero] @[simp] lemma witt_polynomial_one : witt_polynomial p R 1 = C ↑p * X 1 + (X 0) ^ p := by simp only [witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ, range_one, sum_singleton, one_mul, pow_one, C_1, pow_zero] lemma aeval_witt_polynomial {A : Type*} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) : aeval f (W_ R n) = ∑ i in range (n+1), p^i * (f i) ^ (p ^ (n-i)) := by simp [witt_polynomial, alg_hom.map_sum, aeval_monomial, finsupp.prod_single_index] /-- Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial by expanding the `n`th witt polynomial by `p`. -/ @[simp] lemma witt_polynomial_zmod_self (n : ℕ) : W_ (zmod (p ^ (n + 1))) (n + 1) = expand p (W_ (zmod (p^(n + 1))) n) := begin simp only [witt_polynomial_eq_sum_C_mul_X_pow], rw [sum_range_succ, ← nat.cast_pow, char_p.cast_eq_zero (zmod (p^(n+1))) (p^(n+1)), C_0, zero_mul, zero_add, alg_hom.map_sum, sum_congr rfl], intros k hk, rw [alg_hom.map_mul, alg_hom.map_pow, expand_X, alg_hom_C, ← pow_mul, ← pow_succ], congr, rw mem_range at hk, omega end section p_prime -- in fact, `0 < p` would be sufficient variables [hp : fact p.prime] include hp lemma witt_polynomial_vars [char_zero R] (n : ℕ) : (witt_polynomial p R n).vars = range (n + 1) := begin have : ∀ i, (monomial (finsupp.single i (p ^ (n - i))) (p ^ i : R)).vars = {i}, { intro i, rw vars_monomial_single, { rw ← nat.pos_iff_ne_zero, apply pow_pos hp.pos }, { rw [← nat.cast_pow, nat.cast_ne_zero], apply ne_of_gt, apply pow_pos hp.pos i } }, rw [witt_polynomial, vars_sum_of_disjoint], { simp only [this, int.nat_cast_eq_coe_nat, bind_singleton_eq_self], }, { simp only [this, int.nat_cast_eq_coe_nat], intros a b h, apply singleton_disjoint.mpr, rwa mem_singleton, }, end lemma witt_polynomial_vars_subset (n : ℕ) : (witt_polynomial p R n).vars ⊆ range (n + 1) := begin rw [← map_witt_polynomial p (int.cast_ring_hom R), ← witt_polynomial_vars p ℤ], apply vars_map, end end p_prime end /-! ## Witt polynomials as a basis of the polynomial algebra If `p` is invertible in `R`, then the Witt polynomials form a basis of the polynomial algebra `mv_polynomial ℕ R`. The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction. -/ /-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials that corresponds to the ordinary `X n`. -/ noncomputable def X_in_terms_of_W [invertible (p : R)] : ℕ → mv_polynomial ℕ R | n := (X n - (∑ i : fin n, have _ := i.2, (C (p^(i : ℕ) : R) * (X_in_terms_of_W i)^(p^(n-i))))) * C (⅟p ^ n : R) lemma X_in_terms_of_W_eq [invertible (p : R)] {n : ℕ} : X_in_terms_of_W p R n = (X n - (∑ i in range n, C (p^i : R) * X_in_terms_of_W p R i ^ p ^ (n - i))) * C (⅟p ^ n : R) := by { rw [X_in_terms_of_W, ← fin.sum_univ_eq_sum_range] } @[simp] lemma constant_coeff_X_in_terms_of_W [hp : fact p.prime] [invertible (p : R)] (n : ℕ) : constant_coeff (X_in_terms_of_W p R n) = 0 := begin apply nat.strong_induction_on n; clear n, intros n IH, rw [X_in_terms_of_W_eq, mul_comm, ring_hom.map_mul, ring_hom.map_sub, ring_hom.map_sum, constant_coeff_C, sum_eq_zero], { simp only [constant_coeff_X, sub_zero, mul_zero] }, { intros m H, rw mem_range at H, simp only [ring_hom.map_mul, ring_hom.map_pow, constant_coeff_C, IH m H], rw [zero_pow, mul_zero], apply pow_pos hp.pos, } end @[simp] lemma X_in_terms_of_W_zero [invertible (p : R)] : X_in_terms_of_W p R 0 = X 0 := by rw [X_in_terms_of_W_eq, range_zero, sum_empty, pow_zero, C_1, mul_one, sub_zero] section p_prime variables [hp : fact p.prime] include hp lemma X_in_terms_of_W_vars_aux (n : ℕ) : n ∈ (X_in_terms_of_W p ℚ n).vars ∧ (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := begin apply nat.strong_induction_on n, clear n, intros n ih, rw [X_in_terms_of_W_eq, mul_comm, vars_C_mul, vars_sub_of_disjoint, vars_X, range_succ, insert_eq], swap 3, { apply nonzero_of_invertible }, work_on_goal 0 { simp only [true_and, true_or, eq_self_iff_true, mem_union, mem_singleton], intro i, rw [mem_union, mem_union], apply or.imp id }, work_on_goal 1 { rw [vars_X, singleton_disjoint] }, all_goals { intro H, replace H := vars_sum_subset _ _ H, rw mem_bind at H, rcases H with ⟨j, hj, H⟩, rw vars_C_mul at H, swap, { apply pow_ne_zero, exact_mod_cast hp.ne_zero }, rw mem_range at hj, replace H := (ih j hj).2 (vars_pow _ _ H), rw mem_range at H }, { rw mem_range, exact lt_of_lt_of_le H hj }, { exact lt_irrefl n (lt_of_lt_of_le H hj) }, end lemma X_in_terms_of_W_vars_subset (n : ℕ) : (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := (X_in_terms_of_W_vars_aux p n).2 end p_prime lemma X_in_terms_of_W_aux [invertible (p : R)] (n : ℕ) : X_in_terms_of_W p R n * C (p^n : R) = X n - ∑ i in range n, C (p^i : R) * (X_in_terms_of_W p R i)^p^(n-i) := by rw [X_in_terms_of_W_eq, mul_assoc, ← C_mul, ← mul_pow, inv_of_mul_self, one_pow, C_1, mul_one] @[simp] lemma bind₁_X_in_terms_of_W_witt_polynomial [invertible (p : R)] (k : ℕ) : bind₁ (X_in_terms_of_W p R) (W_ R k) = X k := begin rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum], simp only [alg_hom.map_pow, C_pow, alg_hom.map_mul, alg_hom_C], rw [sum_range_succ, nat.sub_self, pow_zero, pow_one, bind₁_X_right, mul_comm, ← C_pow, X_in_terms_of_W_aux], simp only [C_pow, bind₁_X_right, sub_add_cancel], end @[simp] lemma bind₁_witt_polynomial_X_in_terms_of_W [invertible (p : R)] (n : ℕ) : bind₁ (W_ R) (X_in_terms_of_W p R n) = X n := begin apply nat.strong_induction_on n, clear n, intros n H, rw [X_in_terms_of_W_eq, alg_hom.map_mul, alg_hom.map_sub, bind₁_X_right, alg_hom_C, alg_hom.map_sum], have : W_ R n - ∑ i in range n, C (p ^ i : R) * (X i) ^ p ^ (n - i) = C (p ^ n : R) * X n, by simp only [witt_polynomial_eq_sum_C_mul_X_pow, nat.sub_self, sum_range_succ, pow_one, add_sub_cancel, pow_zero], rw [sum_congr rfl, this], { -- this is really slow for some reason rw [mul_right_comm, ← C_mul, ← mul_pow, mul_inv_of_self, one_pow, C_1, one_mul] }, { intros i h, rw mem_range at h, simp only [alg_hom.map_mul, alg_hom.map_pow, alg_hom_C, H i h] }, end
af5382d5d1a811d12d81d13ab724da544716c90c
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/ExamPractice/quiz1.lean
91bc5d613617fefe6ef9fd562ee2b9114869deb2
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
416
lean
-- Derek Johnson def s1 := "Hello, " def s2 := "Nifty!" def s3 := s1 ++ s2 theorem t1 : (s1 ++ s2) = s3 := eq.refl s3 theorem t2 : 4^2 = 16 := eq.refl 16 theorem t3 : (s1 ++ s2) = s3 ∧ (5^2 = 25) := and.intro (eq.refl s3) (eq.refl 25) theorem t4 : ∀ (P Q R : Prop), (P ∧ Q) ∧ (Q ∧ R) → (P ∧ R) := λ (P Q R : Prop), λ h, and.intro (h.left.left)(h.right.right)
b44ef53d9b436b4d95e3b8bd69e1ac09fb2fb662
be30445afb85fcb2041b437059d21f9a84dff894
/move_to_main.hlean
aa2a6d005a7e456e5948e66475cc8466b9fda79a
[ "Apache-2.0" ]
permissive
EgbertRijke/GraphModel
784efde97299c4f3cb1760369e8a260e02caafd5
2a473880764093dd151554a913292ed465e80e62
refs/heads/master
1,609,477,731,119
1,476,299,056,000
1,476,299,056,000
58,213,801
6
0
null
null
null
null
UTF-8
Lean
false
false
1,026
hlean
import types open eq inductive pathover2 {A B : Type} (C : A → B → Type) : Π {a a' : A} (p : a=a') {b b' : B} (q : b=b') (x : C a b) (y : C a' b'), Type := | idpo2 : Π {a : A} {b : B} (x : C a b), pathover2 C (idpath a) (idpath b) x x definition tr_eq_of_homotopy {A : Type} {B : A → Type} (x y : A) (C : B x → B y → Type) : Π (f g : Π (a : A), B a) (H : f ~ g) (c : C (f x) (f y)), (eq_of_homotopy H) ▸ c = (H x) ▸ ( (H y) ▸ c) := begin intros f g H, induction H, rewrite eq_of_homotopy_idp, intro c, reflexivity end local attribute homotopy2.rec_on [recursor] definition tr_eq_of_homotopy2 {A : Type} {B : A → Type} {C : Π {a : A}, B a → Type} {a a' : A} (x : B a) (y : B a') (D : C x → C y → Type) : Π (f g : Π {{a : A}} (b : B a), C b) (H : f ~2 g) (d : D (f x) (f y)), (eq_of_homotopy2 H) ▸ d = (H a x) ▸ ((H a' y) ▸ d) := begin intros f g H, induction H, induction q, intro d, krewrite eq_of_homotopy2_id, end
0727642dc573820eb3fb5392873ccc8a91f02880
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/macroscopes.lean
37ea91c864792a62c771c9492aec8079da25e9df
[ "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
1,136
lean
new_frontend open Lean def check (b : Bool) : IO Unit := «unless» b $ throw $ IO.userError "check failed" def test1 : IO Unit := do let x := `x; let x := addMacroScope `main x 1; IO.println $ x; let v := extractMacroScopes x; let x := { v with name := `y }.review; IO.println $ x; let v := extractMacroScopes x; let x := { v with name := `x }.review; IO.println $ x; let x := addMacroScope `main x 2; IO.println $ x; let v := extractMacroScopes x; let x := { v with name := `y }.review; IO.println $ x; let v := extractMacroScopes x; let x := { v with name := `x }.review; IO.println $ x; let x := addMacroScope `main x 3; IO.println $ x; let x := addMacroScope `foo x 4; IO.println $ x; let x := addMacroScope `foo x 5; let v := extractMacroScopes x; check (v.mainModule == `foo); IO.println $ x; let x := addMacroScope `bla.bla x 6; IO.println $ x; let v := extractMacroScopes x; check (v.mainModule == `bla.bla); let x := addMacroScope `bla.bla x 7; IO.println $ x; let v := extractMacroScopes x; let x := { v with name := `y }.review; IO.println $ x; let x := { v with name := `z.w }.review; IO.println $ x; pure () #eval test1
8c9159d58439e7f5d4e57a5a2a82923b1683ead7
aa5a655c05e5359a70646b7154e7cac59f0b4132
/tests/lean/mvar3.lean
77033e4d434e3f7b7b3f66261ecafb76e5a4a9d2
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,853
lean
import Lean.MetavarContext open Lean def mkLambdaTest (mctx : MetavarContext) (ngen : NameGenerator) (lctx : LocalContext) (xs : Array Expr) (e : Expr) : Except MetavarContext.MkBinding.Exception (MetavarContext × NameGenerator × Expr) := match MetavarContext.mkLambda xs e lctx { mctx := mctx, ngen := ngen } with | EStateM.Result.ok e s => Except.ok (s.mctx, s.ngen, e) | EStateM.Result.error e s => Except.error e def check (b : Bool) : IO Unit := «unless» b (throw $ IO.userError "error") def f := mkConst `f def g := mkConst `g def a := mkConst `a def b := mkConst `b def c := mkConst `c def b0 := mkBVar 0 def b1 := mkBVar 1 def b2 := mkBVar 2 def u := mkLevelParam `u def typeE := mkSort levelOne def natE := mkConst `Nat def boolE := mkConst `Bool def vecE := mkConst `Vec [levelZero] def α := mkFVar `α def x := mkFVar `x def y := mkFVar `y def z := mkFVar `z def w := mkFVar `w def m1 := mkMVar `m1 def m2 := mkMVar `m2 def m3 := mkMVar `m3 def bi := BinderInfo.default def arrow (d b : Expr) := mkForall `_ bi d b def lctx1 : LocalContext := {} def lctx2 := lctx1.mkLocalDecl `α `α typeE def lctx3 := lctx2.mkLocalDecl `x `x m1 def lctx4 := lctx3.mkLocalDecl `y `y (arrow natE m2) def mctx1 : MetavarContext := {} def mctx2 := mctx1.addExprMVarDecl `m1 `m1 lctx2 #[] typeE def mctx3 := mctx2.addExprMVarDecl `m2 `m2 lctx3 #[] natE def mctx4 := mctx3.addExprMVarDecl `m3 `m3 lctx3 #[] natE def mctx4' := mctx3.addExprMVarDecl `m3 `m3 lctx3 #[] natE MetavarKind.syntheticOpaque def R1 := match mkLambdaTest mctx4 {namePrefix := `n} lctx4 #[α, x, y] $ mkAppN f #[m3, x] with | Except.ok s => s | Except.error e => panic! (toString e) def e1 := R1.2.2 def mctx5 := R1.1 def sortNames (xs : List Name) : List Name := (xs.toArray.qsort Name.lt).toList def sortNamePairs {α} [Inhabited α] (xs : List (Name × α)) : List (Name × α) := (xs.toArray.qsort (fun a b => Name.lt a.1 b.1)).toList #eval toString $ sortNames $ mctx5.decls.toList.map Prod.fst #eval toString $ sortNamePairs $ mctx5.eAssignment.toList #eval e1 #eval check (!e1.hasFVar) def R2 := match mkLambdaTest mctx4' {namePrefix := `n} lctx4 #[α, x, y] $ mkAppN f #[m3, y] with | Except.ok s => s | Except.error e => panic! (toString e) def e2 := R2.2.2 def mctx6 := R2.1 #eval toString $ sortNames $ mctx6.decls.toList.map Prod.fst #eval toString $ sortNamePairs $ mctx6.eAssignment.toList -- ?n.2 was delayed assigned because ?m.3 is synthetic #eval toString $ sortNames $ mctx6.dAssignment.toList.map Prod.fst #eval e2 #print "assigning ?m1 and ?n.1" def R3 := let mctx := mctx6.assignExpr `m3 x; let mctx := mctx.assignExpr (Name.mkNum `n 1) (mkLambda `_ bi typeE natE); -- ?n.2 is instantiated because we have the delayed assignment `?n.2 α x := ?m1` (mctx.instantiateMVars e2) def e3 := R3.1 def mctx7 := R3.2 #eval e3
d619eaab696dad63010ca0eec5347cea7d9026b0
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/Exercises week 5/22_homework_sheet.lean
3d2c22b3762be204a671061e5245afcfe7af2c1d
[]
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
5,177
lean
/- Homework 2.2: Functional Programming — Trees -/ /- Question 1: Huffman's algorithm -/ /- Recall the following definition from the lecture. -/ inductive tree (α : Type) | leaf : ℕ → α → tree | inner : ℕ → tree → tree → tree export tree (leaf inner) /- To make our lives easy, we will fix a type α of symbols equipped with decidable equality throughout this question. -/ section parameter (α : Type) parameter [decidable_eq α] /- We start by defining the alphabet of a tree: the set of its labels. We use lists to represent sets to get executability for free. The cost is that we must ignore the order or number of occurrences of elements in a list when comparing alphabets. -/ def alphabet : tree α → list α | (leaf _ a) := [a] | (inner _ l r) := alphabet l ++ alphabet r /- 1.1. Define the following function, so that we can obtain the alphabet of an entire forest (i.e. list of trees). Hint: Through this exercise, try to keep your definitions as simple as possible, because this will affect proving ease further down. -/ def alphabet_list : list (tree α) → list α | [] := [] | (x :: xs) := alphabet_list xs ++ alphabet x /- A tree is consistent if it contains no duplicate labels. This can be defined as an inductive predicate. -/ inductive consistent : tree α → Prop | consistent_leaf (w : ℕ) (a : α) : consistent (leaf w a) | consistent_inner (w : ℕ) (l : tree α) (r : tree α) : consistent l → consistent r → (∀a, a ∈ alphabet l → a ∈ alphabet r → false) → consistent (inner w l r) /- 1.2. A forest is consistent if it contains no duplicate labels (even in different trees). Define an inductive predicate `consistent_list` that captures this property. -/ inductive consistent_trees : list (tree α) → Prop | consistent_nil (w: ℕ) (a: α) : consistent_trees[] | consistent_cons (w: ℕ) (t: tree α) (ts: list (tree α) : consistent t → consistent_trees ts → (∀a, a ∈ alphabet t → a ∈ alphabet_list ts → false) → consistent_trees ts /- 1.3. The height of a tree is the length of the longest path from its root node to a leaf. A tree consisting of a single node has height 0 by convention. Define a recursive function `height` that computes this. Hint: You may use the built-in `max` function. -/ def height {α: Type} : tree α → ℕ | (leaf _ a) := 1 | (inner _ l r) := 1 + max (height l) (height r) /- 1.4. Now define the same function on forests, where the height of a forest is defined as the height of its tallest tree. -/ def height_forest {α: Type}: list(tree α) → ℕ | [] := 0 | (x :: xs) := 1 + max (height x) (height_forest xs) /- 1.5. Define a function that returns the depth of a symbol in a tree. For example, if the symbol is stored in a leaf node immediately below the root, it would be at depth 1. Symbols that do not occur in the tree are conventionally put at depth 0. For symbols that occur several times as labels, you can arbitrarily choose which occurrence to consider (e.g. the leftmost one). -/ def depth : tree α → α → ℕ | (leaf _ a) x := 1 | (inner _ l r) x := depth l x + depth r x /- 1.6. State and prove that the depth of a symbol in a tree is less than or equal to the height of the tree. Hint: You might find the lemmas `le_max_left`, `add_le_add_left`, and similarly named ones useful. Use Visual Studio Code's Command Palette to explore Lean's library (e.g. `#le_max`). -/ lemma depthlessequal :∀t : tree α, consistent t → ∀a ∈ alphabet t, depth t a <= height t | (leaf _ a) ct := begin repeat {apply exists.intro}, simp[alphabet], simp[depth, height], intro s, simp[le_of_eq] end | (inner _ l r) ct := begin repeat{apply exists.intro}, simp[alphabet], simp[depth, height], intro s, intro a, simp[le_max], end /- 1.7. A tree's height is not only an upper bound on the depth of symbols stored in the tree. It is also a tight bound. Complete the following proof. -/ lemma exists_at_height : ∀t : tree α, consistent t → ∃a ∈ alphabet t, depth t a = height t | (leaf _ a) ct := begin repeat {apply exists.intro}, simp[alphabet], simp[depth, height] end | t@(inner _ l r) ct := -- `t@` introduces the alias `t` for `inner _ l r` have cl : consistent l := begin have bla: ∀ (t : tree α), consistent t → (∃ (a : α) (H : a ∈ alphabet t), depth t a = height t) , intro a, intro b, apply exists_at_height, assumption, end have cr : consistent r := sorry, let ⟨b, b_in_alpha_l, depth_l_b_eq_height_l⟩ := exists_at_height l cl in let ⟨c, c_in_alpha_r, depth_r_c_eq_height_r⟩ := exists_at_height r cr in let b_or_c := if height r ≤ height l then b else c in have borc_in_alpha_t : b_or_c ∈ alphabet t := begin repeat {apply exists.intro}, simp[alphabet], apply or.inr, simp [b_or_c], by_cases (ite (height r ≤ height l) b c ∈ alphabet r), end have depth_t_borc_eq_height_t : depth t b_or_c = height t := sorry, -- **optional** ⟨b_or_c, borc_in_alpha_t, depth_t_borc_eq_height_t⟩ end /- Question 2: Enter your question here. -/
13f88bc647f83a337126b9419ae6d85c28f316a4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/homology/exact_auto.lean
f92b32fd408632ec89c527c66a05276edcc10fcf
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,713
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.homology.image_to_kernel_map import Mathlib.PostPort universes v u l namespace Mathlib /-! # 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. This definition is equivalent to the homology at `B` vanishing (at least for preadditive categories). At this level of generality, this is not necessarily equivalent to other reasonable definitions of exactness, for example that the inclusion map `image.ι f` is a kernel of `g` or that the map `image f ⟶ kernel g` is an isomorphism. By adding more assumptions on our category, we get these equivalences and more. Currently, there is one particular set of assumptions mathlib knows about: abelian categories. Consequently, many interesting results about exact sequences are found in `category_theory/abelian/exact.lean`. # 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`. * Precomposing the first morphism with an epimorphism retains exactness. Postcomposing the second morphism with a monomorphism retains exactness. * If `f` and `g` are exact and `i` is an isomorphism, then `f ≫ i.hom` and `i.inv ≫ g` are also exact. # 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 -/ 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 {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] {A : V} {B : V} {C : V} (f : A ⟶ B) (g : B ⟶ C) where w : f ≫ g = 0 epi : epi (image_to_kernel_map f g w) @[simp] theorem exact.w_assoc {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] {A : V} {B : V} {C : V} {f : A ⟶ B} {g : B ⟶ C} [c : exact f g] {X' : V} (f' : C ⟶ X') : f ≫ g ≫ f' = 0 ≫ f' := sorry theorem exact_comp_hom_inv_comp {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] {A : V} {B : V} {C : V} {D : V} {f : A ⟶ B} {g : B ⟶ C} [exact f g] (i : B ≅ D) : exact (f ≫ iso.hom i) (iso.inv i ≫ g) := sorry theorem exact_comp_hom_inv_comp_iff {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] {A : V} {B : V} {C : V} {D : V} {f : A ⟶ B} {g : B ⟶ C} (i : B ≅ D) : exact (f ≫ iso.hom i) (iso.inv i ≫ g) ↔ exact f g := sorry theorem exact_epi_comp {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] {A : V} {B : V} {C : V} {D : V} {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D} [exact g h] [epi f] : exact (f ≫ g) h := sorry theorem exact_comp_mono {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] {A : V} {B : V} {C : V} {D : V} {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D} [exact f g] [mono h] : exact f (g ≫ h) := sorry theorem exact_kernel {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] {A : V} {B : V} {f : A ⟶ B} : exact (limits.kernel.ι f) f := sorry theorem kernel_ι_eq_zero_of_exact_zero_left {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] (A : V) {B : V} {C : V} {g : B ⟶ C} [exact 0 g] : limits.kernel.ι g = 0 := sorry theorem exact_zero_left_of_mono {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] (A : V) {B : V} {C : V} {g : B ⟶ C} [limits.has_zero_object V] [mono g] : exact 0 g := sorry @[simp] theorem kernel_comp_cokernel_assoc {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] [limits.has_cokernels V] {A : V} {B : V} {C : V} (f : A ⟶ B) (g : B ⟶ C) [exact f g] {X' : V} (f' : limits.cokernel f ⟶ X') : limits.kernel.ι g ≫ limits.cokernel.π f ≫ f' = 0 ≫ f' := sorry theorem comp_eq_zero_of_exact {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] [limits.has_cokernels V] {A : V} {B : V} {C : V} (f : A ⟶ B) (g : B ⟶ C) [exact f g] {X : V} {Y : V} {ι : X ⟶ B} (hι : ι ≫ g = 0) {π : B ⟶ Y} (hπ : f ≫ π = 0) : ι ≫ π = 0 := sorry @[simp] theorem fork_ι_comp_cofork_π {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] [limits.has_cokernels V] {A : V} {B : V} {C : V} (f : A ⟶ B) (g : B ⟶ C) [exact f g] (s : limits.kernel_fork g) (t : limits.cokernel_cofork f) : limits.fork.ι s ≫ limits.cofork.π t = 0 := comp_eq_zero_of_exact f g (limits.kernel_fork.condition s) (limits.cokernel_cofork.condition t) theorem exact_of_zero {V : Type u} [category V] [limits.has_zero_morphisms V] [limits.has_equalizers V] [limits.has_images V] [limits.has_zero_object V] {A : V} {C : V} (f : A ⟶ 0) (g : 0 ⟶ C) : exact f g := sorry end Mathlib
11842e33b48acf54d70f35af8dda59e61f1b04bf
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/qpf/multivariate/constructions/prj_auto.lean
8bb64c4813618f90404fb24cda7d6c00814a743b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,816
lean
/- Copyright (c) 2020 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.functor.multivariate import Mathlib.data.qpf.multivariate.basic import Mathlib.PostPort universes u u_1 u_2 namespace Mathlib /-! Projection functors are QPFs. The `n`-ary projection functors on `i` is an `n`-ary functor `F` such that `F (α₀..αᵢ₋₁, αᵢ, αᵢ₊₁..αₙ₋₁) = αᵢ` -/ namespace mvqpf /-- The projection `i` functor -/ def prj {n : ℕ} (i : fin2 n) (v : typevec n) := v i protected instance prj.inhabited {n : ℕ} (i : fin2 n) {v : typevec n} [Inhabited (v i)] : Inhabited (prj i v) := { default := Inhabited.default } /-- `map` on functor `prj i` -/ def prj.map {n : ℕ} (i : fin2 n) {α : typevec n} {β : typevec n} (f : typevec.arrow α β) : prj i α → prj i β := f i protected instance prj.mvfunctor {n : ℕ} (i : fin2 n) : mvfunctor (prj i) := mvfunctor.mk (prj.map i) /-- Polynomial representation of the projection functor -/ def prj.P {n : ℕ} (i : fin2 n) : mvpfunctor n := mvpfunctor.mk PUnit fun (_x : PUnit) (j : fin2 n) => ulift (plift (i = j)) /-- Abstraction function of the `qpf` instance -/ def prj.abs {n : ℕ} (i : fin2 n) {α : typevec n} : mvpfunctor.obj (prj.P i) α → prj i α := sorry /-- Representation function of the `qpf` instance -/ def prj.repr {n : ℕ} (i : fin2 n) {α : typevec n} : prj i α → mvpfunctor.obj (prj.P i) α := fun (x : α i) => sigma.mk PUnit.unit fun (j : fin2 n) (_x : mvpfunctor.B (prj.P i) PUnit.unit j) => sorry protected instance prj.mvqpf {n : ℕ} (i : fin2 n) : mvqpf (prj i) := mk (prj.P i) (prj.abs i) (prj.repr i) sorry sorry end Mathlib
c18e0fdd790908046d2306cfcc95399e9da780ba
7490bf5d40d31857a58062614642bb5a41c36154
/dm_box.lean
a634a587ec8d3ac90c090c9582f81afedcd54236
[]
no_license
reesegrayallen/Lean-Discrete-Mathematics
9f1d6fe1c814cc9264ce868a67adcf5a82566e22
00c875284613ea12e0a729f519738aab8599456b
refs/heads/main
1,674,181,372,629
1,606,801,004,000
1,606,801,004,000
317,387,970
0
0
null
null
null
null
UTF-8
Lean
false
false
513
lean
/- HOMEWORK 3 Reese Allen (rga2uz) CS2102 - Sullivan -/ -- defining new polymorphic abstract data type inductive dm_box (α : Type) : Type | mk : (α : Type) → dm_box -- function defintions using lambda expressions, c-style (') and by cases ('') def unbox {α : Type} : (dm_box α) → α := λ (b : dm_box α), match b with | dm_box.mk x := x end def unbox' {α : Type } (b : dm_box α) := match b with | dm_box.mk x := x end def unbox'' {α : Type} : (dm_box α) → α | (dm_box.mk x) := x
845f4afdd8c2f03b49c75dd076f709d5a42a8a9d
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/src/Lean/Elab/SetOption.lean
60c0880b2dfe3ad414d7fdae98756673c654fe5f
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
1,338
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Log import Lean.Elab.InfoTree namespace Lean.Elab variable [Monad m] [MonadOptions m] [MonadExceptOf Exception m] [MonadRef m] variable [AddErrorMessageContext m] [MonadLiftT (EIO Exception) m] [MonadInfoTree m] def elabSetOption (id : Syntax) (val : Syntax) : m Options := do let optionName := id.getId.eraseMacroScopes match val.isStrLit? with | some str => setOption optionName (DataValue.ofString str) | none => match val.isNatLit? with | some num => setOption optionName (DataValue.ofNat num) | none => match val with | Syntax.atom _ "true" => setOption optionName (DataValue.ofBool true) | Syntax.atom _ "false" => setOption optionName (DataValue.ofBool false) | _ => addCompletionInfo <| CompletionInfo.option (← getRef) throwError "unexpected set_option value {val}" where setOption (optionName : Name) (val : DataValue) : m Options := do let decl ← IO.toEIO (fun (ex : IO.Error) => Exception.error (← getRef) ex.toString) (getOptionDecl optionName) unless decl.defValue.sameCtor val do throwError "type mismatch at set_option" return (← getOptions).insert optionName val end Lean.Elab
ad84b28b025c0edc780cfb20df420ff18c3789d4
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/ring_theory/discrete_valuation_ring.lean
c8433e754c71085c5377d2bc6f623a25e0c12bb2
[ "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
13,139
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import ring_theory.principal_ideal_domain import order.conditionally_complete_lattice import ring_theory.multiplicity import ring_theory.valuation.basic /-! # Discrete valuation rings This file defines discrete valuation rings (DVRs) and develops a basic interface for them. ## Important definitions There are various definitions of a DVR in the literature; we define a DVR to be a local PID which is not a field (the first definition in Wikipedia) and prove that this is equivalent to being a PID with a unique non-zero prime ideal (the definition in Serre's book "Local Fields"). Let R be an integral domain, assumed to be a principal ideal ring and a local ring. * `discrete_valuation_ring R` : a predicate expressing that R is a DVR ### Definitions ## Implementation notes It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible. We do not hence define `uniformizer` at all, because we can use `irreducible` instead. ## Tags discrete valuation ring -/ open_locale classical universe u open ideal local_ring /-- An integral domain is a discrete valuation ring if it's a local PID which is not a field -/ class discrete_valuation_ring (R : Type u) [integral_domain R] extends is_principal_ideal_ring R, local_ring R : Prop := (not_a_field' : maximal_ideal R ≠ ⊥) namespace discrete_valuation_ring variables (R : Type u) [integral_domain R] [discrete_valuation_ring R] lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field' variable {R} open principal_ideal_ring /-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the maximal ideal of R -/ theorem irreducible_iff_uniformizer (ϖ : R) : irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} := ⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm, begin intro h, have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R, from h.symm ▸ submodule.mem_span_singleton_self ϖ, refine ⟨h2, _⟩, intros a b hab, by_contra h, push_neg at h, obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h, rw h at ha hb, rw mem_span_singleton' at ha hb, rcases ha with ⟨a, rfl⟩, rcases hb with ⟨b, rfl⟩, rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab, have h3 := eq_zero_of_mul_eq_self_right _ hab.symm, { apply not_a_field R, simp [h, h3] }, { intro hh, apply h2, refine is_unit_of_dvd_one ϖ _, use a * b, exact hh.symm } end⟩ variable (R) /-- Uniformisers exist in a DVR -/ theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ := by {simp_rw [irreducible_iff_uniformizer], exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal} /-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/ theorem iff_pid_with_one_nonzero_prime (R : Type u) [integral_domain R] : discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P := begin split, { intro RDVR, rcases id RDVR with ⟨RPID, Rlocal, Rnotafield⟩, split, assumption, resetI, use local_ring.maximal_ideal R, split, split, { assumption }, { apply_instance } , { rintro Q ⟨hQ1, hQ2⟩, obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1, have hq : q ≠ 0, { rintro rfl, apply hQ1, simp }, erw span_singleton_prime hq at hQ2, replace hQ2 := irreducible_of_prime hQ2, rw irreducible_iff_uniformizer at hQ2, exact hQ2.symm } }, { rintro ⟨RPID, Punique⟩, haveI : local_ring R := local_of_unique_nonzero_prime R Punique, refine {not_a_field' := _}, rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩, have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1), intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM } end lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) : associated a b := begin rw irreducible_iff_uniformizer at ha hb, rw [←span_singleton_eq_span_singleton, ←ha, hb], end end discrete_valuation_ring namespace discrete_valuation_ring variable (R : Type*) /-- Alternative characterisation of discrete valuation rings. -/ def has_unit_mul_pow_irreducible_factorization [integral_domain R] : Prop := ∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x namespace has_unit_mul_pow_irreducible_factorization variables {R} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) include hR lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin rcases hR with ⟨ϖ, hϖ, hR⟩, suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ, { apply associated.trans (this hp) (this hq).symm, }, clear hp hq p q, intros p hp, obtain ⟨n, hn⟩ := hR hp.ne_zero, have : irreducible (ϖ ^ n) := irreducible_of_associated hn.symm hp, rcases lt_trichotomy n 1 with (H|rfl|H), { obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial }, simpa only [not_irreducible_one, pow_zero] using this, }, { simpa only [pow_one] using hn.symm, }, { obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H, rw pow_succ at this, rcases this.2 _ _ rfl with H0|H0, { exact (hϖ.not_unit H0).elim, }, { rw [add_comm, pow_succ] at H0, exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } } end /-- Implementation detail: an integral domain in which there is a unit `p` such that every nonzero element is associated to a power of `p` is a unique factorization domain. See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/ theorem ufd : unique_factorization_monoid R := let p := classical.some hR in let spec := classical.some_spec hR in unique_factorization_monoid_of_exists_prime_of_factor $ λ x hx, begin use multiset.repeat p (classical.some (spec.2 hx)), split, { intros q hq, have hpq := multiset.eq_of_mem_repeat hq, rw hpq, refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩, intros a b h, by_cases ha : a = 0, { rw ha, simp only [true_or, dvd_zero], }, by_cases hb : b = 0, { rw hb, simp only [or_true, dvd_zero], }, obtain ⟨m, u, rfl⟩ := spec.2 ha, rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (is_unit_unit _)] at h, rw is_unit.dvd_mul_right (is_unit_unit _), by_cases hm : m = 0, { simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h }, left, obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm, apply dvd_mul_of_dvd_left (dvd_refl _) _ }, { rw [multiset.prod_repeat], exact (classical.some_spec (spec.2 hx)), } end omit hR lemma of_ufd_of_unique_irreducible [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : has_unit_mul_pow_irreducible_factorization R := begin obtain ⟨p, hp⟩ := h₁, refine ⟨p, hp, _⟩, intros x hx, cases wf_dvd_monoid.exists_factors x hx with fx hfx, refine ⟨fx.card, _⟩, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, symmetry, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ q hq rfl, rw associates.mk_eq_mk_iff_associated, apply h₂ (hfx.1 _ hq) hp, end end has_unit_mul_pow_irreducible_factorization lemma aux_pid_of_ufd_of_unique_irreducible (R : Type u) [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : is_principal_ideal_ring R := begin constructor, intro I, by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], }, obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0, obtain ⟨p, hp, H⟩ := has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂, have ex : ∃ n : ℕ, p ^ n ∈ I, { obtain ⟨n, u, rfl⟩ := H hx0, refine ⟨n, _⟩, simpa only [units.mul_inv_cancel_right] using @ideal.mul_mem_right _ _ I _ ↑u⁻¹ hxI, }, constructor, use p ^ (nat.find ex), show I = ideal.span _, apply le_antisymm, { intros r hr, by_cases hr0 : r = 0, { simp only [hr0, submodule.zero_mem], }, obtain ⟨n, u, rfl⟩ := H hr0, simp only [mem_span_singleton, is_unit_unit, is_unit.dvd_mul_right], apply pow_dvd_pow, apply nat.find_min', simpa only [units.mul_inv_cancel_right] using @ideal.mul_mem_right _ _ I _ ↑u⁻¹ hr, }, { erw submodule.span_singleton_le_iff_mem, exact nat.find_spec ex, }, end /-- A unique factorization domain with at least one irreducible element in which all irreducible elements are associated is a discrete valuation ring. -/ lemma of_ufd_of_unique_irreducible {R : Type u} [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : discrete_valuation_ring R := begin rw iff_pid_with_one_nonzero_prime, haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂, obtain ⟨p, hp⟩ := h₁, refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩, { rw submodule.ne_bot_iff, refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, }, { rwa [ideal.span_singleton_prime hp.ne_zero, ← unique_factorization_monoid.irreducible_iff_prime], }, { intro I, rw ← submodule.is_principal.span_singleton_generator I, rintro ⟨I0, hI⟩, apply span_singleton_eq_span_singleton.mpr, apply h₂ _ hp, erw [ne.def, span_singleton_eq_bot] at I0, rwa [unique_factorization_monoid.irreducible_iff_prime, ← ideal.span_singleton_prime I0], }, end /-- An integral domain in which there is a unit `p` such that every nonzero element is associated to a power of `p` is a discrete valuation ring. -/ lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) : discrete_valuation_ring R := begin letI : unique_factorization_monoid R := hR.ufd, apply of_ufd_of_unique_irreducible _ hR.unique_irreducible, unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, }, end section variables [integral_domain R] [discrete_valuation_ring R] variable {R} lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ), associated x (ϖ ^ n) := begin have : wf_dvd_monoid R := is_noetherian_ring.wf_dvd_monoid, cases wf_dvd_monoid.exists_factors x hx with fx hfx, unfreezingI { use fx.card }, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ _ _ rfl, rw associates.mk_eq_mk_iff_associated, refine associated_of_irreducible _ _ hirr, apply hfx.1, assumption end open submodule.is_principal lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) : ∃ n : ℕ, s = ideal.span {ϖ ^ n} := begin have gen_ne_zero : generator s ≠ 0, { rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption }, rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩, use n, have : span _ = _ := span_singleton_generator s, rw [← this, ← hnu, span_singleton_eq_span_singleton], use u end lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q) (u v : units R) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) : m = n := begin have key : associated (multiset.repeat p m).prod (multiset.repeat q n).prod, { rw [multiset.prod_repeat, multiset.prod_repeat, associated], refine ⟨u * v⁻¹, _⟩, simp only [units.coe_mul], rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], }, have := multiset.card_eq_card_of_rel (unique_factorization_monoid.factors_unique _ _ key), { simpa only [multiset.card_repeat] }, all_goals { intros x hx, replace hx := multiset.eq_of_mem_repeat hx, unfreezingI { subst hx, assumption } }, end lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : units R) (m n : ℕ) (h : ↑u * ϖ ^ m = v * ϖ ^ n) : u = v := begin obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h, rw ← sub_eq_zero at h, rw [← sub_mul, mul_eq_zero] at h, cases h, { rw sub_eq_zero at h, exact_mod_cast h }, { apply (hirr.ne_zero (pow_eq_zero h)).elim, } end end end discrete_valuation_ring
92a9c556ebfd8532cb9cfe1918132ebaf73df455
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/finset/card.lean
8a6f1f2e0e381e91ff227e813bcac0d1967c5b78
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
24,538
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad -/ import data.finset.image import tactic.by_contra /-! # Cardinality of a finite set This defines the cardinality of a `finset` and provides induction principles for finsets. ## Main declarations * `finset.card`: `s.card : ℕ` returns the cardinality of `s : finset α`. ### Induction principles * `finset.strong_induction`: Strong induction * `finset.strong_induction_on` * `finset.strong_downward_induction` * `finset.strong_downward_induction_on` * `finset.case_strong_induction_on` ## TODO Should we add a noncomputable version? -/ open function multiset nat variables {α β : Type*} namespace finset variables {s t : finset α} {a b : α} /-- `s.card` is the number of elements of `s`, aka its cardinality. -/ def card (s : finset α) : ℕ := s.1.card lemma card_def (s : finset α) : s.card = s.1.card := rfl @[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl @[simp] lemma card_empty : card (∅ : finset α) = 0 := rfl lemma card_le_of_subset : s ⊆ t → s.card ≤ t.card := multiset.card_le_of_le ∘ val_le_iff.mpr @[mono] lemma card_mono : monotone (@card α) := by apply card_le_of_subset @[simp] lemma card_eq_zero : s.card = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero lemma card_pos : 0 < s.card ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm alias card_pos ↔ _ nonempty.card_pos lemma card_ne_zero_of_mem (h : a ∈ s) : s.card ≠ 0 := (not_congr card_eq_zero).2 $ ne_empty_of_mem h @[simp] lemma card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _ lemma card_singleton_inter [decidable_eq α] : ({a} ∩ s).card ≤ 1 := begin cases (finset.decidable_mem a s), { simp [finset.singleton_inter_of_not_mem h] }, { simp [finset.singleton_inter_of_mem h] } end @[simp] lemma card_cons (h : a ∉ s) : (s.cons a h).card = s.card + 1 := card_cons _ _ section insert_erase variables [decidable_eq α] @[simp] lemma card_insert_of_not_mem (h : a ∉ s) : (insert a s).card = s.card + 1 := by rw [←cons_eq_insert _ _ h, card_cons] lemma card_insert_of_mem (h : a ∈ s) : card (insert a s) = s.card := by rw insert_eq_of_mem h lemma card_insert_le (a : α) (s : finset α) : card (insert a s) ≤ s.card + 1 := by by_cases a ∈ s; [{rw insert_eq_of_mem h, exact nat.le_succ _ }, rw card_insert_of_not_mem h] /-- If `a ∈ s` is known, see also `finset.card_insert_of_mem` and `finset.card_insert_of_not_mem`. -/ lemma card_insert_eq_ite : card (insert a s) = if a ∈ s then s.card else s.card + 1 := begin by_cases h : a ∈ s, { rw [card_insert_of_mem h, if_pos h] }, { rw [card_insert_of_not_mem h, if_neg h] } end @[simp] lemma card_doubleton (h : a ≠ b) : ({a, b} : finset α).card = 2 := by rw [card_insert_of_not_mem (not_mem_singleton.2 h), card_singleton] @[simp] lemma card_erase_of_mem : a ∈ s → (s.erase a).card = s.card - 1 := card_erase_of_mem @[simp] lemma card_erase_add_one : a ∈ s → (s.erase a).card + 1 = s.card := card_erase_add_one lemma card_erase_lt_of_mem : a ∈ s → (s.erase a).card < s.card := card_erase_lt_of_mem lemma card_erase_le : (s.erase a).card ≤ s.card := card_erase_le lemma pred_card_le_card_erase : s.card - 1 ≤ (s.erase a).card := begin by_cases h : a ∈ s, { exact (card_erase_of_mem h).ge }, { rw erase_eq_of_not_mem h, exact nat.sub_le _ _ } end /-- If `a ∈ s` is known, see also `finset.card_erase_of_mem` and `finset.erase_eq_of_not_mem`. -/ lemma card_erase_eq_ite : (s.erase a).card = if a ∈ s then s.card - 1 else s.card := card_erase_eq_ite end insert_erase @[simp] lemma card_range (n : ℕ) : (range n).card = n := card_range n @[simp] lemma card_attach : s.attach.card = s.card := multiset.card_attach end finset section to_list_multiset variables [decidable_eq α] (m : multiset α) (l : list α) lemma multiset.card_to_finset : m.to_finset.card = m.dedup.card := rfl lemma multiset.to_finset_card_le : m.to_finset.card ≤ m.card := card_le_of_le $ dedup_le _ lemma multiset.to_finset_card_of_nodup {m : multiset α} (h : m.nodup) : m.to_finset.card = m.card := congr_arg card $ multiset.dedup_eq_self.mpr h lemma list.card_to_finset : l.to_finset.card = l.dedup.length := rfl lemma list.to_finset_card_le : l.to_finset.card ≤ l.length := multiset.to_finset_card_le ⟦l⟧ lemma list.to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := multiset.to_finset_card_of_nodup h end to_list_multiset namespace finset variables {s t : finset α} {f : α → β} {n : ℕ} @[simp] lemma length_to_list (s : finset α) : s.to_list.length = s.card := by { rw [to_list, ←multiset.coe_card, multiset.coe_to_list], refl } lemma card_image_le [decidable_eq β] : (s.image f).card ≤ s.card := by simpa only [card_map] using (s.1.map f).to_finset_card_le lemma card_image_of_inj_on [decidable_eq β] (H : set.inj_on f s) : (s.image f).card = s.card := by simp only [card, image_val_of_inj_on H, card_map] lemma inj_on_of_card_image_eq [decidable_eq β] (H : (s.image f).card = s.card) : set.inj_on f s := begin change (s.1.map f).dedup.card = s.1.card at H, have : (s.1.map f).dedup = s.1.map f, { refine multiset.eq_of_le_of_card_le (multiset.dedup_le _) _, rw H, simp only [multiset.card_map] }, rw multiset.dedup_eq_self at this, exact inj_on_of_nodup_map this, end lemma card_image_iff [decidable_eq β] : (s.image f).card = s.card ↔ set.inj_on f s := ⟨inj_on_of_card_image_eq, card_image_of_inj_on⟩ lemma card_image_of_injective [decidable_eq β] (s : finset α) (H : injective f) : (s.image f).card = s.card := card_image_of_inj_on $ λ x _ y _ h, H h lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) : (s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f := by { rw [←pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] } @[simp] lemma card_map (f : α ↪ β) : (s.map f).card = s.card := multiset.card_map _ _ @[simp] lemma card_subtype (p : α → Prop) [decidable_pred p] (s : finset α) : (s.subtype p).card = (s.filter p).card := by simp [finset.subtype] lemma card_filter_le (s : finset α) (p : α → Prop) [decidable_pred p] : (s.filter p).card ≤ s.card := card_le_of_subset $ filter_subset _ _ lemma eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : t.card ≤ s.card) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma eq_of_superset_of_card_ge (hst : s ⊆ t) (hts : t.card ≤ s.card) : t = s := (eq_of_subset_of_card_le hst hts).symm lemma subset_iff_eq_of_card_le (h : t.card ≤ s.card) : s ⊆ t ↔ s = t := ⟨λ hst, eq_of_subset_of_card_le hst h, eq.subset'⟩ lemma map_eq_of_subset {f : α ↪ α} (hs : s.map f ⊆ s) : s.map f = s := eq_of_subset_of_card_le hs (card_map _).ge lemma filter_card_eq {p : α → Prop} [decidable_pred p] (h : (s.filter p).card = s.card) (x : α) (hx : x ∈ s) : p x := begin rw [←eq_of_subset_of_card_le (s.filter_subset p) h.ge, mem_filter] at hx, exact hx.2, end lemma card_lt_card (h : s ⊂ t) : s.card < t.card := card_lt_of_lt $ val_lt_iff.2 h lemma card_eq_of_bijective (f : ∀ i, i < n → α) (hf : ∀ a ∈ s, ∃ i, ∃ h : i < n, f i h = a) (hf' : ∀ i (h : i < n), f i h ∈ s) (f_inj : ∀ i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : s.card = n := begin classical, have : ∀ (a : α), a ∈ s ↔ ∃ i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from λ a, ⟨λ ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, λ ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc s.card = card ((range n).attach.image $ λ i, f i.1 (mem_range.1 i.2)) : by rw this ... = card ((range n).attach) : card_image_of_injective _ $ λ ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n end lemma card_congr {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by classical; calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ $ λ a b h, subtype.eq $ h₂ _ _ _ _ h) ... = t.card : congr_arg card (finset.ext $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_le_card_of_inj_on {t : finset β} (f : α → β) (hf : ∀ a ∈ s, f a ∈ t) (f_inj : ∀ a₁ ∈ s, ∀ a₂ ∈ s, f a₁ = f a₂ → a₁ = a₂) : s.card ≤ t.card := by classical; calc s.card = (s.image f).card : (card_image_of_inj_on f_inj).symm ... ≤ t.card : card_le_of_subset $ image_subset_iff.2 hf /-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole. -/ lemma exists_ne_map_eq_of_card_lt_of_maps_to {t : finset β} (hc : t.card < s.card) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin classical, by_contra' hz, refine hc.not_le (card_le_card_of_inj_on f hf _), intros x hx y hy, contrapose, exact hz x hx y hy, end lemma le_card_of_inj_on_range (f : ℕ → α) (hf : ∀ i < n, f i ∈ s) (f_inj : ∀ (i < n) (j < n), f i = f j → i = j) : n ≤ s.card := calc n = card (range n) : (card_range n).symm ... ≤ s.card : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simpa only [mem_range]) lemma surj_on_of_inj_on_of_card_le {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : t.card ≤ s.card) : ∀ b ∈ t, ∃ a ha, b = f a ha := begin classical, intros b hb, have h : (s.attach.image $ λ (a : {a // a ∈ s}), f a a.prop).card = s.card, { exact @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h) }, have h' : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t, { exact eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]) }, rw ←h' at hb, obtain ⟨a, ha₁, ha₂⟩ := mem_image.1 hb, exact ⟨a, a.2, ha₂.symm⟩, end lemma inj_on_of_surj_on_of_card_le {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : s.card ≤ t.card) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from (left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)).injective, subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) @[simp] lemma card_disj_union (s t : finset α) (h) : (s.disj_union t h).card = s.card + t.card := multiset.card_add _ _ /-! ### Lattice structure -/ section lattice variables [decidable_eq α] lemma card_union_add_card_inter (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc lemma card_inter_add_card_union (s t : finset α) : (s ∩ t).card + (s ∪ t).card = s.card + t.card := by rw [add_comm, card_union_add_card_inter] lemma card_union_le (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ nat.le_add_right _ _ lemma card_union_eq (h : disjoint s t) : (s ∪ t).card = s.card + t.card := by rw [←disj_union_eq_union s t h, card_disj_union _ _ _] @[simp] lemma card_disjoint_union (h : disjoint s t) : card (s ∪ t) = s.card + t.card := card_union_eq h lemma card_sdiff (h : s ⊆ t) : card (t \ s) = t.card - s.card := suffices card (t \ s) = card ((t \ s) ∪ s) - s.card, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, add_tsub_cancel_right] lemma card_sdiff_add_card_eq_card {s t : finset α} (h : s ⊆ t) : card (t \ s) + card s = card t := ((nat.sub_eq_iff_eq_add (card_le_of_subset h)).mp (card_sdiff h).symm).symm lemma le_card_sdiff (s t : finset α) : t.card - s.card ≤ card (t \ s) := calc card t - card s ≤ card t - card (s ∩ t) : tsub_le_tsub_left (card_le_of_subset (inter_subset_left s t)) _ ... = card (t \ (s ∩ t)) : (card_sdiff (inter_subset_right s t)).symm ... ≤ card (t \ s) : by rw sdiff_inter_self_right t s lemma card_le_card_sdiff_add_card : s.card ≤ (s \ t).card + t.card := tsub_le_iff_right.1 $ le_card_sdiff _ _ lemma card_sdiff_add_card : (s \ t).card + t.card = (s ∪ t).card := by rw [←card_disjoint_union sdiff_disjoint, sdiff_union_self_eq_union] end lattice lemma filter_card_add_filter_neg_card_eq_card (p : α → Prop) [decidable_pred p] : (s.filter p).card + (s.filter (not ∘ p)).card = s.card := by { classical, simp [←card_union_eq, filter_union_filter_neg_eq, disjoint_filter] } /-- Given a set `A` and a set `B` inside it, we can shrink `A` to any appropriate size, and keep `B` inside it. -/ lemma exists_intermediate_set {A B : finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin classical, rcases nat.le.dest h₁ with ⟨k, _⟩, clear h₁, induction k with k ih generalizing A, { exact ⟨A, h₂, subset.refl _, h.symm⟩ }, have : (A \ B).nonempty, { rw [←card_pos, card_sdiff h₂, ←h, nat.add_right_comm, add_tsub_cancel_right, nat.add_succ], apply nat.succ_pos }, rcases this with ⟨a, ha⟩, have z : i + card B + k = card (erase A a), { rw [card_erase_of_mem (mem_sdiff.1 ha).1, ←h], refl }, rcases ih _ z with ⟨B', hB', B'subA', cards⟩, { exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ }, { rintro t th, apply mem_erase_of_ne_of_mem _ (h₂ th), rintro rfl, exact not_mem_sdiff_of_mem_right th ha } end /-- We can shrink `A` to any smaller size. -/ lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ (B : finset α), B ⊆ A ∧ card B = i := let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩ lemma exists_subset_or_subset_of_two_mul_lt_card [decidable_eq α] {X Y : finset α} {n : ℕ} (hXY : 2 * n < (X ∪ Y).card) : ∃ C : finset α, n < C.card ∧ (C ⊆ X ∨ C ⊆ Y) := begin have h₁ : (X ∩ (Y \ X)).card = 0 := finset.card_eq_zero.mpr (finset.inter_sdiff_self X Y), have h₂ : (X ∪ Y).card = X.card + (Y \ X).card, { rw [←card_union_add_card_inter X (Y \ X), finset.union_sdiff_self_eq_union, h₁, add_zero] }, rw [h₂, two_mul] at hXY, rcases lt_or_lt_of_add_lt_add hXY with h|h, { exact ⟨X, h, or.inl (finset.subset.refl X)⟩ }, { exact ⟨Y \ X, h, or.inr (finset.sdiff_subset Y X)⟩ } end /-! ### Explicit description of a finset from its card -/ lemma card_eq_one : s.card = 1 ↔ ∃ a, s = {a} := by cases s; simp only [multiset.card_eq_one, finset.card, ←val_inj, singleton_val] lemma exists_eq_insert_iff [decidable_eq α] {s t : finset α} : (∃ a ∉ s, insert a s = t) ↔ s ⊆ t ∧ s.card + 1 = t.card := begin split, { rintro ⟨a, ha, rfl⟩, exact ⟨subset_insert _ _, (card_insert_of_not_mem ha).symm⟩ }, { rintro ⟨hst, h⟩, obtain ⟨a, ha⟩ : ∃ a, t \ s = {a}, { exact card_eq_one.1 (by rw [card_sdiff hst, ←h, add_tsub_cancel_left]) }, refine ⟨a, λ hs, (_ : a ∉ {a}) $ mem_singleton_self _, by rw [insert_eq, ←ha, sdiff_union_of_subset hst]⟩, rw ←ha, exact not_mem_sdiff_of_mem_right hs } end lemma card_le_one : s.card ≤ 1 ↔ ∀ (a ∈ s) (b ∈ s), a = b := begin obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty, { simp }, refine (nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).le_iff_eq.trans (card_eq_one.trans ⟨_, _⟩), { rintro ⟨y, rfl⟩, simp }, { exact λ h, ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, λ y hy, h _ hy _ hx⟩⟩ } end lemma card_le_one_iff : s.card ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b := by { rw card_le_one, tauto } lemma card_le_one_iff_subset_singleton [nonempty α] : s.card ≤ 1 ↔ ∃ (x : α), s ⊆ {x} := begin refine ⟨λ H, _, _⟩, { obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty, { exact ⟨classical.arbitrary α, empty_subset _⟩ }, { exact ⟨x, λ y hy, by rw [card_le_one.1 H y hy x hx, mem_singleton]⟩ } }, { rintro ⟨x, hx⟩, rw ←card_singleton x, exact card_le_of_subset hx } end /-- A `finset` of a subsingleton type has cardinality at most one. -/ lemma card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 := finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _ lemma one_lt_card : 1 < s.card ↔ ∃ (a ∈ s) (b ∈ s), a ≠ b := by { rw ←not_iff_not, push_neg, exact card_le_one } lemma one_lt_card_iff : 1 < s.card ↔ ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b := by { rw one_lt_card, simp only [exists_prop, exists_and_distrib_left] } lemma two_lt_card_iff : 2 < s.card ↔ ∃ a b c, a ∈ s ∧ b ∈ s ∧ c ∈ s ∧ a ≠ b ∧ a ≠ c ∧ b ≠ c := begin classical, refine ⟨λ h, _, _⟩, { obtain ⟨c, hc⟩ := card_pos.mp (zero_lt_two.trans h), have : 1 < (s.erase c).card := by rwa [←add_lt_add_iff_right 1, card_erase_add_one hc], obtain ⟨a, b, ha, hb, hab⟩ := one_lt_card_iff.mp this, exact ⟨a, b, c, mem_of_mem_erase ha, mem_of_mem_erase hb, hc, hab, ne_of_mem_erase ha, ne_of_mem_erase hb⟩ }, { rintros ⟨a, b, c, ha, hb, hc, hab, hac, hbc⟩, rw [←card_erase_add_one hc, ←card_erase_add_one (mem_erase_of_ne_of_mem hbc hb), ←card_erase_add_one (mem_erase_of_ne_of_mem hab (mem_erase_of_ne_of_mem hac ha))], apply nat.le_add_left }, end lemma two_lt_card : 2 < s.card ↔ ∃ (a ∈ s) (b ∈ s) (c ∈ s), a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp_rw [two_lt_card_iff, exists_prop, exists_and_distrib_left] lemma exists_ne_of_one_lt_card (hs : 1 < s.card) (a : α) : ∃ b, b ∈ s ∧ b ≠ a := begin obtain ⟨x, hx, y, hy, hxy⟩ := finset.one_lt_card.mp hs, by_cases ha : y = a, { exact ⟨x, hx, ne_of_ne_of_eq hxy ha⟩ }, { exact ⟨y, hy, ha⟩ } end lemma card_eq_succ [decidable_eq α] : s.card = n + 1 ↔ ∃ a t, a ∉ t ∧ insert a t = s ∧ t.card = n := ⟨λ h, let ⟨a, has⟩ := card_pos.mp (h.symm ▸ nat.zero_lt_succ _ : 0 < s.card) in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [h, card_erase_of_mem has, add_tsub_cancel_right]⟩, λ ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat⟩ lemma card_eq_two [decidable_eq α] : s.card = 2 ↔ ∃ x y, x ≠ y ∧ s = {x, y} := begin split, { rw card_eq_succ, simp_rw [card_eq_one], rintro ⟨a, _, hab, rfl, b, rfl⟩, exact ⟨a, b, not_mem_singleton.1 hab, rfl⟩ }, { rintro ⟨x, y, h, rfl⟩, exact card_doubleton h } end lemma card_eq_three [decidable_eq α] : s.card = 3 ↔ ∃ x y z, x ≠ y ∧ x ≠ z ∧ y ≠ z ∧ s = {x, y, z} := begin split, { rw card_eq_succ, simp_rw [card_eq_two], rintro ⟨a, _, abc, rfl, b, c, bc, rfl⟩, rw [mem_insert, mem_singleton, not_or_distrib] at abc, exact ⟨a, b, c, abc.1, abc.2, bc, rfl⟩ }, { rintro ⟨x, y, z, xy, xz, yz, rfl⟩, simp only [xy, xz, yz, mem_insert, card_insert_of_not_mem, not_false_iff, mem_singleton, or_self, card_singleton] } end /-! ### Inductions -/ /-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from the empty set and iterating. This can be used either to define data, or to prove properties. -/ def strong_induction {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) : ∀ (s : finset α), p s | s := H s (λ t h, have t.card < s.card, from card_lt_card h, strong_induction t) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} lemma strong_induction_eq {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) (s : finset α) : strong_induction H s = H s (λ t h, strong_induction H t) := by rw strong_induction /-- Analogue of `strong_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} (s : finset α) : (∀ s, (∀ t ⊂ s, p t) → p s) → p s := λ H, strong_induction H s lemma strong_induction_on_eq {p : finset α → Sort*} (s : finset α) (H : ∀ s, (∀ t ⊂ s, p t) → p s) : s.strong_induction_on H = H s (λ t h, t.strong_induction_on H) := by { dunfold strong_induction_on, rw strong_induction } @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀ t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) /-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than `n`, one knows how to define `p s`. Then one can inductively define `p s` for all finsets `s` of cardinality less than `n`, starting from finsets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strong_downward_induction {p : finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : ∀ (s : finset α), s.card ≤ n → p s | s := H s (λ t ht h, have n - t.card < n - s.card, from (tsub_lt_tsub_iff_left_of_le ht).2 (finset.card_lt_card h), strong_downward_induction t ht) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : finset α), n - t.card)⟩]} lemma strong_downward_induction_eq {p : finset α → Sort*} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : finset α) : strong_downward_induction H s = H s (λ t ht hst, strong_downward_induction H t ht) := by rw strong_downward_induction /-- Analogue of `strong_downward_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_downward_induction_on {p : finset α → Sort*} (s : finset α) (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.card ≤ n → p s := strong_downward_induction H s lemma strong_downward_induction_on_eq {p : finset α → Sort*} (s : finset α) (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.strong_downward_induction_on H = H s (λ t ht h, t.strong_downward_induction_on H ht) := by { dunfold strong_downward_induction_on, rw strong_downward_induction } lemma lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image ( < ) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf end finset
55ba3bdee59e06e80f74773457e47120e90539d4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/intervals/iso_Ioo.lean
1ce9692e865e7818d13a7ddf5ed2ccb57e68c221
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,693
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.monotone.odd import tactic.field_simp /-! # Order isomorphism between a linear ordered field and `(-1, 1)` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we provide an order isomorphism `order_iso_Ioo_neg_one_one` between the open interval `(-1, 1)` in a linear ordered field and the whole field. -/ open set /-- In a linear ordered field, the whole field is order isomorphic to the open interval `(-1, 1)`. We consider the actual implementation to be a "black box", so it is irreducible. -/ @[irreducible] def order_iso_Ioo_neg_one_one (k : Type*) [linear_ordered_field k] : k ≃o Ioo (-1 : k) 1 := begin refine strict_mono.order_iso_of_right_inverse _ _ (λ x, x / (1 - |x|)) _, { refine cod_restrict (λ x, x / (1 + |x|)) _ (λ x, abs_lt.1 _), have H : 0 < 1 + |x|, from (abs_nonneg x).trans_lt (lt_one_add _), calc |x / (1 + |x|)| = |x| / (1 + |x|) : by rw [abs_div, abs_of_pos H] ... < 1 : (div_lt_one H).2 (lt_one_add _) }, { refine (strict_mono_of_odd_strict_mono_on_nonneg _ _).cod_restrict _, { intro x, simp only [abs_neg, neg_div] }, { rintros x (hx : 0 ≤ x) y (hy : 0 ≤ y) hxy, simp [abs_of_nonneg, mul_add, mul_comm x y, div_lt_div_iff, hx.trans_lt (lt_one_add _), hy.trans_lt (lt_one_add _), *] } }, { refine λ x, subtype.ext _, have : 0 < 1 - |(x : k)|, from sub_pos.2 (abs_lt.2 x.2), field_simp [abs_div, this.ne', abs_of_pos this] } end
46a8949b35cde5affb6a7892e0f958505f62266a
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/name.lean
46d5d6a052866ba36934b3138398b205fc65f117
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
4,104
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.ordering.basic init.coe init.data.to_string /-- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/ inductive name | anonymous : name | mk_string : string → name → name | mk_numeral : unsigned → name → name /-- Gadget for automatic parameter support. This is similar to the opt_param gadget, but it uses the tactic declaration names tac_name to synthesize the argument. Like opt_param, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ @[reducible] def {u} auto_param (α : Sort u) (tac_name : name) : Sort u := α @[simp] lemma {u} auto_param_eq (α : Sort u) (n : name) : auto_param α n = α := rfl instance : inhabited name := ⟨name.anonymous⟩ def mk_str_name (n : name) (s : string) : name := name.mk_string s n def mk_num_name (n : name) (v : nat) : name := name.mk_numeral (unsigned.of_nat' v) n def mk_simple_name (s : string) : name := mk_str_name name.anonymous s instance string_to_name : has_coe string name := ⟨mk_simple_name⟩ infix ` <.> `:65 := mk_str_name open name def name.get_prefix : name → name | anonymous := anonymous | (mk_string s p) := p | (mk_numeral s p) := p def name.update_prefix : name → name → name | anonymous new_p := anonymous | (mk_string s p) new_p := mk_string s new_p | (mk_numeral s p) new_p := mk_numeral s new_p -- Without this option, we get errors when defining the following definitions. set_option eqn_compiler.ite false def name.to_string_with_sep (sep : string) : name → string | anonymous := "[anonymous]" | (mk_string s anonymous) := s | (mk_numeral v anonymous) := repr v | (mk_string s n) := name.to_string_with_sep n ++ sep ++ s | (mk_numeral v n) := name.to_string_with_sep n ++ sep ++ repr v private def name.components' : name -> list name | anonymous := [] | (mk_string s n) := mk_string s anonymous :: name.components' n | (mk_numeral v n) := mk_numeral v anonymous :: name.components' n def name.components (n : name) : list name := (name.components' n).reverse protected def name.to_string : name → string := name.to_string_with_sep "." protected def name.repr (n : name) : string := "`" ++ n.to_string instance : has_to_string name := ⟨name.to_string⟩ instance : has_repr name := ⟨name.repr⟩ /- TODO(Leo): provide a definition in Lean. -/ meta constant name.has_decidable_eq : decidable_eq name /-! Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/ meta constant name.cmp : name → name → ordering meta constant name.lex_cmp : name → name → ordering meta constant name.append : name → name → name meta constant name.is_internal : name → bool protected meta def name.lt (a b : name) : Prop := name.cmp a b = ordering.lt meta instance : decidable_rel name.lt := λ a b, ordering.decidable_eq _ _ meta instance : has_lt name := ⟨name.lt⟩ attribute [instance] name.has_decidable_eq meta instance : has_append name := ⟨name.append⟩ /-- `name.append_after n i` return a name of the form n_i -/ meta constant name.append_after : name → nat → name meta def name.is_prefix_of : name → name → bool | p name.anonymous := ff | p n := if p = n then tt else name.is_prefix_of p n.get_prefix meta def name.is_suffix_of : name → name → bool | anonymous _ := tt | (mk_string s n) (mk_string s' n') := (s = s') && name.is_suffix_of n n' | (mk_numeral v n) (mk_numeral v' n') := (v = v') && name.is_suffix_of n n' | _ _ := ff meta def name.replace_prefix : name → name → name → name | anonymous p p' := anonymous | (mk_string s c) p p' := if c = p then mk_string s p' else mk_string s (name.replace_prefix c p p') | (mk_numeral v c) p p' := if c = p then mk_numeral v p' else mk_numeral v (name.replace_prefix c p p')
cf313373a9872fe3334a3620ab9b4e75c5ead83f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/protected.lean
66aa2130683e70b691f721902fa72108c4fe8ec0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,022
lean
namespace Foo protected def x := 10 end Foo open Foo #check x -- error unknown identifier `x` #check Foo.x namespace Bla.Foo protected def y := 20 def z := 30 end Bla.Foo open Bla #check Foo.y open Bla.Foo #check y -- error unknown identifier `y` #check z protected def x := 0 -- Error protected partial def Foo.f (x : Nat) := if x > 0 then f (x-1) * 2 else 1 -- Error protected partial def Bla.f (x : Nat) := if x > 0 then Bla.f (x-1) * 2 else 1 #eval Bla.f 3 namespace Foo protected partial def g (x : Nat) := if x > 0 then g (x-1) * 2 else 1 -- error end Foo namespace Bla protected partial def g (x : Nat) := if x > 0 then Bla.g (x-1) * 2 else 1 #eval g 3 -- error #eval Bla.g 3 end Bla def S (σ : Type) (m : Type → Type) (α : Type) := σ → m (α × σ) namespace S variable {σ : Type} {m : Type → Type} [Monad m] {α : Type} protected def pure (a : α) : S σ m α := fun s => pure (a, s) -- This `pure` is the top-level one. The `pure` being defined here is called `S.pure`. end S
480cb0cfd39bcc5db323099e687c2eb48db2529f
4727251e0cd73359b15b664c3170e5d754078599
/src/model_theory/direct_limit.lean
b228a91cfa896ee54d3d341268f0f4d198178fb7
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
14,744
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.fintype.order import algebra.direct_limit import model_theory.quotients import model_theory.finitely_generated /-! # Direct Limits of First-Order Structures This file constructs the direct limit of a directed system of first-order embeddings. ## Main Definitions * `first_order.language.direct_limit G f` is the direct limit of the directed system `f` of first-order embeddings between the structures indexed by `G`. -/ universes v w u₁ u₂ open_locale first_order namespace first_order namespace language open Structure set variables {L : language} {ι : Type v} [preorder ι] variables {G : ι → Type w} [Π i, L.Structure (G i)] variables (f : Π i j, i ≤ j → G i ↪[L] G j) namespace directed_system /-- A copy of `directed_system.map_self` specialized to `L`-embeddings, as otherwise the `λ i j h, f i j h` can confuse the simplifier. -/ lemma map_self [directed_system G (λ i j h, f i j h)] (i x h) : f i i h x = x := directed_system.map_self (λ i j h, f i j h) i x h /-- A copy of `directed_system.map_map` specialized to `L`-embeddings, as otherwise the `λ i j h, f i j h` can confuse the simplifier. -/ lemma map_map [directed_system G (λ i j h, f i j h)] {i j k} (hij hjk x) : f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x := directed_system.map_map (λ i j h, f i j h) hij hjk x variables {G' : ℕ → Type w} [Π i, L.Structure (G' i)] (f' : Π (n : ℕ), G' n ↪[L] G' (n + 1)) /-- Given a chain of embeddings of structures indexed by `ℕ`, defines a `directed_system` by composing them. -/ def nat_le_rec (m n : ℕ) (h : m ≤ n) : G' m ↪[L] G' n := nat.le_rec_on h (λ k g, (f' k).comp g) (embedding.refl L _) @[simp] lemma coe_nat_le_rec (m n : ℕ) (h : m ≤ n) : (nat_le_rec f' m n h : G' m → G' n) = nat.le_rec_on h (λ n, f' n) := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, ext x, induction k with k ih, { rw [nat_le_rec, nat.le_rec_on_self, embedding.refl_apply, nat.le_rec_on_self] }, { rw [nat.le_rec_on_succ le_self_add, nat_le_rec, nat.le_rec_on_succ le_self_add, ← nat_le_rec, embedding.comp_apply, ih] } end instance nat_le_rec.directed_system : directed_system G' (λ i j h, nat_le_rec f' i j h) := ⟨λ i x h, congr (congr rfl (nat.le_rec_on_self _)) rfl, λ i j k ij jk, by simp [nat.le_rec_on_trans ij jk]⟩ end directed_system namespace direct_limit /-- Raises a family of elements in the `Σ`-type to the same level along the embeddings. -/ def unify {α : Type*} (x : α → (Σ i, G i)) (i : ι) (h : i ∈ upper_bounds (range (sigma.fst ∘ x))) (a : α) : G i := f (x a).1 i (h (mem_range_self a)) (x a).2 variable [directed_system G (λ i j h, f i j h)] @[simp] lemma unify_sigma_mk_self {α : Type*} {i : ι} {x : α → G i} : unify f (sigma.mk i ∘ x) i (λ j ⟨a, hj⟩, trans (le_of_eq hj.symm) (refl _)) = x := begin ext a, simp only [unify, directed_system.map_self], end lemma comp_unify {α : Type*} {x : α → (Σ i, G i)} {i j : ι} (ij : i ≤ j) (h : i ∈ upper_bounds (range (sigma.fst ∘ x))) : (f i j ij) ∘ (unify f x i h) = unify f x j (λ k hk, trans (mem_upper_bounds.1 h k hk) ij) := begin ext a, simp [unify, directed_system.map_map], end end direct_limit variables (G) namespace direct_limit /-- The directed limit glues together the structures along the embeddings. -/ def setoid [directed_system G (λ i j h, f i j h)] [is_directed ι (≤)] : setoid (Σ i, G i) := { r := λ ⟨i, x⟩ ⟨j, y⟩, ∃ (k : ι) (ik : i ≤ k) (jk : j ≤ k), f i k ik x = f j k jk y, iseqv := ⟨λ ⟨i, x⟩, ⟨i, refl i, refl i, rfl⟩, λ ⟨i, x⟩ ⟨j, y⟩ ⟨k, ik, jk, h⟩, ⟨k, jk, ik, h.symm⟩, λ ⟨i, x⟩ ⟨j, y⟩ ⟨k, z⟩ ⟨ij, hiij, hjij, hij⟩ ⟨jk, hjjk, hkjk, hjk⟩, begin obtain ⟨ijk, hijijk, hjkijk⟩ := (directed_of (≤) ij jk), refine ⟨ijk, le_trans hiij hijijk, le_trans hkjk hjkijk, _⟩, rw [← directed_system.map_map, hij, directed_system.map_map], symmetry, rw [← directed_system.map_map, ← hjk, directed_system.map_map], end ⟩ } /-- The structure on the `Σ`-type which becomes the structure on the direct limit after quotienting. -/ noncomputable def sigma_structure [is_directed ι (≤)] [nonempty ι] : L.Structure (Σ i, G i) := { fun_map := λ n F x, ⟨_, fun_map F (unify f x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) (classical.some_spec (fintype.bdd_above_range (λ a, (x a).1))))⟩, rel_map := λ n R x, rel_map R (unify f x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) (classical.some_spec (fintype.bdd_above_range (λ a, (x a).1)))) } end direct_limit /-- The direct limit of a directed system is the structures glued together along the embeddings. -/ def direct_limit [directed_system G (λ i j h, f i j h)] [is_directed ι (≤)] := quotient (direct_limit.setoid G f) local attribute [instance] direct_limit.setoid instance [directed_system G (λ i j h, f i j h)] [is_directed ι (≤)] [inhabited ι] [inhabited (G default)] : inhabited (direct_limit G f) := ⟨⟦⟨default, default⟩⟧⟩ namespace direct_limit variables [is_directed ι (≤)] [directed_system G (λ i j h, f i j h)] lemma equiv_iff {x y : Σ i, G i} {i : ι} (hx : x.1 ≤ i) (hy : y.1 ≤ i) : x ≈ y ↔ (f x.1 i hx) x.2 = (f y.1 i hy) y.2 := begin cases x, cases y, refine ⟨λ xy, _, λ xy, ⟨i, hx, hy, xy⟩⟩, obtain ⟨j, _, _, h⟩ := xy, obtain ⟨k, ik, jk⟩ := directed_of (≤) i j, have h := congr_arg (f j k jk) h, apply (f i k ik).injective, rw [directed_system.map_map, directed_system.map_map] at *, exact h end lemma fun_map_unify_equiv {n : ℕ} (F : L.functions n) (x : (fin n) → (Σ i, G i)) (i j : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) (hj : j ∈ upper_bounds (range (sigma.fst ∘ x))) : (⟨i, fun_map F (unify f x i hi)⟩ : Σ i, G i) ≈ ⟨j, fun_map F (unify f x j hj)⟩ := begin obtain ⟨k, ik, jk⟩ := directed_of (≤) i j, refine ⟨k, ik, jk, _⟩, rw [(f i k ik).map_fun, (f j k jk).map_fun, comp_unify, comp_unify], end lemma rel_map_unify_equiv {n : ℕ} (R : L.relations n) (x : (fin n) → (Σ i, G i)) (i j : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) (hj : j ∈ upper_bounds (range (sigma.fst ∘ x))) : rel_map R (unify f x i hi) = rel_map R (unify f x j hj) := begin obtain ⟨k, ik, jk⟩ := directed_of (≤) i j, rw [← (f i k ik).map_rel, comp_unify, ← (f j k jk).map_rel, comp_unify], end variable [nonempty ι] lemma exists_unify_eq {α : Type*} [fintype α] {x y : α → (Σ i, G i)} (xy : x ≈ y) : ∃ (i : ι) (hx : i ∈ upper_bounds (range (sigma.fst ∘ x))) (hy : i ∈ upper_bounds (range (sigma.fst ∘ y))), unify f x i hx = unify f y i hy := begin obtain ⟨i, hi⟩ := fintype.bdd_above_range (sum.elim (λ a, (x a).1) (λ a, (y a).1)), rw [sum.elim_range, upper_bounds_union] at hi, simp_rw [← function.comp_apply sigma.fst _] at hi, exact ⟨i, hi.1, hi.2, funext (λ a, (equiv_iff G f _ _).1 (xy a))⟩, end lemma fun_map_equiv_unify {n : ℕ} (F : L.functions n) (x : (fin n) → (Σ i, G i)) (i : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) : @fun_map _ _ (sigma_structure G f) _ F x ≈ ⟨_, fun_map F (unify f x i hi)⟩ := fun_map_unify_equiv G f F x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) i _ hi lemma rel_map_equiv_unify {n : ℕ} (R : L.relations n) (x : (fin n) → (Σ i, G i)) (i : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) : @rel_map _ _ (sigma_structure G f) _ R x = rel_map R (unify f x i hi) := rel_map_unify_equiv G f R x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) i _ hi /-- The direct limit `setoid` respects the structure `sigma_structure`, so quotienting by it gives rise to a valid structure. -/ noncomputable instance prestructure : L.prestructure (direct_limit.setoid G f) := { to_structure := sigma_structure G f, fun_equiv := λ n F x y xy, begin obtain ⟨i, hx, hy, h⟩ := exists_unify_eq G f xy, refine setoid.trans (fun_map_equiv_unify G f F x i hx) (setoid.trans _ (setoid.symm (fun_map_equiv_unify G f F y i hy))), rw h, end, rel_equiv := λ n R x y xy, begin obtain ⟨i, hx, hy, h⟩ := exists_unify_eq G f xy, refine trans (rel_map_equiv_unify G f R x i hx) (trans _ (symm (rel_map_equiv_unify G f R y i hy))), rw h, end } /-- The `L.Structure` on a direct limit of `L.Structure`s. -/ noncomputable instance Structure : L.Structure (direct_limit G f) := language.quotient_structure @[simp] lemma fun_map_quotient_mk_sigma_mk {n : ℕ} {F : L.functions n} {i : ι} {x : fin n → G i} : fun_map F (λ a, (⟦⟨i, x a⟩⟧ : direct_limit G f)) = ⟦⟨i, fun_map F x⟩⟧ := begin simp only [function.comp_app, fun_map_quotient_mk, quotient.eq], obtain ⟨k, ik, jk⟩ := directed_of (≤) i (classical.some (fintype.bdd_above_range (λ (a : fin n), i))), refine ⟨k, jk, ik, _⟩, simp only [embedding.map_fun, comp_unify], refl end @[simp] lemma rel_map_quotient_mk_sigma_mk {n : ℕ} {R : L.relations n} {i : ι} {x : fin n → G i} : rel_map R (λ a, (⟦⟨i, x a⟩⟧ : direct_limit G f)) = rel_map R x := begin rw [rel_map_quotient_mk], obtain ⟨k, ik, jk⟩ := directed_of (≤) i (classical.some (fintype.bdd_above_range (λ (a : fin n), i))), rw [rel_map_equiv_unify G f R (λ a, ⟨i, x a⟩) i, unify_sigma_mk_self], end lemma exists_quotient_mk_sigma_mk_eq {α : Type*} [fintype α] (x : α → direct_limit G f) : ∃ (i : ι) (y : α → G i), x = quotient.mk ∘ (sigma.mk i) ∘ y := begin obtain ⟨i, hi⟩ := fintype.bdd_above_range (λ a, (x a).out.1), refine ⟨i, unify f (quotient.out ∘ x) i hi, _⟩, ext a, rw [quotient.eq_mk_iff_out, function.comp_app, unify, equiv_iff G f _], { simp only [directed_system.map_self] }, { refl } end variables (L ι) /-- The canonical map from a component to the direct limit. -/ def of (i : ι) : G i ↪[L] direct_limit G f := { to_fun := quotient.mk ∘ sigma.mk i, inj' := λ x y h, begin simp only [quotient.eq] at h, obtain ⟨j, h1, h2, h3⟩ := h, exact (f i j h1).injective h3, end } variables {L ι G f} @[simp] lemma of_apply {i : ι} {x : G i} : of L ι G f i x = ⟦⟨i, x⟩⟧ := rfl @[simp] lemma of_f {i j : ι} {hij : i ≤ j} {x : G i} : (of L ι G f j (f i j hij x)) = of L ι G f i x := begin simp only [of_apply, quotient.eq], refine setoid.symm ⟨j, hij, refl j, _⟩, simp only [directed_system.map_self], end /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : ∃ i x, of L ι G f i x = z := ⟨z.out.1, z.out.2, by simp⟩ @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of L ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [L.Structure P] (g : Π i, G i ↪[L] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (L ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f ↪[L] P := { to_fun := quotient.lift (λ (x : Σ i, G i), (g x.1) x.2) (λ x y xy, begin simp only, obtain ⟨i, hx, hy⟩ := directed_of (≤) x.1 y.1, rw [← Hg x.1 i hx, ← Hg y.1 i hy], exact congr_arg _ ((equiv_iff _ _ _ _).1 xy), end), inj' := λ x y xy, begin rw [← quotient.out_eq x, ← quotient.out_eq y, quotient.lift_mk, quotient.lift_mk] at xy, obtain ⟨i, hx, hy⟩ := directed_of (≤) x.out.1 y.out.1, rw [← Hg x.out.1 i hx, ← Hg y.out.1 i hy] at xy, rw [← quotient.out_eq x, ← quotient.out_eq y, quotient.eq, equiv_iff G f hx hy], exact (g i).injective xy, end, map_fun' := λ n F x, begin obtain ⟨i, y, rfl⟩ := exists_quotient_mk_sigma_mk_eq G f x, rw [fun_map_quotient_mk_sigma_mk, ← function.comp.assoc, quotient.lift_comp_mk], simp only [quotient.lift_mk, embedding.map_fun], end, map_rel' := λ n R x, begin obtain ⟨i, y, rfl⟩ := exists_quotient_mk_sigma_mk_eq G f x, rw [rel_map_quotient_mk_sigma_mk G f, ← (g i).map_rel R y, ← function.comp.assoc, quotient.lift_comp_mk], end } variables {L ι G f} omit Hg @[simp] lemma lift_quotient_mk_sigma_mk {i} (x : G i) : lift L ι G f g Hg (⟦⟨i, x⟩⟧) = (g i) x := begin change (lift L ι G f g Hg).to_fun (⟦⟨i, x⟩⟧) = _, simp only [lift, quotient.lift_mk], end lemma lift_of {i} (x : G i) : lift L ι G f g Hg (of L ι G f i x) = g i x := by simp theorem lift_unique (F : direct_limit G f ↪[L] P) (x) : F x = lift L ι G f (λ i, F.comp $ of L ι G f i) (λ i j hij x, by rw [F.comp_apply, F.comp_apply, of_f]) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl /-- The direct limit of countably many countably generated structures is countably generated. -/ theorem cg {ι : Type*} [encodable ι] [preorder ι] [is_directed ι (≤)] [nonempty ι] {G : ι → Type w} [Π i, L.Structure (G i)] (f : Π i j, i ≤ j → G i ↪[L] G j) (h : ∀ i, Structure.cg L (G i)) [directed_system G (λ i j h, f i j h)] : Structure.cg L (direct_limit G f) := begin refine ⟨⟨⋃ i, direct_limit.of L ι G f i '' (classical.some (h i).out), _, _⟩⟩, { exact set.countable_Union (λ i, set.countable.image (classical.some_spec (h i).out).1 _) }, { rw [eq_top_iff, substructure.closure_Union], simp_rw [← embedding.coe_to_hom, substructure.closure_image], rw le_supr_iff, intros S hS x hx, let out := @quotient.out _ (direct_limit.setoid G f), refine hS (out x).1 ⟨(out x).2, _, _⟩, { rw [(classical.some_spec (h (out x).1).out).2], simp only [substructure.coe_top] }, { simp only [embedding.coe_to_hom, direct_limit.of_apply, sigma.eta, quotient.out_eq] } } end instance cg' {ι : Type*} [encodable ι] [preorder ι] [is_directed ι (≤)] [nonempty ι] {G : ι → Type w} [Π i, L.Structure (G i)] (f : Π i j, i ≤ j → G i ↪[L] G j) [h : ∀ i, Structure.cg L (G i)] [directed_system G (λ i j h, f i j h)] : Structure.cg L (direct_limit G f) := cg f h end direct_limit end language end first_order
a61f73c1437c8d5b32e593983cbaab6add4bf354
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/products/bifunctor.lean
805e65ffc4b02e7faab316bd8e6cbb17bcaa7166
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,819
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 -/ import category_theory.products.basic open category_theory namespace category_theory.bifunctor universes v₁ v₂ v₃ u₁ u₂ u₃ variables {C : Type u₁} {D : Type u₂} {E : Type u₃} variables [category.{v₁} C] [category.{v₂} D] [category.{v₃} E] @[simp] lemma map_id (F : (C × D) ⥤ E) (X : C) (Y : D) : F.map ((𝟙 X, 𝟙 Y) : (X, Y) ⟶ (X, Y)) = 𝟙 (F.obj (X, Y)) := F.map_id (X, Y) @[simp] lemma map_id_comp (F : (C × D) ⥤ E) (W : C) {X Y Z : D} (f : X ⟶ Y) (g : Y ⟶ Z) : F.map ((𝟙 W, f ≫ g) : (W, X) ⟶ (W, Z)) = F.map ((𝟙 W, f) : (W, X) ⟶ (W, Y)) ≫ F.map ((𝟙 W, g) : (W, Y) ⟶ (W, Z)) := by rw [←functor.map_comp,prod_comp,category.comp_id] @[simp] lemma map_comp_id (F : (C × D) ⥤ E) (X Y Z : C) (W : D) (f : X ⟶ Y) (g : Y ⟶ Z) : F.map ((f ≫ g, 𝟙 W) : (X, W) ⟶ (Z, W)) = F.map ((f, 𝟙 W) : (X, W) ⟶ (Y, W)) ≫ F.map ((g, 𝟙 W) : (Y, W) ⟶ (Z, W)) := by rw [←functor.map_comp,prod_comp,category.comp_id] @[simp] lemma diagonal (F : (C × D) ⥤ E) (X X' : C) (f : X ⟶ X') (Y Y' : D) (g : Y ⟶ Y') : F.map ((𝟙 X, g) : (X, Y) ⟶ (X, Y')) ≫ F.map ((f, 𝟙 Y') : (X, Y') ⟶ (X', Y')) = F.map ((f, g) : (X, Y) ⟶ (X', Y')) := by rw [←functor.map_comp, prod_comp, category.id_comp, category.comp_id] @[simp] lemma diagonal' (F : (C × D) ⥤ E) (X X' : C) (f : X ⟶ X') (Y Y' : D) (g : Y ⟶ Y') : F.map ((f, 𝟙 Y) : (X, Y) ⟶ (X', Y)) ≫ F.map ((𝟙 X', g) : (X', Y) ⟶ (X', Y')) = F.map ((f, g) : (X, Y) ⟶ (X', Y')) := by rw [←functor.map_comp, prod_comp, category.id_comp, category.comp_id] end category_theory.bifunctor
f097ed3e78336ef622262611686f478f48b0ec82
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/filter/small_sets.lean
96269fff4611391672d1b47368052c063cac9b6a
[ "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
5,257
lean
/- Copyright (c) 2022 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Floris van Doorn, Yury Kudryashov -/ import order.filter.lift import order.filter.at_top_bot /-! # The filter of small sets This file defines the filter of small sets w.r.t. a filter `f`, which is the largest filter containing all powersets of members of `f`. `g` converges to `f.small_sets` if for all `s ∈ f`, eventually we have `g x ⊆ s`. An example usage is that if `f : ι → E → ℝ` is a family of nonnegative functions with integral 1, then saying that `λ i, support (f i)` tendsto `(𝓝 0).small_sets` is a way of saying that `f` tends to the Dirac delta distribution. -/ open_locale filter open filter set variables {α β : Type*} {ι : Sort*} namespace filter variables {l l' la : filter α} {lb : filter β} /-- The filter `l.small_sets` is the largest filter containing all powersets of members of `l`. -/ def small_sets (l : filter α) : filter (set α) := l.lift' powerset lemma small_sets_eq_generate {f : filter α} : f.small_sets = generate (powerset '' f.sets) := by { simp_rw [generate_eq_binfi, small_sets, infi_image], refl } lemma has_basis.small_sets {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) : has_basis l.small_sets p (λ i, 𝒫 (s i)) := h.lift' monotone_powerset lemma has_basis_small_sets (l : filter α) : has_basis l.small_sets (λ t : set α, t ∈ l) powerset := l.basis_sets.small_sets /-- `g` converges to `f.small_sets` if for all `s ∈ f`, eventually we have `g x ⊆ s`. -/ lemma tendsto_small_sets_iff {f : α → set β} : tendsto f la lb.small_sets ↔ ∀ t ∈ lb, ∀ᶠ x in la, f x ⊆ t := (has_basis_small_sets lb).tendsto_right_iff lemma eventually_small_sets {p : set α → Prop} : (∀ᶠ s in l.small_sets, p s) ↔ ∃ s ∈ l, ∀ t ⊆ s, p t := eventually_lift'_iff monotone_powerset lemma eventually_small_sets' {p : set α → Prop} (hp : ∀ ⦃s t⦄, s ⊆ t → p t → p s) : (∀ᶠ s in l.small_sets, p s) ↔ ∃ s ∈ l, p s := eventually_small_sets.trans $ exists₂_congr $ λ s hsf, ⟨λ H, H s subset.rfl, λ hs t ht, hp ht hs⟩ lemma frequently_small_sets {p : set α → Prop} : (∃ᶠ s in l.small_sets, p s) ↔ ∀ t ∈ l, ∃ s ⊆ t, p s := l.has_basis_small_sets.frequently_iff lemma frequently_small_sets_mem (l : filter α) : ∃ᶠ s in l.small_sets, s ∈ l := frequently_small_sets.2 $ λ t ht, ⟨t, subset.rfl, ht⟩ lemma has_antitone_basis.tendsto_small_sets {ι} [preorder ι] {s : ι → set α} (hl : l.has_antitone_basis s) : tendsto s at_top l.small_sets := tendsto_small_sets_iff.2 $ λ t ht, hl.eventually_subset ht @[mono] lemma monotone_small_sets : monotone (@small_sets α) := monotone_lift' monotone_id monotone_const @[simp] lemma small_sets_bot : (⊥ : filter α).small_sets = pure ∅ := by rw [small_sets, lift'_bot monotone_powerset, powerset_empty, principal_singleton] @[simp] lemma small_sets_top : (⊤ : filter α).small_sets = ⊤ := by rw [small_sets, lift'_top, powerset_univ, principal_univ] @[simp] lemma small_sets_principal (s : set α) : (𝓟 s).small_sets = 𝓟(𝒫 s) := lift'_principal monotone_powerset lemma small_sets_comap (l : filter β) (f : α → β) : (comap f l).small_sets = l.lift' (powerset ∘ preimage f) := comap_lift'_eq2 monotone_powerset lemma comap_small_sets (l : filter β) (f : α → set β) : comap f l.small_sets = l.lift' (preimage f ∘ powerset) := comap_lift'_eq lemma small_sets_infi {f : ι → filter α} : (infi f).small_sets = (⨅ i, (f i).small_sets) := lift'_infi_of_map_univ powerset_inter powerset_univ lemma small_sets_inf (l₁ l₂ : filter α) : (l₁ ⊓ l₂).small_sets = l₁.small_sets ⊓ l₂.small_sets := lift'_inf _ _ powerset_inter instance small_sets_ne_bot (l : filter α) : ne_bot l.small_sets := (lift'_ne_bot_iff monotone_powerset).2 $ λ _ _, powerset_nonempty lemma tendsto.small_sets_mono {s t : α → set β} (ht : tendsto t la lb.small_sets) (hst : ∀ᶠ x in la, s x ⊆ t x) : tendsto s la lb.small_sets := begin rw [tendsto_small_sets_iff] at ht ⊢, exact λ u hu, (ht u hu).mp (hst.mono $ λ a hst ht, subset.trans hst ht) end @[simp] lemma eventually_small_sets_eventually {p : α → Prop} : (∀ᶠ s in l.small_sets, ∀ᶠ x in l', x ∈ s → p x) ↔ ∀ᶠ x in l ⊓ l', p x := calc _ ↔ ∃ s ∈ l, ∀ᶠ x in l', x ∈ s → p x : eventually_small_sets' $ λ s t hst ht, ht.mono $ λ x hx hs, hx (hst hs) ... ↔ ∃ (s ∈ l) (t ∈ l'), ∀ x, x ∈ t → x ∈ s → p x : by simp only [eventually_iff_exists_mem] ... ↔ ∀ᶠ x in l ⊓ l', p x : by simp only [eventually_inf, and_comm, mem_inter_iff, ← and_imp] @[simp] lemma eventually_small_sets_forall {p : α → Prop} : (∀ᶠ s in l.small_sets, ∀ x ∈ s, p x) ↔ ∀ᶠ x in l, p x := by simpa only [inf_top_eq, eventually_top] using @eventually_small_sets_eventually α l ⊤ p alias eventually_small_sets_forall ↔ eventually.of_small_sets eventually.small_sets @[simp] lemma eventually_small_sets_subset {s : set α} : (∀ᶠ t in l.small_sets, t ⊆ s) ↔ s ∈ l := eventually_small_sets_forall end filter
3d1df3ef69d78c2db35db786aa3a4e0fd5f9edc8
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/complex/polynomial.lean
7a7bd7cbe7eaa1a04a253e397000bc2003495490
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,622
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import analysis.special_functions.pow import field_theory.algebraic_closure import topology.algebra.polynomial /-! # The fundamental theorem of algebra This file proves that every nonconstant complex polynomial has a root. As a consequence, the complex numbers are algebraically closed. -/ open complex polynomial metric filter is_absolute_value set open_locale classical namespace complex /- The following proof uses the method given at <https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/ /-- The fundamental theorem of algebra. Every non constant complex polynomial has a root. -/ lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z := let ⟨z₀, hz₀⟩ := f.exists_forall_norm_le in exists.intro z₀ $ classical.by_contradiction $ λ hf0, have hfX : f - C (f.eval z₀) ≠ 0, from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)), let n := root_multiplicity z₀ (f - C (f.eval z₀)) in let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0, let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous g) z₀ ((g.eval z₀).abs) (complex.abs_pos.2 hg0) in let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0, have hg0' : 0 < abs (eval z₀ g), from complex.abs_pos.2 hg0, have hfg0 : 0 < (f.eval z₀).abs / abs (eval z₀ g), from div_pos hf0' hg0', have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0), have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs, from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz]; exact ((min_le_left _ _).trans (min_le_left _ _)).trans_lt (half_lt_self hδ'₁)), have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n / ((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀), mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv', inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1, from (div_lt_one hf0').2 $ (lt_div_iff' hg0').1 $ calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0 ... = δ : pow_one _ ... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self (div_pos hf0' hg0'), have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n, from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁ ... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv, sub_eq_add_neg]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'z₀ : abs (z' - z₀) = δ, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel, sub_eq_add_neg, add_assoc] ... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀ ... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀), lt_irrefl (f.eval z₀).abs $ calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n : add_lt_add_of_le_of_lt (by rw hF₂) hF₃ ... = (f.eval z₀).abs : sub_add_cancel _ _ instance is_alg_closed : is_alg_closed ℂ := is_alg_closed.of_exists_root _ $ λ p _ hp, complex.exists_root $ degree_pos_of_irreducible hp end complex
218c930ab8b3348fb0c34de1926a293b0f88e55b
4727251e0cd73359b15b664c3170e5d754078599
/archive/examples/prop_encodable.lean
64da2837b4f0bad5499490f2f3bb90a74516be79
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,982
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.W.basic /-! # W types The file `data/W.lean` shows that if `α` is an an encodable fintype and for every `a : α`, `β a` is encodable, then `W β` is encodable. As an example of how this can be used, we show that the type of propositional formulas with variables labeled from an encodable type is encodable. The strategy is to define a type of labels corresponding to the constructors. From the definition (using `sum`, `unit`, and an encodable type), Lean can infer that it is encodable. We then define a map from propositional formulas to the corresponding `Wfin` type, and show that map has a left inverse. We mark the auxiliary constructions `private`, since their only purpose is to show encodability. -/ /-- Propositional formulas with labels from `α`. -/ inductive prop_form (α : Type*) | var : α → prop_form | not : prop_form → prop_form | and : prop_form → prop_form → prop_form | or : prop_form → prop_form → prop_form /-! The next three functions make it easier to construct functions from a small `fin`. -/ section variable {α : Type*} /-- the trivial function out of `fin 0`. -/ def mk_fn0 : fin 0 → α | ⟨_, h⟩ := absurd h dec_trivial /-- defines a function out of `fin 1` -/ def mk_fn1 (t : α) : fin 1 → α | ⟨0, _⟩ := t | ⟨n+1, h⟩ := absurd h dec_trivial /-- defines a function out of `fin 2` -/ def mk_fn2 (s t : α) : fin 2 → α | ⟨0, _⟩ := s | ⟨1, _⟩ := t | ⟨n+2, h⟩ := absurd h dec_trivial attribute [simp] mk_fn0 mk_fn1 mk_fn2 end namespace prop_form private def constructors (α : Type*) := α ⊕ unit ⊕ unit ⊕ unit local notation `cvar` a := sum.inl a local notation `cnot` := sum.inr (sum.inl unit.star) local notation `cand` := sum.inr (sum.inr (sum.inr unit.star)) local notation `cor` := sum.inr (sum.inr (sum.inl unit.star)) @[simp] private def arity (α : Type*) : constructors α → nat | (cvar a) := 0 | cnot := 1 | cand := 2 | cor := 2 variable {α : Type*} private def f : prop_form α → W_type (λ i, fin (arity α i)) | (var a) := ⟨cvar a, mk_fn0⟩ | (not p) := ⟨cnot, mk_fn1 (f p)⟩ | (and p q) := ⟨cand, mk_fn2 (f p) (f q)⟩ | (or p q) := ⟨cor, mk_fn2 (f p) (f q)⟩ private def finv : W_type (λ i, fin (arity α i)) → prop_form α | ⟨cvar a, fn⟩ := var a | ⟨cnot, fn⟩ := not (finv (fn ⟨0, dec_trivial⟩)) | ⟨cand, fn⟩ := and (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩)) | ⟨cor, fn⟩ := or (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩)) instance [encodable α] : encodable (prop_form α) := begin haveI : encodable (constructors α), { unfold constructors, apply_instance }, exact encodable.of_left_inverse f finv (by { intro p, induction p; simp [f, finv, *] }) end end prop_form
4023e20deba7d981dd1c1d61bc49ad778b710bd9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/intNegSucc.lean
d9e9089290b572d762f5fb10c9af7cd1903e0878
[ "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
570
lean
def Int64Min : Int := -1*(Int.ofNat ((UInt64.size / 2))) #eval Int.negSucc 9223372036854775807 #reduce Int.negSucc 9223372036854775807 #print "---" #eval - Int.negSucc 9223372036854775807 #reduce - Int.negSucc 9223372036854775807 #print "---" #eval Int.negSucc 9223372036854775807 == 0 #reduce Int.negSucc 9223372036854775807 == 0 #print "---" #eval Int.negSucc 9223372036854775807 == Int64Min #reduce Int.negSucc 9223372036854775807 == Int64Min #print "---" #eval (Int.negSucc 9223372036854775807) + 1 == 1 #reduce (Int.negSucc 9223372036854775807) + 1 == 1
886d1a7e190098ea0f07330934ccbddbd9b4d211
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/big_operators/pi.lean
7ad8db101e32df8e28f6e07aaf03a6361ffbb8ad
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,658
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.ring.pi import algebra.big_operators.basic import data.fintype.basic import algebra.group.prod /-! # Big operators for Pi Types This file contains theorems relevant to big operators in binary and arbitrary product of monoids and groups -/ open_locale big_operators namespace pi @[to_additive] lemma list_prod_apply {α : Type*} {β : α → Type*} [Πa, monoid (β a)] (a : α) (l : list (Πa, β a)) : l.prod a = (l.map (λf:Πa, β a, f a)).prod := (monoid_hom.apply β a).map_list_prod _ @[to_additive] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := (monoid_hom.apply β a).map_multiset_prod _ end pi @[simp, to_additive] lemma finset.prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a := (monoid_hom.apply β a).map_prod _ _ @[simp, to_additive] lemma fintype.prod_apply {α : Type*} {β : α → Type*} {γ : Type*} [fintype γ] [∀a, comm_monoid (β a)] (a : α) (g : γ → Πa, β a) : (∏ c, g c) a = ∏ c, g c a := finset.prod_apply a finset.univ g @[simp, to_additive] lemma monoid_hom.finset_prod_apply {ι M N : Type*} [monoid M] [comm_monoid N] (f : ι → M →* N) (s : finset ι) (a : M) : (∏ i in s, f i) a = ∏ i in s, f i a := (monoid_hom.eval a).map_prod _ _ @[to_additive prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) section single variables {I : Type*} [decidable_eq I] {Z : I → Type*} variables [Π i, add_comm_monoid (Z i)] -- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here. lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) : ∑ i, pi.single i (f i) = f := begin ext a, rw [finset.sum_apply, finset.sum_eq_single a], { simp, }, { intros b _ h, simp [h.symm], }, { intro h, exfalso, simpa using h, }, end @[ext] lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Π i, Z i) →+ G) (w : ∀ (i : I) (x : Z i), g (pi.single i x) = h (pi.single i x)) : g = h := begin ext k, rw [←finset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum], apply finset.sum_congr rfl, intros, apply w, end end single section ring_hom open pi variables {I : Type*} [decidable_eq I] {f : I → Type*} variables [Π i, semiring (f i)] -- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances -- on `Π i, f i` @[ext] lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin apply ring_hom.coe_add_monoid_hom_injective, convert add_monoid_hom.functions_ext _ _ _ _; assumption end end ring_hom namespace prod variables {α β γ : Type*} [comm_monoid α] [comm_monoid β] {s : finset γ} {f : γ → α × β} @[to_additive] lemma fst_prod : (∏ c in s, f c).1 = ∏ c in s, (f c).1 := (monoid_hom.fst α β).map_prod f s @[to_additive] lemma snd_prod : (∏ c in s, f c).2 = ∏ c in s, (f c).2 := (monoid_hom.snd α β).map_prod f s end prod
d847ea1902ad7dfd4b716564805810bdce7328a1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/module/ordered_auto.lean
6b623ac69e89f7036513e423949e764af51d7262
[]
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
8,901
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.pi import Mathlib.algebra.ordered_pi import Mathlib.algebra.module.prod import Mathlib.algebra.ordered_field import Mathlib.PostPort universes u_1 u_2 l u_3 namespace Mathlib /-! # Ordered semimodules In this file we define * `ordered_semimodule R M` : an ordered additive commutative monoid `M` is an `ordered_semimodule` over an `ordered_semiring` `R` if the scalar product respects the order relation on the monoid and on the ring. There is a correspondence between this structure and convex cones, which is proven in `analysis/convex/cone.lean`. ## Implementation notes * We choose to define `ordered_semimodule` as a `Prop`-valued mixin, so that it can be used for both modules and algebras (the axioms for an "ordered algebra" are exactly that the algebra is ordered as a module). * To get ordered modules and ordered vector spaces, it suffices to the replace the `order_add_comm_monoid` and the `ordered_semiring` as desired. ## References * https://en.wikipedia.org/wiki/Ordered_vector_space ## Tags ordered semimodule, ordered module, ordered vector space -/ /-- An ordered semimodule is an ordered additive commutative monoid with a partial order in which the scalar multiplication is compatible with the order. -/ class ordered_semimodule (R : Type u_1) (M : Type u_2) [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] where smul_lt_smul_of_pos : ∀ {a b : M} {c : R}, a < b → 0 < c → c • a < c • b lt_of_smul_lt_smul_of_pos : ∀ {a b : M} {c : R}, c • a < c • b → 0 < c → a < b theorem smul_lt_smul_of_pos {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} : a < b → 0 < c → c • a < c • b := ordered_semimodule.smul_lt_smul_of_pos theorem smul_le_smul_of_nonneg {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c • a ≤ c • b := sorry theorem eq_of_smul_eq_smul_of_pos_of_le {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (h₁ : c • a = c • b) (hc : 0 < c) (hle : a ≤ b) : a = b := or.resolve_left (has_le.le.lt_or_eq hle) fun (hlt : a < b) => has_lt.lt.ne (smul_lt_smul_of_pos hlt hc) h₁ theorem lt_of_smul_lt_smul_of_nonneg {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (h : c • a < c • b) (hc : 0 ≤ c) : a < b := sorry theorem smul_lt_smul_iff_of_pos {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (hc : 0 < c) : c • a < c • b ↔ a < b := { mp := fun (h : c • a < c • b) => lt_of_smul_lt_smul_of_nonneg h (has_lt.lt.le hc), mpr := fun (h : a < b) => smul_lt_smul_of_pos h hc } theorem smul_pos_iff_of_pos {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {c : R} (hc : 0 < c) : 0 < c • a ↔ 0 < a := iff.trans (eq.mpr (id (Eq._oldrec (Eq.refl (0 < c • a ↔ c • 0 < c • a)) (smul_zero c))) (iff.refl (0 < c • a))) (smul_lt_smul_iff_of_pos hc) /-- If `R` is a linear ordered semifield, then it suffices to verify only the first axiom of `ordered_semimodule`. Moreover, it suffices to verify that `a < b` and `0 < c` imply `c • a ≤ c • b`. We have no semifields in `mathlib`, so we use the assumption `∀ c ≠ 0, is_unit c` instead. -/ theorem ordered_semimodule.mk'' {R : Type u_1} {M : Type u_2} [linear_ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] (hR : ∀ {c : R}, c ≠ 0 → is_unit c) (hlt : ∀ {a b : M} {c : R}, a < b → 0 < c → c • a ≤ c • b) : ordered_semimodule R M := sorry /-- If `R` is a linear ordered field, then it suffices to verify only the first axiom of `ordered_semimodule`. -/ theorem ordered_semimodule.mk' {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_monoid M] [semimodule k M] (hlt : ∀ {a b : M} {c : k}, a < b → 0 < c → c • a ≤ c • b) : ordered_semimodule k M := ordered_semimodule.mk'' (fun (c : k) (hc : c ≠ 0) => is_unit.mk0 c hc) hlt protected instance linear_ordered_semiring.to_ordered_semimodule {R : Type u_1} [linear_ordered_semiring R] : ordered_semimodule R R := ordered_semimodule.mk ordered_semiring.mul_lt_mul_of_pos_left fun (_x _x_1 _x_2 : R) (h : _x_2 • _x < _x_2 • _x_1) (hc : 0 < _x_2) => lt_of_mul_lt_mul_left h (has_lt.lt.le hc) theorem smul_le_smul_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : c • a ≤ c • b ↔ a ≤ b := sorry theorem smul_le_smul_iff_of_neg {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : c < 0) : c • a ≤ c • b ↔ b ≤ a := sorry theorem smul_lt_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : c • a < b ↔ a < c⁻¹ • b := sorry theorem smul_le_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : c • a ≤ b ↔ a ≤ c⁻¹ • b := sorry theorem le_smul_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : a ≤ c • b ↔ c⁻¹ • a ≤ b := sorry protected instance prod.ordered_semimodule {k : Type u_1} {M : Type u_2} {N : Type u_3} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] [ordered_add_comm_group N] [semimodule k N] [ordered_semimodule k N] : ordered_semimodule k (M × N) := ordered_semimodule.mk' fun (v u : M × N) (c : k) (h : v < u) (hc : 0 < c) => { left := smul_le_smul_of_nonneg (and.left (and.left h)) (has_lt.lt.le hc), right := smul_le_smul_of_nonneg (and.right (and.left h)) (has_lt.lt.le hc) } protected instance pi.ordered_semimodule {k : Type u_1} [linear_ordered_field k] {ι : Type u_2} {M : ι → Type u_3} [(i : ι) → ordered_add_comm_group (M i)] [(i : ι) → semimodule k (M i)] [∀ (i : ι), ordered_semimodule k (M i)] : ordered_semimodule k ((i : ι) → M i) := ordered_semimodule.mk' fun (v u : (i : ι) → M i) (c : k) (h : v < u) (hc : 0 < c) (i : ι) => id (smul_le_smul_of_nonneg (has_lt.lt.le h i) (has_lt.lt.le hc)) -- Sometimes Lean fails to apply the dependent version to non-dependent functions, -- so we define another instance protected instance pi.ordered_semimodule' {k : Type u_1} [linear_ordered_field k] {ι : Type u_2} {M : Type u_3} [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] : ordered_semimodule k (ι → M) := pi.ordered_semimodule protected instance order_dual.has_scalar {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : has_scalar R (order_dual M) := has_scalar.mk has_scalar.smul protected instance order_dual.mul_action {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : mul_action R (order_dual M) := mul_action.mk sorry sorry protected instance order_dual.distrib_mul_action {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : distrib_mul_action R (order_dual M) := distrib_mul_action.mk sorry sorry protected instance order_dual.semimodule {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : semimodule R (order_dual M) := semimodule.mk sorry sorry protected instance order_dual.ordered_semimodule {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] : ordered_semimodule R (order_dual M) := ordered_semimodule.mk (fun (a b : order_dual M) => ordered_semimodule.smul_lt_smul_of_pos) fun (a b : order_dual M) => ordered_semimodule.lt_of_smul_lt_smul_of_pos end Mathlib
35b773d1b6a15596cb53acfd489c0d07b63422c3
9cba98daa30c0804090f963f9024147a50292fa0
/old/src/classical_geometry_test.lean
aee05ab64abc460025f1daaa13ce3259141b8135
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
107
lean
import .classical_geometry noncomputable def aGeom1DSpace : classicalGeometry := classicalGeometry.mk 0 1
364e80023a08e810b0e604e3a84b35ffe3338697
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/tests/lean/unifier_bug.lean
af6f1136d45464c3e191ae5842e211a32ea3ba06
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
200
lean
import logic theorem test {A B : Type} {a : A} {b : B} (H : a == b) : eq.rec_on (heq.type_eq H) a = b := -- Remark the error message should not occur in the token theorem heq.rec_on H rfl
3edfe055151f41ed906a9d0bb75cc30c242605ab
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/continuous_function/algebra.lean
1fdde95a636b9637b3011350f3ac31de229bd547
[ "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
33,360
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Nicolò Cavalleri -/ import topology.algebra.module.basic import topology.continuous_function.ordered import topology.algebra.uniform_group import topology.uniform_space.compact_convergence import topology.algebra.star import algebra.algebra.subalgebra.basic import tactic.field_simp /-! # Algebraic structures over continuous functions In this file we define instances of algebraic structures over the type `continuous_map α β` (denoted `C(α, β)`) of **bundled** continuous maps from `α` to `β`. For example, `C(α, β)` is a group when `β` is a group, a ring when `β` is a ring, etc. For each type of algebraic structure, we also define an appropriate subobject of `α → β` with carrier `{ f : α → β | continuous f }`. For example, when `β` is a group, a subgroup `continuous_subgroup α β` of `α → β` is constructed with carrier `{ f : α → β | continuous f }`. Note that, rather than using the derived algebraic structures on these subobjects (for example, when `β` is a group, the derived group structure on `continuous_subgroup α β`), one should use `C(α, β)` with the appropriate instance of the structure. -/ local attribute [elab_simple] continuous.comp namespace continuous_functions variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {f g : {f : α → β | continuous f }} instance : has_coe_to_fun {f : α → β | continuous f} (λ _, α → β) := ⟨subtype.val⟩ end continuous_functions namespace continuous_map variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] @[to_additive] instance has_mul [has_mul β] [has_continuous_mul β] : has_mul C(α, β) := ⟨λ f g, ⟨f * g, continuous_mul.comp (f.continuous.prod_mk g.continuous : _)⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul [has_mul β] [has_continuous_mul β] (f g : C(α, β)) : ⇑(f * g) = f * g := rfl @[simp, to_additive] lemma mul_comp [has_mul γ] [has_continuous_mul γ] (f₁ f₂ : C(β, γ)) (g : C(α, β)) : (f₁ * f₂).comp g = f₁.comp g * f₂.comp g := rfl @[to_additive] instance [has_one β] : has_one C(α, β) := ⟨const α 1⟩ @[simp, norm_cast, to_additive] lemma coe_one [has_one β] : ⇑(1 : C(α, β)) = 1 := rfl @[simp, to_additive] lemma one_comp [has_one γ] (g : C(α, β)) : (1 : C(β, γ)).comp g = 1 := rfl instance [has_nat_cast β] : has_nat_cast C(α, β) := ⟨λ n, continuous_map.const _ n⟩ @[simp, norm_cast] lemma coe_nat_cast [has_nat_cast β] (n : ℕ) : ((n : C(α, β)) : α → β) = n := rfl instance [has_int_cast β] : has_int_cast C(α, β) := ⟨λ n, continuous_map.const _ n⟩ @[simp, norm_cast] lemma coe_int_cast [has_int_cast β] (n : ℤ) : ((n : C(α, β)) : α → β) = n := rfl instance has_nsmul [add_monoid β] [has_continuous_add β] : has_smul ℕ C(α, β) := ⟨λ n f, ⟨n • f, f.continuous.nsmul n⟩⟩ @[to_additive] instance has_pow [monoid β] [has_continuous_mul β] : has_pow C(α, β) ℕ := ⟨λ f n, ⟨f ^ n, f.continuous.pow n⟩⟩ @[norm_cast, to_additive] lemma coe_pow [monoid β] [has_continuous_mul β] (f : C(α, β)) (n : ℕ) : ⇑(f ^ n) = f ^ n := rfl -- don't make `coe_nsmul` simp as the linter complains it's redundant WRT `coe_smul` attribute [simp] coe_pow @[to_additive] lemma pow_comp [monoid γ] [has_continuous_mul γ] (f : C(β, γ)) (n : ℕ) (g : C(α, β)) : (f^n).comp g = (f.comp g)^n := rfl -- don't make `nsmul_comp` simp as the linter complains it's redundant WRT `smul_comp` attribute [simp] pow_comp @[to_additive] instance [group β] [topological_group β] : has_inv C(α, β) := { inv := λ f, ⟨f⁻¹, f.continuous.inv⟩ } @[simp, norm_cast, to_additive] lemma coe_inv [group β] [topological_group β] (f : C(α, β)) : ⇑(f⁻¹) = f⁻¹ := rfl @[simp, to_additive] lemma inv_comp [group γ] [topological_group γ] (f : C(β, γ)) (g : C(α, β)) : (f⁻¹).comp g = (f.comp g)⁻¹ := rfl @[to_additive] instance [has_div β] [has_continuous_div β] : has_div C(α, β) := { div := λ f g, ⟨f / g, f.continuous.div' g.continuous⟩ } @[simp, norm_cast, to_additive] lemma coe_div [has_div β] [has_continuous_div β] (f g : C(α, β)) : ⇑(f / g) = f / g := rfl @[simp, to_additive] lemma div_comp [has_div γ] [has_continuous_div γ] (f g : C(β, γ)) (h : C(α, β)) : (f / g).comp h = (f.comp h) / (g.comp h) := rfl instance has_zsmul [add_group β] [topological_add_group β] : has_smul ℤ C(α, β) := { smul := λ z f, ⟨z • f, f.continuous.zsmul z⟩ } @[to_additive] instance has_zpow [group β] [topological_group β] : has_pow C(α, β) ℤ := { pow := λ f z, ⟨f ^ z, f.continuous.zpow z⟩ } @[norm_cast, to_additive] lemma coe_zpow [group β] [topological_group β] (f : C(α, β)) (z : ℤ) : ⇑(f ^ z) = f ^ z := rfl -- don't make `coe_zsmul` simp as the linter complains it's redundant WRT `coe_smul` attribute [simp] coe_zpow @[to_additive] lemma zpow_comp [group γ] [topological_group γ] (f : C(β, γ)) (z : ℤ) (g : C(α, β)) : (f^z).comp g = (f.comp g)^z := rfl -- don't make `zsmul_comp` simp as the linter complains it's redundant WRT `smul_comp` attribute [simp] zpow_comp end continuous_map section group_structure /-! ### Group stucture In this section we show that continuous functions valued in a topological group inherit the structure of a group. -/ section subtype /-- The `submonoid` of continuous maps `α → β`. -/ @[to_additive "The `add_submonoid` of continuous maps `α → β`. "] def continuous_submonoid (α : Type*) (β : Type*) [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : submonoid (α → β) := { carrier := { f : α → β | continuous f }, one_mem' := @continuous_const _ _ _ _ 1, mul_mem' := λ f g fc gc, fc.mul gc } /-- The subgroup of continuous maps `α → β`. -/ @[to_additive "The `add_subgroup` of continuous maps `α → β`. "] def continuous_subgroup (α : Type*) (β : Type*) [topological_space α] [topological_space β] [group β] [topological_group β] : subgroup (α → β) := { inv_mem' := λ f fc, continuous.inv fc, ..continuous_submonoid α β, }. end subtype namespace continuous_map @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semigroup β] [has_continuous_mul β] : semigroup C(α, β) := coe_injective.semigroup _ coe_mul @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_semigroup β] [has_continuous_mul β] : comm_semigroup C(α, β) := coe_injective.comm_semigroup _ coe_mul @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [mul_one_class β] [has_continuous_mul β] : mul_one_class C(α, β) := coe_injective.mul_one_class _ coe_one coe_mul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [mul_zero_class β] [has_continuous_mul β] : mul_zero_class C(α, β) := coe_injective.mul_zero_class _ coe_zero coe_mul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semigroup_with_zero β] [has_continuous_mul β] : semigroup_with_zero C(α, β) := coe_injective.semigroup_with_zero _ coe_zero coe_mul @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid C(α, β) := coe_injective.monoid _ coe_one coe_mul coe_pow instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid_with_zero β] [has_continuous_mul β] : monoid_with_zero C(α, β) := coe_injective.monoid_with_zero _ coe_zero coe_one coe_mul coe_pow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_monoid β] [has_continuous_mul β] : comm_monoid C(α, β) := coe_injective.comm_monoid _ coe_one coe_mul coe_pow instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_monoid_with_zero β] [has_continuous_mul β] : comm_monoid_with_zero C(α, β) := coe_injective.comm_monoid_with_zero _ coe_zero coe_one coe_mul coe_pow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [locally_compact_space α] [topological_space β] [has_mul β] [has_continuous_mul β] : has_continuous_mul C(α, β) := ⟨begin refine continuous_of_continuous_uncurry _ _, have h1 : continuous (λ x : (C(α, β) × C(α, β)) × α, x.fst.fst x.snd) := continuous_eval'.comp (continuous_fst.prod_map continuous_id), have h2 : continuous (λ x : (C(α, β) × C(α, β)) × α, x.fst.snd x.snd) := continuous_eval'.comp (continuous_snd.prod_map continuous_id), exact h1.mul h2, end⟩ /-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/ @[to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`.", simps] def coe_fn_monoid_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : C(α, β) →* (α → β) := { to_fun := coe_fn, map_one' := coe_one, map_mul' := coe_mul } /-- Composition on the left by a (continuous) homomorphism of topological monoids, as a `monoid_hom`. Similar to `monoid_hom.comp_left`. -/ @[to_additive "Composition on the left by a (continuous) homomorphism of topological `add_monoid`s, as an `add_monoid_hom`. Similar to `add_monoid_hom.comp_left`.", simps] protected def _root_.monoid_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] [topological_space γ] [monoid γ] [has_continuous_mul γ] (g : β →* γ) (hg : continuous g) : C(α, β) →* C(α, γ) := { to_fun := λ f, (⟨g, hg⟩ : C(β, γ)).comp f, map_one' := ext $ λ x, g.map_one, map_mul' := λ f₁ f₂, ext $ λ x, g.map_mul _ _ } /-- Composition on the right as a `monoid_hom`. Similar to `monoid_hom.comp_hom'`. -/ @[to_additive "Composition on the right as an `add_monoid_hom`. Similar to `add_monoid_hom.comp_hom'`.", simps] def comp_monoid_hom' {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [mul_one_class γ] [has_continuous_mul γ] (g : C(α, β)) : C(β, γ) →* C(α, γ) := { to_fun := λ f, f.comp g, map_one' := one_comp g, map_mul' := λ f₁ f₂, mul_comp f₁ f₂ g } open_locale big_operators @[simp, to_additive] lemma coe_prod {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) : ⇑(∏ i in s, f i) = (∏ i in s, (f i : α → β)) := (coe_fn_monoid_hom : C(α, β) →* _).map_prod f s @[to_additive] lemma prod_apply {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) (a : α) : (∏ i in s, f i) a = (∏ i in s, f i a) := by simp @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] : group C(α, β) := coe_injective.group _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : comm_group C(α, β) := coe_injective.comm_group _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : topological_group C(α, β) := { continuous_mul := by { letI : uniform_space β := topological_group.to_uniform_space β, have : uniform_group β := topological_comm_group_is_uniform, rw continuous_iff_continuous_at, rintros ⟨f, g⟩, rw [continuous_at, tendsto_iff_forall_compact_tendsto_uniformly_on, nhds_prod_eq], exactI λ K hK, uniform_continuous_mul.comp_tendsto_uniformly_on ((tendsto_iff_forall_compact_tendsto_uniformly_on.mp filter.tendsto_id K hK).prod (tendsto_iff_forall_compact_tendsto_uniformly_on.mp filter.tendsto_id K hK)), }, continuous_inv := by { letI : uniform_space β := topological_group.to_uniform_space β, have : uniform_group β := topological_comm_group_is_uniform, rw continuous_iff_continuous_at, intro f, rw [continuous_at, tendsto_iff_forall_compact_tendsto_uniformly_on], exactI λ K hK, uniform_continuous_inv.comp_tendsto_uniformly_on (tendsto_iff_forall_compact_tendsto_uniformly_on.mp filter.tendsto_id K hK), } } end continuous_map end group_structure section ring_structure /-! ### Ring stucture In this section we show that continuous functions valued in a topological semiring `R` inherit the structure of a ring. -/ section subtype /-- The subsemiring of continuous maps `α → β`. -/ def continuous_subsemiring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [semiring R] [topological_semiring R] : subsemiring (α → R) := { ..continuous_add_submonoid α R, ..continuous_submonoid α R } /-- The subring of continuous maps `α → β`. -/ def continuous_subring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [ring R] [topological_ring R] : subring (α → R) := { ..continuous_subsemiring α R, ..continuous_add_subgroup α R } end subtype namespace continuous_map instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_non_assoc_semiring β] [topological_semiring β] : non_unital_non_assoc_semiring C(α, β) := coe_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul coe_nsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_semiring β] [topological_semiring β] : non_unital_semiring C(α, β) := coe_injective.non_unital_semiring _ coe_zero coe_add coe_mul coe_nsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [add_monoid_with_one β] [has_continuous_add β] : add_monoid_with_one C(α, β) := coe_injective.add_monoid_with_one _ coe_zero coe_one coe_add coe_nsmul coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_assoc_semiring β] [topological_semiring β] : non_assoc_semiring C(α, β) := coe_injective.non_assoc_semiring _ coe_zero coe_one coe_add coe_mul coe_nsmul coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] : semiring C(α, β) := coe_injective.semiring _ coe_zero coe_one coe_add coe_mul coe_nsmul coe_pow coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_non_assoc_ring β] [topological_ring β] : non_unital_non_assoc_ring C(α, β) := coe_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_ring β] [topological_ring β] : non_unital_ring C(α, β) := coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_assoc_ring β] [topological_ring β] : non_assoc_ring C(α, β) := coe_injective.non_assoc_ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul coe_nat_cast coe_int_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : ring C(α, β) := coe_injective.ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul coe_pow coe_nat_cast coe_int_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_comm_semiring β] [topological_semiring β] : non_unital_comm_semiring C(α, β) := coe_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul coe_nsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_semiring β] [topological_semiring β] : comm_semiring C(α, β) := coe_injective.comm_semiring _ coe_zero coe_one coe_add coe_mul coe_nsmul coe_pow coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_comm_ring β] [topological_ring β] : non_unital_comm_ring C(α, β) := coe_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_ring β] [topological_ring β] : comm_ring C(α, β) := coe_injective.comm_ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul coe_pow coe_nat_cast coe_int_cast /-- Composition on the left by a (continuous) homomorphism of topological semirings, as a `ring_hom`. Similar to `ring_hom.comp_left`. -/ @[simps] protected def _root_.ring_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] [topological_space γ] [semiring γ] [topological_semiring γ] (g : β →+* γ) (hg : continuous g) : C(α, β) →+* C(α, γ) := { .. g.to_monoid_hom.comp_left_continuous α hg, .. g.to_add_monoid_hom.comp_left_continuous α hg } /-- Coercion to a function as a `ring_hom`. -/ @[simps] def coe_fn_ring_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : C(α, β) →+* (α → β) := { to_fun := coe_fn, ..(coe_fn_monoid_hom : C(α, β) →* _), ..(coe_fn_add_monoid_hom : C(α, β) →+ _) } end continuous_map end ring_structure local attribute [ext] subtype.eq section module_structure /-! ### Semiodule stucture In this section we show that continuous functions valued in a topological module `M` over a topological semiring `R` inherit the structure of a module. -/ section subtype variables (α : Type*) [topological_space α] variables (R : Type*) [semiring R] variables (M : Type*) [topological_space M] [add_comm_group M] variables [module R M] [has_continuous_const_smul R M] [topological_add_group M] /-- The `R`-submodule of continuous maps `α → M`. -/ def continuous_submodule : submodule R (α → M) := { carrier := { f : α → M | continuous f }, smul_mem' := λ c f hf, hf.const_smul c, ..continuous_add_subgroup α M } end subtype namespace continuous_map variables {α β : Type*} [topological_space α] [topological_space β] {R R₁ : Type*} {M : Type*} [topological_space M] {M₂ : Type*} [topological_space M₂] @[to_additive continuous_map.has_vadd] instance [has_smul R M] [has_continuous_const_smul R M] : has_smul R C(α, M) := ⟨λ r f, ⟨r • f, f.continuous.const_smul r⟩⟩ @[to_additive] instance [locally_compact_space α] [has_smul R M] [has_continuous_const_smul R M] : has_continuous_const_smul R C(α, M) := ⟨λ γ, continuous_of_continuous_uncurry _ (continuous_eval'.const_smul γ)⟩ @[to_additive] instance [locally_compact_space α] [topological_space R] [has_smul R M] [has_continuous_smul R M] : has_continuous_smul R C(α, M) := ⟨begin refine continuous_of_continuous_uncurry _ _, have h : continuous (λ x : (R × C(α, M)) × α, x.fst.snd x.snd) := continuous_eval'.comp (continuous_snd.prod_map continuous_id), exact (continuous_fst.comp continuous_fst).smul h, end⟩ @[simp, to_additive, norm_cast] lemma coe_smul [has_smul R M] [has_continuous_const_smul R M] (c : R) (f : C(α, M)) : ⇑(c • f) = c • f := rfl @[to_additive] lemma smul_apply [has_smul R M] [has_continuous_const_smul R M] (c : R) (f : C(α, M)) (a : α) : (c • f) a = c • (f a) := rfl @[simp, to_additive] lemma smul_comp [has_smul R M] [has_continuous_const_smul R M] (r : R) (f : C(β, M)) (g : C(α, β)) : (r • f).comp g = r • (f.comp g) := rfl @[to_additive] instance [has_smul R M] [has_continuous_const_smul R M] [has_smul R₁ M] [has_continuous_const_smul R₁ M] [smul_comm_class R R₁ M] : smul_comm_class R R₁ C(α, M) := { smul_comm := λ _ _ _, ext $ λ _, smul_comm _ _ _ } instance [has_smul R M] [has_continuous_const_smul R M] [has_smul R₁ M] [has_continuous_const_smul R₁ M] [has_smul R R₁] [is_scalar_tower R R₁ M] : is_scalar_tower R R₁ C(α, M) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance [has_smul R M] [has_smul Rᵐᵒᵖ M] [has_continuous_const_smul R M] [is_central_scalar R M] : is_central_scalar R C(α, M) := { op_smul_eq_smul := λ _ _, ext $ λ _, op_smul_eq_smul _ _ } instance [monoid R] [mul_action R M] [has_continuous_const_smul R M] : mul_action R C(α, M) := function.injective.mul_action _ coe_injective coe_smul instance [monoid R] [add_monoid M] [distrib_mul_action R M] [has_continuous_add M] [has_continuous_const_smul R M] : distrib_mul_action R C(α, M) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [has_continuous_add M] [module R M] [has_continuous_const_smul R M] variables [has_continuous_add M₂] [module R M₂] [has_continuous_const_smul R M₂] instance module : module R C(α, M) := function.injective.module R coe_fn_add_monoid_hom coe_injective coe_smul variables (R) /-- Composition on the left by a continuous linear map, as a `linear_map`. Similar to `linear_map.comp_left`. -/ @[simps] protected def _root_.continuous_linear_map.comp_left_continuous (α : Type*) [topological_space α] (g : M →L[R] M₂) : C(α, M) →ₗ[R] C(α, M₂) := { map_smul' := λ c f, ext $ λ x, g.map_smul' c _, .. g.to_linear_map.to_add_monoid_hom.comp_left_continuous α g.continuous } /-- Coercion to a function as a `linear_map`. -/ @[simps] def coe_fn_linear_map : C(α, M) →ₗ[R] (α → M) := { to_fun := coe_fn, map_smul' := coe_smul, ..(coe_fn_add_monoid_hom : C(α, M) →+ _) } end continuous_map end module_structure section algebra_structure /-! ### Algebra structure In this section we show that continuous functions valued in a topological algebra `A` over a ring `R` inherit the structure of an algebra. Note that the hypothesis that `A` is a topological algebra is obtained by requiring that `A` be both a `has_continuous_smul` and a `topological_semiring`.-/ section subtype variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] /-- The `R`-subalgebra of continuous maps `α → A`. -/ def continuous_subalgebra : subalgebra R (α → A) := { carrier := { f : α → A | continuous f }, algebra_map_mem' := λ r, (continuous_const : continuous $ λ (x : α), algebra_map R A r), ..continuous_subsemiring α A } end subtype section continuous_map variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] {A₂ : Type*} [topological_space A₂] [semiring A₂] [algebra R A₂] [topological_semiring A₂] /-- Continuous constant functions as a `ring_hom`. -/ def continuous_map.C : R →+* C(α, A) := { to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩, map_one' := by ext x; exact (algebra_map R A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _, map_zero' := by ext x; exact (algebra_map R A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ } @[simp] lemma continuous_map.C_apply (r : R) (a : α) : continuous_map.C r a = algebra_map R A r := rfl variables [has_continuous_const_smul R A] [has_continuous_const_smul R A₂] instance continuous_map.algebra : algebra R C(α, A) := { to_ring_hom := continuous_map.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, } variables (R) /-- Composition on the left by a (continuous) homomorphism of topological `R`-algebras, as an `alg_hom`. Similar to `alg_hom.comp_left`. -/ @[simps] protected def alg_hom.comp_left_continuous {α : Type*} [topological_space α] (g : A →ₐ[R] A₂) (hg : continuous g) : C(α, A) →ₐ[R] C(α, A₂) := { commutes' := λ c, continuous_map.ext $ λ _, g.commutes' _, .. g.to_ring_hom.comp_left_continuous α hg } /-- Coercion to a function as an `alg_hom`. -/ @[simps] def continuous_map.coe_fn_alg_hom : C(α, A) →ₐ[R] (α → A) := { to_fun := coe_fn, commutes' := λ r, rfl, -- `..(continuous_map.coe_fn_ring_hom : C(α, A) →+* _)` times out for some reason map_zero' := continuous_map.coe_zero, map_one' := continuous_map.coe_one, map_add' := continuous_map.coe_add, map_mul' := continuous_map.coe_mul } variables {R} /-- A version of `separates_points` for subalgebras of the continuous functions, used for stating the Stone-Weierstrass theorem. -/ abbreviation subalgebra.separates_points (s : subalgebra R C(α, A)) : Prop := set.separates_points ((λ f : C(α, A), (f : α → A)) '' (s : set C(α, A))) lemma subalgebra.separates_points_monotone : monotone (λ s : subalgebra R C(α, A), s.separates_points) := λ s s' r h x y n, begin obtain ⟨f, m, w⟩ := h n, rcases m with ⟨f, ⟨m, rfl⟩⟩, exact ⟨_, ⟨f, ⟨r m, rfl⟩⟩, w⟩, end @[simp] lemma algebra_map_apply (k : R) (a : α) : algebra_map R C(α, A) k a = k • 1 := by { rw algebra.algebra_map_eq_smul_one, refl, } variables {𝕜 : Type*} [topological_space 𝕜] /-- A set of continuous maps "separates points strongly" if for each pair of distinct points there is a function with specified values on them. We give a slightly unusual formulation, where the specified values are given by some function `v`, and we ask `f x = v x ∧ f y = v y`. This avoids needing a hypothesis `x ≠ y`. In fact, this definition would work perfectly well for a set of non-continuous functions, but as the only current use case is in the Stone-Weierstrass theorem, writing it this way avoids having to deal with casts inside the set. (This may need to change if we do Stone-Weierstrass on non-compact spaces, where the functions would be continuous functions vanishing at infinity.) -/ def set.separates_points_strongly (s : set C(α, 𝕜)) : Prop := ∀ (v : α → 𝕜) (x y : α), ∃ f : s, (f x : 𝕜) = v x ∧ f y = v y variables [field 𝕜] [topological_ring 𝕜] /-- Working in continuous functions into a topological field, a subalgebra of functions that separates points also separates points strongly. By the hypothesis, we can find a function `f` so `f x ≠ f y`. By an affine transformation in the field we can arrange so that `f x = a` and `f x = b`. -/ lemma subalgebra.separates_points.strongly {s : subalgebra 𝕜 C(α, 𝕜)} (h : s.separates_points) : (s : set C(α, 𝕜)).separates_points_strongly := λ v x y, begin by_cases n : x = y, { subst n, use ((v x) • 1 : C(α, 𝕜)), { apply s.smul_mem, apply s.one_mem, }, { simp [coe_fn_coe_base'] }, }, obtain ⟨f, ⟨f, ⟨m, rfl⟩⟩, w⟩ := h n, replace w : f x - f y ≠ 0 := sub_ne_zero_of_ne w, let a := v x, let b := v y, let f' := ((b - a) * (f x - f y)⁻¹) • (continuous_map.C (f x) - f) + continuous_map.C a, refine ⟨⟨f', _⟩, _, _⟩, { simp only [f', set_like.mem_coe, subalgebra.mem_to_submodule], -- TODO should there be a tactic for this? -- We could add an attribute `@[subobject_mem]`, and a tactic -- ``def subobject_mem := `[solve_by_elim with subobject_mem { max_depth := 10 }]`` solve_by_elim [subalgebra.add_mem, subalgebra.smul_mem, subalgebra.sub_mem, subalgebra.algebra_map_mem] { max_depth := 6 }, }, { simp [f', coe_fn_coe_base'], }, { simp [f', coe_fn_coe_base', inv_mul_cancel_right₀ w], }, end end continuous_map instance continuous_map.subsingleton_subalgebra (α : Type*) [topological_space α] (R : Type*) [comm_semiring R] [topological_space R] [topological_semiring R] [subsingleton α] : subsingleton (subalgebra R C(α, R)) := begin fsplit, intros s₁ s₂, by_cases n : nonempty α, { obtain ⟨x⟩ := n, ext f, have h : f = algebra_map R C(α, R) (f x), { ext x', simp only [mul_one, algebra.id.smul_eq_mul, algebra_map_apply], congr, }, rw h, simp only [subalgebra.algebra_map_mem], }, { ext f, have h : f = 0, { ext x', exact false.elim (n ⟨x'⟩), }, subst h, simp only [subalgebra.zero_mem], }, end end algebra_structure section module_over_continuous_functions /-! ### Structure as module over scalar functions If `M` is a module over `R`, then we show that the space of continuous functions from `α` to `M` is naturally a module over the ring of continuous functions from `α` to `R`. -/ namespace continuous_map instance has_smul' {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] [has_continuous_smul R M] : has_smul C(α, R) C(α, M) := ⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩ instance module' {α : Type*} [topological_space α] (R : Type*) [ring R] [topological_space R] [topological_ring R] (M : Type*) [topological_space M] [add_comm_monoid M] [has_continuous_add M] [module R M] [has_continuous_smul R M] : module C(α, R) C(α, M) := { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul R (f x), zero_smul := λ f, by ext x; exact zero_smul _ _, smul_zero := λ r, by ext x; exact smul_zero _, } end continuous_map end module_over_continuous_functions /-! We now provide formulas for `f ⊓ g` and `f ⊔ g`, where `f g : C(α, β)`, in terms of `continuous_map.abs`. -/ section variables {R : Type*} [linear_ordered_field R] -- TODO: -- This lemma (and the next) could go all the way back in `algebra.order.field`, -- except that it is tedious to prove without tactics. -- Rather than stranding it at some intermediate location, -- it's here, immediately prior to the point of use. lemma min_eq_half_add_sub_abs_sub {x y : R} : min x y = 2⁻¹ * (x + y - |x - y|) := by cases le_total x y with h h; field_simp [h, abs_of_nonneg, abs_of_nonpos, mul_two]; abel lemma max_eq_half_add_add_abs_sub {x y : R} : max x y = 2⁻¹ * (x + y + |x - y|) := by cases le_total x y with h h; field_simp [h, abs_of_nonneg, abs_of_nonpos, mul_two]; abel end namespace continuous_map section lattice variables {α : Type*} [topological_space α] variables {β : Type*} [linear_ordered_field β] [topological_space β] [order_topology β] [topological_ring β] lemma inf_eq (f g : C(α, β)) : f ⊓ g = (2⁻¹ : β) • (f + g - |f - g|) := ext (λ x, by simpa using min_eq_half_add_sub_abs_sub) -- Not sure why this is grosser than `inf_eq`: lemma sup_eq (f g : C(α, β)) : f ⊔ g = (2⁻¹ : β) • (f + g + |f - g|) := ext (λ x, by simpa [mul_add] using @max_eq_half_add_add_abs_sub _ _ (f x) (g x)) end lattice /-! ### Star structure If `β` has a continuous star operation, we put a star structure on `C(α, β)` by using the star operation pointwise. If `β` is a ⋆-ring, then `C(α, β)` inherits a ⋆-ring structure. If `β` is a ⋆-ring and a ⋆-module over `R`, then the space of continuous functions from `α` to `β` is a ⋆-module over `R`. -/ section star_structure variables {R α β : Type*} variables [topological_space α] [topological_space β] section has_star variables [has_star β] [has_continuous_star β] instance : has_star C(α, β) := { star := λ f, star_continuous_map.comp f } @[simp] lemma coe_star (f : C(α, β)) : ⇑(star f) = star f := rfl @[simp] lemma star_apply (f : C(α, β)) (x : α) : star f x = star (f x) := rfl end has_star instance [has_involutive_star β] [has_continuous_star β] : has_involutive_star C(α, β) := { star_involutive := λ f, ext $ λ x, star_star _ } instance [add_monoid β] [has_continuous_add β] [star_add_monoid β] [has_continuous_star β] : star_add_monoid C(α, β) := { star_add := λ f g, ext $ λ x, star_add _ _ } instance [semigroup β] [has_continuous_mul β] [star_semigroup β] [has_continuous_star β] : star_semigroup C(α, β) := { star_mul := λ f g, ext $ λ x, star_mul _ _ } instance [non_unital_semiring β] [topological_semiring β] [star_ring β] [has_continuous_star β] : star_ring C(α, β) := { ..continuous_map.star_add_monoid } instance [has_star R] [has_star β] [has_smul R β] [star_module R β] [has_continuous_star β] [has_continuous_const_smul R β] : star_module R C(α, β) := { star_smul := λ k f, ext $ λ x, star_smul _ _ } end star_structure end continuous_map
92ec93dde275324a165910c86ba9b9fcdab4631c
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/analysis/normed_space/basic.lean
50f9c4f81c6ec4e69be23253d7a838ca7f15e2fc
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
34,264
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal topology.instances.complex import topology.algebra.module variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e section prio set_option default_priority 100 -- see Note [default priority] /-- 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 (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) end prio /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { 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 normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { 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 normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- 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 (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp ... ≤ ∥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] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : 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₂ : α) : 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 : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {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₂ : α) : 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₂ : α} {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₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _ lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {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₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 rfl lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥s.sum f∥ ≤ s.sum n := by { haveI := classical.dec_eq β, exact le_trans (norm_sum_le s f) (finset.sum_le_sum h) } lemma norm_pos_iff (g : α) : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {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 : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, { x | ∥ f x ∥ < ε } ∈ l := metric.tendsto_nhds.trans $ forall_congr $ λ ε, forall_congr $ λ εgt0, begin simp only [dist_zero_right], exact exists_sets_subset_iff end section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) := by { rw [edist_dist, dist_eq_norm, _root_.sub_zero, of_real_norm_eq_coe_nnnorm] } end nnnorm /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), 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 norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := by simp [norm, le_max_left] lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := by simp [norm, le_max_right] /-- 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 (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } /-- 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 : Πb, π b} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma ne_mem_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : {y | f y ≠ x} ∈ l := begin have : {y | 1 + ∥x∥ ≤ ∥f y∥} ∈ l := h (mem_at_top (1 + ∥x∥)), apply mem_sets_of_superset this, assume y hy hxy, subst x, simp at hy, exact not_le_of_lt zero_lt_one hy end /-- A normed 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 α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm] ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _ ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : topological_add_monoid α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference end normed_group section normed_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) end prio @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_add_le }, { rw ←zero_add (0 : ℝ), apply tendsto.add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto.mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto.mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ /-- A normed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) end prio @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul' ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (s.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := if hb : b = 0 then by simp [hb] else begin apply eq_div_of_mul_eq, { apply ne_of_gt, apply (norm_pos_iff _).mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α] (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α] {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := begin refine metric.tendsto_nhds.2 (λε εpos, _), let δ := min (ε/2/2 * ∥r∥^2) (∥r∥/2), have norm_r_pos : 0 < ∥r∥ := (norm_pos_iff r).mpr r0, have A : 0 < ε / 2 / 2 * ∥r∥ ^ 2 := mul_pos' (half_pos (half_pos εpos)) (pow_pos norm_r_pos 2), have δpos : 0 < δ, by simp [half_pos norm_r_pos, A], refine ⟨ball r δ, ball_mem_nhds r δpos, λx hx, _⟩, have rx : ∥r∥/2 ≤ ∥x∥ := calc ∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring ... ≤ ∥r∥ - ∥r - x∥ : begin apply sub_le_sub (le_refl _), rw ← dist_eq_norm, exact le_trans (le_of_lt (mem_ball'.1 hx)) (min_le_right _ _) end ... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x) ... = ∥x∥ : by simp, have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx, have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹, by rw [sub_mul, sub_mul, mul_inv_cancel ((norm_pos_iff x).mp norm_x_pos), one_mul, mul_comm, ← mul_assoc, inv_mul_cancel r0, one_mul], calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _ ... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv] ... ≤ (ε/2/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, inv_nonneg.2, mul_nonneg, (inv_le_inv norm_x_pos norm_r_pos).2, le_refl], show ∥r - x∥ ≤ ε / 2 / 2 * ∥r∥ ^ 2, by { rw ← dist_eq_norm, exact le_trans (le_of_lt (mem_ball'.1 hx)) (min_le_left _ _) }, show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹, { convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx, rw [inv_div (ne.symm (ne_of_lt norm_r_pos)), div_eq_inv_mul, mul_comm], norm_num }, show (0 : ℝ) ≤ 2, by norm_num end ... = ε/2 * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring } ... = ε/2 : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp } ... < ε : half_lt_self εpos end lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} := begin assume x hx, apply continuous_at.continuous_within_at, exact (tendsto_inv hx) end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } end normed_field /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological groups. -/ lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α} (hy : y ≠ 0) (h : tendsto f l (𝓝 y)) : tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) := (normed_field.tendsto_inv hy).comp h lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) : tendsto (λa, f a / g a) l (𝓝 (x / y)) := hf.mul (hg.inv' hy) lemma real.norm_eq_abs (r : ℝ) : norm r = abs r := rfl @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] } @[elim_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[elim_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[elim_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space section prio set_option default_priority 100 -- see Note [default priority] -- see Note[vector space definition] for why we extend `module`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends module α β := (norm_smul : ∀ (a:α) (b:β), norm (a • b) = has_norm.norm a * norm b) end prio variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul := normed_field.norm_mul } set_option class.instance_max_depth 43 lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (𝓝 s)) → (tendsto g e (𝓝 b)) → tendsto (λ x, (f x) • (g x)) e (𝓝 (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_add_le (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (𝓝 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (𝓝 ∥b∥) := filter.tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) limg, have lim1 := limf'.mul limg', simp only [zero_mul, sub_eq_add_neg] at lim1, have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 := (tendsto_const_nhds : tendsto _ _ (𝓝 ∥ s ∥)).mul limg3, simp only [sub_eq_add_neg, mul_zero] at lim2, rw [show (0:ℝ) = 0 + 0, by simp], exact lim1.add lim2 } end lemma tendsto_smul_const {g : γ → F} {e : filter γ} (s : α) {b : F} : (tendsto g e (𝓝 b)) → tendsto (λ x, s • (g x)) e (𝓝 (s • b)) := tendsto_smul tendsto_const_nhds @[priority 100] -- see Note [lower instance priority] instance normed_space.topological_vector_space : topological_vector_space α E := { continuous_smul := continuous_iff_continuous_at.2 $ λp, tendsto_smul (continuous_iff_continuous_at.1 continuous_fst _) (continuous_iff_continuous_at.1 continuous_snd _) } open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos ((norm_pos_iff _).2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥), rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)] end, add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.module } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s := { norm_smul := λc x, norm_smul c (x : E) } end normed_space section normed_algebra /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜' x∥ = ∥x∥) @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜' x∥ = ∥x∥ := normed_algebra.norm_algebra_map_eq _ _ end normed_algebra section restrict_scalars set_option class.instance_max_depth 40 variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] /-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul := λc x, begin change ∥(algebra_map 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..module.restrict_scalars 𝕜 𝕜' E } end restrict_scalars section summable open_locale classical open finset filter variables [normed_group α] [complete_space α] lemma summable_iff_vanishing_norm {f : ι → α} : summable f ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε := begin simp only [summable_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hf : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := summable_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hf ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑i, f i)∥ ≤ (∑ i, ∥f i∥) := have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (𝓝 ∥(∑ i, f i)∥) := (continuous_norm.tendsto _).comp (has_sum_tsum $ summable_of_summable_norm hf), have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (𝓝 (∑ i, ∥f i∥)) := has_sum_tsum hf, le_of_tendsto_of_tendsto at_top_ne_bot h₁ h₂ $ univ_mem_sets' $ assume s, norm_sum_le _ _ end summable
741a51d972ff7ddff7a8cd1fc93cf897d105addf
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/ordered_group.lean
48dd292eef73cd08a49d238a0722bcd2d2a3056a
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
65,167
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.group.with_one import algebra.group.type_tags import order.bounded_lattice set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-! # Ordered monoids and groups This file develops the basics of ordered monoids and groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ universe u variable {α : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c * a ≤ c * b` (multiplication is monotone) * `a * b < a * c → b < c`. -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c + a ≤ c + b` (addition is monotone) * `a + b < a + c → b < c`. -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) attribute [to_additive ordered_add_comm_monoid] ordered_comm_monoid section ordered_comm_monoid variables [ordered_comm_monoid α] {a b c d : α} @[to_additive add_le_add_left] lemma mul_le_mul_left' (h : a ≤ b) (c) : c * a ≤ c * b := ordered_comm_monoid.mul_le_mul_left a b h c @[to_additive add_le_add_right] lemma mul_le_mul_right' (h : a ≤ b) (c) : a * c ≤ b * c := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left' h c @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' : a * b < a * c → b < c := ordered_comm_monoid.lt_of_mul_lt_mul_left a b c @[to_additive add_le_add] lemma mul_le_mul' (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := le_trans (mul_le_mul_right' h₁ _) (mul_le_mul_left' h₂ _) @[to_additive] lemma mul_le_mul_three {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ @[to_additive] lemma le_mul_of_one_le_right (h : 1 ≤ b) : a ≤ a * b := have a * 1 ≤ a * b, from mul_le_mul_left' h _, by rwa mul_one at this @[to_additive] lemma le_mul_of_one_le_left (h : 1 ≤ b) : a ≤ b * a := have 1 * a ≤ b * a, from mul_le_mul_right' h a, by rwa one_mul at this @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' (h : a * b < c * b) : a < c := lt_of_mul_lt_mul_left' (show b * a < b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) -- here we start using properties of one. @[to_additive] lemma le_mul_of_one_le_of_le (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := one_mul b ▸ mul_le_mul' ha hbc @[to_additive] lemma le_mul_of_le_of_one_le (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := mul_one b ▸ mul_le_mul' hbc ha @[to_additive add_nonneg] lemma one_le_mul (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb @[to_additive add_pos_of_pos_of_nonneg] lemma one_lt_mul_of_lt_of_le' (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_of_lt_of_le ha $ le_mul_of_one_le_right hb @[to_additive add_pos_of_nonneg_of_pos] lemma one_lt_mul_of_le_of_lt' (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_of_lt_of_le hb $ le_mul_of_one_le_left ha @[to_additive add_pos] lemma one_lt_mul' (ha : 1 < a) (hb : 1 < b) : 1 < a * b := one_lt_mul_of_lt_of_le' ha $ le_of_lt hb @[to_additive add_nonpos] lemma mul_le_one' (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1:α) ▸ (mul_le_mul' ha hb) @[to_additive] lemma mul_le_of_le_one_of_le' (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one' (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one' (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := lt_of_le_of_lt (mul_le_of_le_of_le_one' (le_refl _) hb) ha @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one' (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha (le_refl _)) hb @[to_additive] lemma mul_lt_one' (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_one_of_le_one_of_lt_one' (le_of_lt ha) hb @[to_additive] lemma lt_mul_of_one_le_of_lt' (ha : 1 ≤ a) (hbc : b < c) : b < a * c := lt_of_lt_of_le hbc $ le_mul_of_one_le_left ha @[to_additive] lemma lt_mul_of_lt_of_one_le' (hbc : b < c) (ha : 1 ≤ a) : b < c * a := lt_of_lt_of_le hbc $ le_mul_of_one_le_right ha @[to_additive] lemma lt_mul_of_one_lt_of_lt' (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt' (le_of_lt ha) hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt' (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le' hbc (le_of_lt ha) @[to_additive] lemma mul_lt_of_le_one_of_lt' (ha : a ≤ 1) (hbc : b < c) : a * b < c := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha (le_refl _)) hbc @[to_additive] lemma mul_lt_of_lt_of_le_one' (hbc : b < c) (ha : a ≤ 1) : b * a < c := lt_of_le_of_lt (mul_le_of_le_of_le_one' (le_refl _) ha) hbc @[to_additive] lemma mul_lt_of_lt_one_of_lt' (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt' (le_of_lt ha) hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one' hbc (le_of_lt ha) @[to_additive] lemma mul_eq_one_iff' (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le (le_refl _) hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha (le_refl _), have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add] lemma monotone.mul' (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) @[to_additive monotone.add_const] lemma monotone.mul_const' (hf : monotone f) (a : α) : monotone (λ x, f x * a) := hf.mul' monotone_const @[to_additive monotone.const_add] lemma monotone.const_mul' (hf : monotone f) (a : α) : monotone (λ x, a * f x) := monotone_const.mul' hf end mono end ordered_comm_monoid lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid α] [preorder α] : preorder (units α) := preorder.lift (coe : units α → α) @[simp, to_additive, norm_cast] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl @[simp, to_additive, norm_cast] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl @[to_additive] instance [monoid α] [partial_order α] : partial_order (units α) := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order (units α) := linear_order.lift coe units.ext @[to_additive] instance [monoid α] [decidable_linear_order α] : decidable_linear_order (units α) := decidable_linear_order.lift coe units.ext @[simp, to_additive, norm_cast] theorem max_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [max, h] @[simp, to_additive, norm_cast] theorem min_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] end units namespace with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order instance [decidable_linear_order α] : decidable_linear_order (with_zero α) := with_bot.decidable_linear_order /-- If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one α] @[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩ @[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 := by rw [eq_comm, coe_eq_one] attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) . @[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ . end has_one instance [has_add α] : has_add (with_top α) := ⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩ instance [add_semigroup α] : add_semigroup (with_top α) := { add := (+), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ } @[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $ @with_zero.monoid_with_zero (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $ @with_zero.comm_monoid_with_zero (multiplicative α) _ } instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) := begin suffices, refine { add_le_add_left := this, ..with_top.partial_order, ..with_top.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ c h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim le_top }, cases b with b, { exact (not_le_of_lt h).elim le_top }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_top.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases b with b; cases h₂, cases a with a, {cases le_antisymm h le_top }, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end @[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe @[simp] lemma add_top [ordered_add_comm_monoid α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [ordered_add_comm_monoid α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by cases a; cases b; simp [none_eq_top, some_eq_coe, coe_add.symm] lemma add_lt_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] end with_top namespace with_bot instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero instance [has_one α] : has_one (with_bot α) := with_top.has_one instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {α : Type*} [add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := by norm_cast @[simp] lemma bot_add [ordered_add_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_add_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl end with_bot /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α := (le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c) section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] {a b c d : α} lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c := canonically_ordered_add_monoid.le_iff_exists_add a b @[simp] lemma zero_le (a : α) : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩ @[simp] lemma bot_eq_zero : (⊥ : α) = 0 := le_antisymm bot_le (zero_le ⊥) @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff' (zero_le _) (zero_le _) @[simp] lemma le_zero_iff_eq : a ≤ 0 ↔ a = 0 := iff.intro (assume h, le_antisymm h (zero_le a)) (assume h, h ▸ le_refl a) lemma zero_lt_iff_ne_zero : 0 < a ↔ a ≠ 0 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm @[nolint ge_or_gt] lemma exists_pos_add_of_lt (h : a < b) : ∃ c > 0, a + c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_lt h), refine ⟨c, zero_lt_iff_ne_zero.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end lemma le_add_left (h : a ≤ c) : a ≤ b + c := calc a = 0 + a : by simp ... ≤ b + c : add_le_add (zero_le _) h lemma le_add_right (h : a ≤ b) : a ≤ b + c := calc a = a + 0 : by simp ... ≤ b + c : add_le_add h (zero_le _) instance with_zero.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } end canonically_ordered_add_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and strictly monotone. -/ @[protect_proj, ancestor add_comm_monoid add_left_cancel_semigroup add_right_cancel_semigroup partial_order] class ordered_cancel_add_comm_monoid (α : Type u) extends add_comm_monoid α, add_left_cancel_semigroup α, add_right_cancel_semigroup α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and strictly monotone. -/ @[protect_proj, ancestor comm_monoid left_cancel_semigroup right_cancel_semigroup partial_order] class ordered_cancel_comm_monoid (α : Type u) extends comm_monoid α, left_cancel_semigroup α, right_cancel_semigroup α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) attribute [to_additive ordered_cancel_add_comm_monoid] ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c d : α} @[to_additive] instance ordered_cancel_comm_monoid.to_left_cancel_monoid : left_cancel_monoid α := { ..‹ordered_cancel_comm_monoid α› } @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' : ∀ {a b c : α}, a * b ≤ a * c → b ≤ c := ordered_cancel_comm_monoid.le_of_mul_le_mul_left @[to_additive] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le (le_of_mul_le_mul_left' (le_of_lt h)) $ mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h), ..‹ordered_cancel_comm_monoid α› } @[to_additive add_lt_add_left] lemma mul_lt_mul_left' (h : a < b) (c : α) : c * a < c * b := lt_of_le_not_le (mul_le_mul_left' (le_of_lt h) _) $ mt le_of_mul_le_mul_left' (not_le_of_gt h) @[to_additive add_lt_add_right] lemma mul_lt_mul_right' (h : a < b) (c : α) : a * c < b * c := begin rw [mul_comm a c, mul_comm b c], exact (mul_lt_mul_left' h c) end @[to_additive add_lt_add] lemma mul_lt_mul''' (h₁ : a < b) (h₂ : c < d) : a * c < b * d := lt_trans (mul_lt_mul_right' h₁ c) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_le_of_lt (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := lt_of_le_of_lt (mul_le_mul_right' h₁ _) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := lt_of_lt_of_le (mul_lt_mul_right' h₁ c) (mul_le_mul_left' h₂ _) @[to_additive] lemma lt_mul_of_one_lt_right (a : α) {b : α} (h : 1 < b) : a < a * b := have a * 1 < a * b, from mul_lt_mul_left' h a, by rwa [mul_one] at this @[to_additive] lemma lt_mul_of_one_lt_left (a : α) {b : α} (h : 1 < b) : a < b * a := have 1 * a < b * a, from mul_lt_mul_right' h a, by rwa [one_mul] at this @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' (h : a * b ≤ c * b) : a ≤ c := le_of_mul_le_mul_left' (show b * a ≤ b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive] lemma mul_lt_one (ha : a < 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul''' ha hb) @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_lt_of_le ha hb) @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_le_of_lt ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_le (ha : 1 < a) (hbc : b ≤ c) : b < a * c := one_mul b ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma lt_mul_of_le_of_one_lt (hbc : b ≤ c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma mul_le_of_le_one_of_le (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_le (ha : a < 1) (hbc : b ≤ c) : a * b < c := one_mul c ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma mul_lt_of_le_of_lt_one (hbc : b ≤ c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma lt_mul_of_one_le_of_lt (ha : 1 ≤ a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_le (hbc : b < c) (ha : 1 ≤ a) : b < c * a := mul_one b ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma lt_mul_of_one_lt_of_lt (ha : 1 < a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul''' ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt (hbc : b < c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul''' hbc ha @[to_additive] lemma mul_lt_of_le_one_of_lt (ha : a ≤ 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma mul_lt_of_lt_of_le_one (hbc : b < c) (ha : a ≤ 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_lt (ha : a < 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul''' ha hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one (hbc : b < c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul''' hbc ha @[simp, to_additive] lemma mul_le_mul_iff_left (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := ⟨le_of_mul_le_mul_left', λ h, mul_le_mul_left' h _⟩ @[simp, to_additive] lemma mul_le_mul_iff_right (c : α) : a * c ≤ b * c ↔ a ≤ b := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_iff_left c @[simp, to_additive] lemma mul_lt_mul_iff_left (a : α) {b c : α} : a * b < a * c ↔ b < c := ⟨lt_of_mul_lt_mul_left', λ h, mul_lt_mul_left' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_right (c : α) : a * c < b * c ↔ a < b := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_iff_left c @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := have a * 1 ≤ a * b ↔ 1 ≤ b, from mul_le_mul_iff_left a, by rwa mul_one at this @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, le_mul_iff_one_le_right'] @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' (a : α) {b : α} : a < a * b ↔ 1 < b := have a * 1 < a * b ↔ 1 < b, from mul_lt_mul_iff_left a, by rwa mul_one at this @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' (a : α) {b : α} : a < b * a ↔ 1 < b := by rw [mul_comm, lt_mul_iff_one_lt_right'] @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' : a * b ≤ b ↔ a ≤ 1 := by { convert mul_le_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' : a * b ≤ a ↔ b ≤ 1 := by { convert mul_le_mul_iff_left a, rw [mul_one] } @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' : a * b < b ↔ a < 1 := by { convert mul_lt_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' : a * b < a ↔ b < 1 := by { convert mul_lt_mul_iff_left a, rw [mul_one] } @[to_additive] lemma mul_eq_one_iff_eq_one_of_one_le (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := ⟨λ hab : a * b = 1, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', mul_one]⟩ section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add_strict_mono] lemma monotone.mul_strict_mono' (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf $ le_of_lt h) (hg h) @[to_additive strict_mono.add_monotone] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg $ le_of_lt h) @[to_additive strict_mono.add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := hf.mul_monotone' monotone_const @[to_additive strict_mono.const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := monotone_const.mul_strict_mono' hf end mono end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid α] lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive ordered_add_comm_group] ordered_comm_group /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) := { mul_le_mul_left := λ a b h c, mul_le_mul_left' h _, .. units.partial_order, .. (infer_instance : comm_group (units α)) } section ordered_comm_group variables [ordered_comm_group α] {a b c d : α} @[to_additive ordered_add_comm_group.add_lt_add_left] lemma ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := begin rw lt_iff_le_not_le at h ⊢, split, { apply ordered_comm_group.mul_le_mul_left _ _ h.1 }, { intro w, replace w : c⁻¹ * (c * b) ≤ c⁻¹ * (c * a) := ordered_comm_group.mul_le_mul_left _ _ w _, simp only [mul_one, mul_comm, mul_left_inv, mul_left_comm] at w, exact h.2 w }, end @[to_additive ordered_add_comm_group.le_of_add_le_add_left] lemma ordered_comm_group.le_of_mul_le_mul_left (h : a * b ≤ a * c) : b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] lemma ordered_comm_group.lt_of_mul_lt_mul_left (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_comm_group.mul_lt_mul_left' _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, le_of_mul_le_mul_left := @ordered_comm_group.le_of_mul_le_mul_left α _, ..s } @[to_additive neg_le_neg] lemma inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := have 1 ≤ a⁻¹ * b, from mul_left_inv a ▸ mul_le_mul_left' h _, have 1 * b⁻¹ ≤ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _, by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma le_of_inv_le_inv (h : b⁻¹ ≤ a⁻¹) : a ≤ b := suffices (a⁻¹)⁻¹ ≤ (b⁻¹)⁻¹, from begin simp [inv_inv] at this, assumption end, inv_le_inv' h @[to_additive] lemma one_le_of_inv_le_one (h : a⁻¹ ≤ 1) : 1 ≤ a := have a⁻¹ ≤ 1⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive] lemma inv_le_one_of_one_le (h : 1 ≤ a) : a⁻¹ ≤ 1 := have a⁻¹ ≤ 1⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive nonpos_of_neg_nonneg] lemma le_one_of_one_le_inv (h : 1 ≤ a⁻¹) : a ≤ 1 := have 1⁻¹ ≤ a⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one (h : a ≤ 1) : 1 ≤ a⁻¹ := have 1⁻¹ ≤ a⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive neg_lt_neg] lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := have 1 < a⁻¹ * b, from mul_left_inv a ▸ mul_lt_mul_left' h (a⁻¹), have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹), by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b := inv_inv a ▸ inv_inv b ▸ inv_lt_inv' h @[to_additive] lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a := have a⁻¹ < 1⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive] lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 := have a⁻¹ < 1⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive neg_of_neg_pos] lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 := have 1⁻¹ < a⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive neg_pos_of_neg] lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ := have 1⁻¹ < a⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive] lemma le_inv_of_le_inv (h : a ≤ b⁻¹) : b ≤ a⁻¹ := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_le_of_inv_le (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma mul_le_of_le_inv_mul (h : b ≤ a⁻¹ * c) : a * b ≤ c := begin have h := mul_le_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma le_inv_mul_of_mul_le (h : a * b ≤ c) : b ≤ a⁻¹ * c := begin have h := mul_le_mul_left' h a⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≤ c) : a ≤ b * c := begin have h := mul_le_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_le_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := begin have h := mul_le_mul_left' h b⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≤ c) : a ≤ b * c := le_mul_of_inv_mul_le h @[to_additive] lemma inv_mul_le_left_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := inv_mul_le_of_le_mul h @[to_additive] lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≤ b) : a ≤ b * c := by { rw mul_comm, exact le_mul_of_inv_mul_le h } @[to_additive] lemma inv_mul_le_right_of_le_mul (h : a ≤ b * c) : c⁻¹ * a ≤ b := by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h } @[to_additive] lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c := begin have h := mul_lt_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c := begin have h := mul_lt_mul_left' h (a⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c := begin have h := mul_lt_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := begin have h := mul_lt_mul_left' h (b⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c := lt_mul_of_inv_mul_lt h @[to_additive] lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := inv_mul_lt_of_lt_mul h @[to_additive] lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c := by { rw mul_comm, exact lt_mul_of_inv_mul_lt h } @[to_additive] lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b := by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h } @[simp, to_additive] lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a := ⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩ @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := have a * b * a⁻¹ ≤ a * b * b⁻¹ ↔ a⁻¹ ≤ b⁻¹, from mul_le_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := have a⁻¹ ≤ (b⁻¹)⁻¹ ↔ b⁻¹ ≤ a, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := have (a⁻¹)⁻¹ ≤ b⁻¹ ↔ b ≤ a⁻¹, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive neg_nonpos] lemma inv_le_one' : a⁻¹ ≤ 1 ↔ 1 ≤ a := have a⁻¹ ≤ 1⁻¹ ↔ 1 ≤ a, from inv_le_inv_iff, by rwa one_inv at this @[simp, to_additive neg_nonneg] lemma one_le_inv' : 1 ≤ a⁻¹ ↔ a ≤ 1 := have 1⁻¹ ≤ a⁻¹ ↔ a ≤ 1, from inv_le_inv_iff, by rwa one_inv at this @[to_additive] lemma inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (inv_le_one'.2 h) h @[to_additive] lemma self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (one_le_inv'.2 h) @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_lt_zero] lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a := have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_pos] lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 := have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := have b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≤ b ↔ a ≤ b * c := by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive sub_le_sub_iff] lemma div_le_div_iff' (a b c d : α) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin split ; intro h, have := mul_le_mul_right' (mul_le_mul_right' h b) d, rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right] at this, have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹, rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc, mul_inv_cancel_right] at this, end end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group α] {a b c d : α} lemma sub_nonneg_of_le (h : b ≤ a) : 0 ≤ a - b := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg (h : 0 ≤ a - b) : b ≤ a := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le (h : a ≤ b) : a - b ≤ 0 := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos (h : a - b ≤ 0) : a ≤ b := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt (h : b < a) : 0 < a - b := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos (h : 0 < a - b) : b < a := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt (h : a < b) : a - b < 0 := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg (h : a - b < 0) : a < b := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_sub_left (h : b ≤ c - a) : a + b ≤ c := begin have h := add_le_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma le_sub_left_of_add_le (h : a + b ≤ c) : b ≤ c - a := begin have h := add_le_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_le_of_le_sub_right (h : a ≤ c - b) : a + b ≤ c := begin have h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le (h : a + b ≤ c) : a ≤ c - b := begin have h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_sub_left_le (h : a - b ≤ c) : a ≤ b + c := begin have h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add (h : a ≤ b + c) : a - b ≤ c := begin have h := add_le_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma le_add_of_sub_right_le (h : a - c ≤ b) : a ≤ b + c := begin have h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add (h : a ≤ b + c) : a - c ≤ b := begin have h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_le_sub_left (h : -a ≤ b - c) : c ≤ a + b := le_add_of_neg_add_le_left (add_le_of_le_sub_right h) lemma neg_le_sub_left_of_le_add (h : c ≤ a + b) : -a ≤ b - c := begin have h := le_neg_add_of_add_le (sub_left_le_of_le_add h), rwa add_comm at h end lemma le_add_of_neg_le_sub_right (h : -b ≤ a - c) : c ≤ a + b := le_add_of_sub_right_le (add_le_of_le_sub_left h) lemma neg_le_sub_right_of_le_add (h : c ≤ a + b) : -b ≤ a - c := le_sub_left_of_add_le (sub_right_le_of_le_add h) lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := sub_left_le_of_le_add (le_add_of_sub_right_le h) lemma sub_le_sub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_sub_left (h : b < c - a) : a + b < c := begin have h := add_lt_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma lt_sub_left_of_add_lt (h : a + b < c) : b < c - a := begin have h := add_lt_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_lt_of_lt_sub_right (h : a < c - b) : a + b < c := begin have h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt (h : a + b < c) : a < c - b := begin have h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_sub_left_lt (h : a - b < c) : a < b + c := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add (h : a < b + c) : a - b < c := begin have h := add_lt_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma lt_add_of_sub_right_lt (h : a - c < b) : a < b + c := begin have h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add (h : a < b + c) : a - c < b := begin have h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_lt_sub_left (h : -a < b - c) : c < a + b := lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h) lemma neg_lt_sub_left_of_lt_add (h : c < a + b) : -a < b - c := begin have h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h), rwa add_comm at h end lemma lt_add_of_neg_lt_sub_right (h : -b < a - c) : c < a + b := lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h) lemma neg_lt_sub_right_of_lt_add (h : c < a + b) : -b < a - c := lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h) lemma sub_lt_of_sub_lt (h : a - b < c) : a - c < b := sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h) lemma sub_lt_sub_left (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c := add_lt_add hab (neg_lt_neg hcd) lemma sub_lt_sub_of_le_of_lt (hab : a ≤ b) (hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt hab (neg_lt_neg hcd) lemma sub_lt_sub_of_lt_of_le (hab : a < b) (hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le hab (neg_le_neg hcd) lemma sub_le_self (a : α) {b : α} (h : 0 ≤ b) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _ ... = a : by rw add_zero lemma sub_lt_self (a : α) {b : α} (h : 0 < b) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _ ... = a : by rw add_zero @[simp] lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b := (add_le_add_iff_left _).trans neg_le_neg_iff @[simp] lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b := add_le_add_iff_right _ @[simp] lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b := (add_lt_add_iff_left _).trans neg_lt_neg_iff @[simp] lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b := add_lt_add_iff_right _ @[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a := have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b := have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b, by rwa sub_self at this @[simp] lemma sub_pos : 0 < a - b ↔ b < a := have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b, by rwa sub_self at this lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c := by rw [le_sub_iff_add_le', add_comm] lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≤ c ↔ a - c ≤ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≤ b - c ↔ c ≤ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b := sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _) lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b := sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _) end ordered_add_comm_group /- TODO: The `add_lt_add_left` field of `ordered_add_comm_group` is redundant, and it is no longer in core so we can remove it now. This alternative constructor is a workaround until someone fixes this. -/ /-- Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`. -/ @[to_additive "Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`."] def ordered_comm_group.mk' {α : Type u} [comm_group α] [partial_order α] (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) : ordered_comm_group α := { mul_le_mul_left := mul_le_mul_left, ..(by apply_instance : comm_group α), ..(by apply_instance : partial_order α) } /-- A decidable linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_cancel_add_comm_monoid (α : Type u) extends ordered_cancel_add_comm_monoid α, decidable_linear_order α section decidable_linear_ordered_cancel_add_comm_monoid variables [decidable_linear_ordered_cancel_add_comm_monoid α] lemma min_add_add_left (a b c : α) : min (a + b) (a + c) = a + min b c := eq.symm (eq_min (show a + min b c ≤ a + b, from add_le_add_left (min_le_left _ _) _) (show a + min b c ≤ a + c, from add_le_add_left (min_le_right _ _) _) (assume d, assume : d ≤ a + b, assume : d ≤ a + c, decidable.by_cases (assume : b ≤ c, by rwa [min_eq_left this]) (assume : ¬ b ≤ c, by rwa [min_eq_right (le_of_lt (lt_of_not_ge this))]))) lemma min_add_add_right (a b c : α) : min (a + c) (b + c) = min a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply min_add_add_left end lemma max_add_add_left (a b c : α) : max (a + b) (a + c) = a + max b c := eq.symm (eq_max (add_le_add_left (le_max_left _ _) _) (add_le_add_left (le_max_right _ _) _) (assume d, assume : a + b ≤ d, assume : a + c ≤ d, decidable.by_cases (assume : b ≤ c, by rwa [max_eq_right this]) (assume : ¬ b ≤ c, by rwa [max_eq_left (le_of_lt (lt_of_not_ge this))]))) lemma max_add_add_right (a b c : α) : max (a + c) (b + c) = max a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply max_add_add_left end end decidable_linear_ordered_cancel_add_comm_monoid /-- A decidable linearly ordered additive commutative group is an additive commutative group with a decidable linear order in which addition is strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_add_comm_group (α : Type u) extends add_comm_group α, decidable_linear_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) instance decidable_linear_ordered_comm_group.to_ordered_add_comm_group (α : Type u) [s : decidable_linear_ordered_add_comm_group α] : ordered_add_comm_group α := { add := s.add, ..s } section decidable_linear_ordered_add_comm_group variables [decidable_linear_ordered_add_comm_group α] @[priority 100] -- see Note [lower instance priority] instance decidable_linear_ordered_add_comm_group.to_decidable_linear_ordered_cancel_add_comm_monoid : decidable_linear_ordered_cancel_add_comm_monoid α := { le_of_add_le_add_left := λ x y z, le_of_add_le_add_left, add_left_cancel := λ x y z, add_left_cancel, add_right_cancel := λ x y z, add_right_cancel, ..‹decidable_linear_ordered_add_comm_group α› } lemma decidable_linear_ordered_add_comm_group.add_lt_add_left (a b : α) (h : a < b) (c : α) : c + a < c + b := ordered_add_comm_group.add_lt_add_left a b h c lemma max_neg_neg (a b : α) : max (-a) (-b) = - min a b := eq.symm (eq_max (show -a ≤ -(min a b), from neg_le_neg $ min_le_left a b) (show -b ≤ -(min a b), from neg_le_neg $ min_le_right a b) (assume d, assume H₁ : -a ≤ d, assume H₂ : -b ≤ d, have H : -d ≤ min a b, from le_min (neg_le_of_neg_le H₁) (neg_le_of_neg_le H₂), show -(min a b) ≤ d, from neg_le_of_neg_le H)) lemma min_eq_neg_max_neg_neg (a b : α) : min a b = - max (-a) (-b) := by rw [max_neg_neg, neg_neg] lemma min_neg_neg (a b : α) : min (-a) (-b) = - max a b := by rw [min_eq_neg_max_neg_neg, neg_neg, neg_neg] lemma max_eq_neg_min_neg_neg (a b : α) : max a b = - min (-a) (-b) := by rw [min_neg_neg, neg_neg] /-- `abs a` is the absolute value of `a`. -/ def abs (a : α) : α := max a (-a) lemma abs_of_nonneg {a : α} (h : 0 ≤ a) : abs a = a := have h' : -a ≤ a, from le_trans (neg_nonpos_of_nonneg h) h, max_eq_left h' lemma abs_of_pos {a : α} (h : 0 < a) : abs a = a := abs_of_nonneg (le_of_lt h) lemma abs_of_nonpos {a : α} (h : a ≤ 0) : abs a = -a := have h' : a ≤ -a, from le_trans h (neg_nonneg_of_nonpos h), max_eq_right h' lemma abs_of_neg {a : α} (h : a < 0) : abs a = -a := abs_of_nonpos (le_of_lt h) lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg (le_refl _) lemma abs_neg (a : α) : abs (-a) = abs a := begin unfold abs, rw [max_comm, neg_neg] end lemma abs_pos_of_pos {a : α} (h : 0 < a) : 0 < abs a := by rwa (abs_of_pos h) lemma abs_pos_of_neg {a : α} (h : a < 0) : 0 < abs a := abs_neg a ▸ abs_pos_of_pos (neg_pos_of_neg h) lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) := by rw [← neg_sub, abs_neg] lemma ne_zero_of_abs_ne_zero {a : α} (h : abs a ≠ 0) : a ≠ 0 := assume ha, h (eq.symm ha ▸ abs_zero) /- these assume a linear order -/ lemma eq_zero_of_neg_eq {a : α} (h : -a = a) : a = 0 := match lt_trichotomy a 0 with | or.inl h₁ := have 0 < a, from h ▸ neg_pos_of_neg h₁, absurd h₁ (lt_asymm this) | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 0, from h ▸ neg_neg_of_pos h₁, absurd h₁ (lt_asymm this) end lemma abs_nonneg (a : α) : 0 ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, by rwa (abs_of_nonneg h)) (assume h : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos h ... = abs a : eq.symm (abs_of_nonpos h)) lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a lemma le_abs_self (a : α) : a ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, begin rw [abs_of_nonneg h] end) (assume h : a ≤ 0, le_trans h $ abs_nonneg a) lemma neg_le_abs_self (a : α) : -a ≤ abs a := abs_neg a ▸ le_abs_self (-a) lemma eq_zero_of_abs_eq_zero {a : α} (h : abs a = 0) : a = 0 := have h₁ : a ≤ 0, from h ▸ le_abs_self a, have h₂ : -a ≤ 0, from h ▸ abs_neg a ▸ le_abs_self (-a), le_antisymm h₁ (nonneg_of_neg_nonpos h₂) lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := have a - b = 0, from eq_zero_of_abs_eq_zero h, show a = b, from eq_of_sub_eq_zero this lemma abs_pos_of_ne_zero {a : α} (h : a ≠ 0) : 0 < abs a := or.elim (lt_or_gt_of_ne h) abs_pos_of_neg abs_pos_of_pos lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := or.elim (le_total 0 a) (assume h : 0 ≤ a, eq.symm (abs_of_nonneg h) ▸ h1) (assume h : a ≤ 0, eq.symm (abs_of_nonpos h) ▸ h2) lemma abs_le_of_le_of_neg_le {a b : α} (h1 : a ≤ b) (h2 : -a ≤ b) : abs a ≤ b := abs_by_cases (λ x : α, x ≤ b) h1 h2 lemma abs_lt_of_lt_of_neg_lt {a b : α} (h1 : a < b) (h2 : -a < b) : abs a < b := abs_by_cases (λ x : α, x < b) h1 h2 private lemma aux1 {a b : α} (h1 : 0 ≤ a + b) (h2 : 0 ≤ a) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume h3 : 0 ≤ b, calc abs (a + b) ≤ abs (a + b) : by apply le_refl ... = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... = abs a + abs b : by rw (abs_of_nonneg h3)) (assume h3 : ¬ 0 ≤ b, have h4 : b ≤ 0, from le_of_lt (lt_of_not_ge h3), calc abs (a + b) = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... ≤ abs a + 0 : add_le_add_left h4 _ ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos h4) _ ... = abs a + abs b : by rw (abs_of_nonpos h4)) private lemma aux2 {a b : α} (h1 : 0 ≤ a + b) : abs (a + b) ≤ abs a + abs b := or.elim (le_total b 0) (assume h2 : b ≤ 0, have h3 : ¬ a < 0, from assume h4 : a < 0, have h5 : a + b < 0, begin have aux := add_lt_add_of_lt_of_le h4 h2, rwa [add_zero] at aux end, not_lt_of_ge h1 h5, aux1 h1 (le_of_not_gt h3)) (assume h2 : 0 ≤ b, begin have h3 : abs (b + a) ≤ abs b + abs a, begin rw add_comm at h1, exact aux1 h1 h2 end, rw [add_comm, add_comm (abs a)], exact h3 end) lemma abs_add_le_abs_add_abs (a b : α) : abs (a + b) ≤ abs a + abs b := or.elim (le_total 0 (a + b)) (assume h2 : 0 ≤ a + b, aux2 h2) (assume h2 : a + b ≤ 0, have h3 : -a + -b = -(a + b), by rw neg_add, have h4 : 0 ≤ -(a + b), from neg_nonneg_of_nonpos h2, have h5 : 0 ≤ -a + -b, begin rw [← h3] at h4, exact h4 end, calc abs (a + b) = abs (-a + -b) : by rw [← abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 h5 ... = abs a + abs b : by rw [abs_neg, abs_neg]) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := have h1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rw sub_add_cancel ... = abs (a - b + b) : by rw sub_add_cancel ... ≤ abs (a - b) + abs b : by apply abs_add_le_abs_add_abs, le_of_add_le_add_right h1 lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left] ... ≤ abs (a - b) + abs (b - c) : by apply abs_add_le_abs_add_abs lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := begin apply le_trans, apply abs_add_le_abs_add_abs, apply le_trans, apply add_le_add_right, apply abs_add_le_abs_add_abs, apply le_refl end lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := begin cases (decidable.em (b ≤ a)) with hba hba, rw (abs_of_nonneg (sub_nonneg_of_le hba)), apply sub_le_sub, apply hau, apply hbl, rw [abs_of_neg (sub_neg_of_lt (lt_of_not_ge hba)), neg_sub], apply sub_le_sub, apply hbu, apply hal end lemma decidable_linear_ordered_add_comm_group.eq_of_abs_sub_nonpos {a b : α} (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) end decidable_linear_ordered_add_comm_group set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) end prio namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `decidable_linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_decidable_linear_ordered_add_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : decidable_linear_ordered_add_comm_group α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace order_dual instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (order_dual α) := { add_le_add_left := λ a b h c, @add_le_add_left α _ b a h _, lt_of_add_lt_add_left := λ a b c h, @lt_of_add_lt_add_left α _ a c b h, ..order_dual.partial_order α, ..show add_comm_monoid α, by apply_instance } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (order_dual α) := { le_of_add_le_add_left := λ a b c : α, le_of_add_le_add_left, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, ..order_dual.ordered_add_comm_monoid } instance [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) := { add_left_neg := λ a : α, add_left_neg a, ..order_dual.ordered_add_comm_monoid, ..show add_comm_group α, by apply_instance } end order_dual section type_tags instance : Π [preorder α], preorder (multiplicative α) := id instance : Π [preorder α], preorder (additive α) := id instance : Π [partial_order α], partial_order (multiplicative α) := id instance : Π [partial_order α], partial_order (additive α) := id instance : Π [linear_order α], linear_order (multiplicative α) := id instance : Π [linear_order α], linear_order (additive α) := id instance : Π [decidable_linear_order α], decidable_linear_order (multiplicative α) := id instance : Π [decidable_linear_order α], decidable_linear_order (additive α) := id instance [ordered_add_comm_monoid α] : ordered_comm_monoid (multiplicative α) := { mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left α _, lt_of_mul_lt_mul_left := @ordered_add_comm_monoid.lt_of_add_lt_add_left α _, ..multiplicative.partial_order, ..multiplicative.comm_monoid } instance [ordered_comm_monoid α] : ordered_add_comm_monoid (additive α) := { add_le_add_left := @ordered_comm_monoid.mul_le_mul_left α _, lt_of_add_lt_add_left := @ordered_comm_monoid.lt_of_mul_lt_mul_left α _, ..additive.partial_order, ..additive.add_comm_monoid } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_comm_monoid (multiplicative α) := { le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left α _, ..multiplicative.right_cancel_semigroup, ..multiplicative.left_cancel_semigroup, ..multiplicative.ordered_comm_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_add_comm_monoid (additive α) := { le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left α _, ..additive.add_right_cancel_semigroup, ..additive.add_left_cancel_semigroup, ..additive.ordered_add_comm_monoid } instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } end type_tags
e19322cc4f7f3b691a9d9c239ae84166e9eab8f3
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/quot.lean
dd78d5304721a1e54564d507fe0f7dc0a1983719
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
16,449
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import logic.relator /-! # Quotients -- extends the core library -/ variables {α : Sort*} {β : Sort*} namespace setoid lemma ext {α : Sort*} : ∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t | ⟨r, _⟩ ⟨p, _⟩ eq := have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b, by subst this end setoid namespace quot variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*} local notation `⟦`:max a `⟧` := quot.mk _ a instance [inhabited α] : inhabited (quot ra) := ⟨⟦default _⟧⟩ /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb := quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa, quot.induction_on qb $ λ b, calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _) == f a₁ b : by simp ... == f a₂ b : ca pa ... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp /-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)` to a map `quot ra → quot rb`. -/ protected def map (f : α → β) (h : (ra ⇒ rb) f f) : quot ra → quot rb := quot.lift (λ x, ⟦f x⟧) $ assume x y (h₁ : ra x y), quot.sound $ h h₁ /-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/ protected def map_right {ra' : α → α → Prop} (h : ∀a₁ a₂, ra a₁ a₂ → ra' a₁ a₂) : quot ra → quot ra' := quot.map id h /-- weaken the relation of a quotient -/ def factor {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : quot r → quot s := quot.lift (quot.mk s) (λ x y rxy, quot.sound (h x y rxy)) lemma factor_mk_eq {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : factor r s h ∘ quot.mk _ = quot.mk _ := rfl end quot namespace quotient variables [sa : setoid α] [sb : setoid β] variables {φ : quotient sa → quotient sb → Sort*} instance [inhabited α] : inhabited (quotient sa) := ⟨⟦default _⟧⟩ /-- Induction on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quot.hrec_on₂ qa qb f (λ _ _ _ p, c _ _ _ _ p (setoid.refl _)) (λ _ _ _ p, c _ _ _ _ (setoid.refl _) p) /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient sa → quotient sb := quot.map f h @[simp] lemma map_mk (f : α → β) (h : ((≈) ⇒ (≈)) f f) (x : α) : quotient.map f h (⟦x⟧ : quotient sa) = (⟦f x⟧ : quotient sb) := rfl variables {γ : Sort*} [sc : setoid γ] /-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements to a function `f : quotient sa → quotient sb → quotient sc`. Useful to define binary operations on quotients. -/ protected def map₂ (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient sa → quotient sb → quotient sc := quotient.lift₂ (λ x y, ⟦f x y⟧) (λ x₁ y₁ x₂ y₂ h₁ h₂, quot.sound $ h h₁ h₂) end quotient @[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := ⟨quotient.exact, quotient.sound⟩ theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} : (∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) := ⟨assume h x, h _, assume h a, a.induction_on h⟩ @[simp] lemma quotient.lift_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift f h (quotient.mk x) = f x := rfl @[simp] lemma quotient.lift_on_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift_on (quotient.mk x) f h = f x := rfl @[simp] theorem quotient.lift_on_beta₂ {α : Type} {β : Type} [setoid α] (f : α → α → β) (h : ∀ (a₁ a₂ b₁ b₂ : α), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x y : α) : quotient.lift_on₂ (quotient.mk x) (quotient.mk y) f h = f x y := rfl /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast @[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a := quotient.exact (quotient.out_eq _) instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) := { r := λ a b, ∀ i, a i ≈ b i, iseqv := ⟨ λ a i, setoid.refl _, λ a b h i, setoid.symm (h _), λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ } /-- Given a function `f : Π i, quotient (S i)`, returns the class of functions `Π i, α i` sending each `i` to an element of the class `f i`. -/ noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : Π i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := ⟦λ i, (f i).out⟧ theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [Π i, setoid (α i)] (f : Π i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ := quotient.sound $ λ i, quotient.mk_out _ lemma nonempty_quotient_iff (s : setoid α) : nonempty (quotient s) ↔ nonempty α := ⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩ /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true) theorem true_equivalence : @equivalence α (λ _ _, true) := ⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩ namespace trunc /-- Constructor for `trunc α` -/ def mk (a : α) : trunc α := quot.mk _ a instance [inhabited α] : inhabited (trunc α) := ⟨mk (default _)⟩ /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β := quot.lift f (λ a b _, c a b) theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind protected theorem lift_beta (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl /-- Lift a constant function on `q : trunc α`. -/ @[reducible, elab_as_eliminator] protected def lift_on (q : trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_eliminator] protected theorem induction_on {β : trunc α → Prop} (q : trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q attribute [elab_as_eliminator] protected theorem induction_on₂ {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁) protected theorem eq (a b : trunc α) : a = b := trunc.induction_on₂ a b (λ x y, quot.sound trivial) instance : subsingleton (trunc α) := ⟨trunc.eq⟩ def bind (q : trunc α) (f : α → trunc β) : trunc β := trunc.lift_on q f (λ a b, trunc.eq _ _) /-- A function `f : α → β` defines a function `map f : trunc α → trunc β`. -/ def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f) instance : monad trunc := { pure := @trunc.mk, bind := @trunc.bind } instance : is_lawful_monad trunc := { id_map := λ α q, trunc.eq _ _, pure_bind := λ α β q f, rfl, bind_assoc := λ α β γ x f g, trunc.eq _ _ } variable {C : trunc α → Sort*} /-- Recursion/induction principle for `trunc`. -/ @[reducible, elab_as_eliminator] protected def rec (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : trunc α) : C q := quot.rec f (λ a b _, h a b) q /-- A version of `trunc.rec` taking `q : trunc α` as the first argument. -/ @[reducible, elab_as_eliminator] protected def rec_on (q : trunc α) (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := trunc.rec f h q /-- A version of `trunc.rec_on` assuming the codomain is a `subsingleton`. -/ @[reducible, elab_as_eliminator] protected def rec_on_subsingleton [∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q := trunc.rec f (λ a b, subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ noncomputable def out : trunc α → α := quot.out @[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _ end trunc theorem nonempty_of_trunc (q : trunc α) : nonempty α := let ⟨a, _⟩ := q.exists_rep in ⟨a⟩ namespace quotient variables {γ : Sort*} {φ : Sort*} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} /- Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules -/ /-- A version of `quotient.mk` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a /-- A version of `quotient.lift_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator, reducible] protected def lift_on' (q : quotient s₁) (f : α → φ) (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h /-- A version of `quotient.lift_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator, reducible] protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := quotient.lift_on₂ q₁ q₂ f h /-- A version of `quotient.ind` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma ind' {p : quotient s₁ → Prop} (h : ∀ a, p (quotient.mk' a)) (q : quotient s₁) : p q := quotient.ind h q /-- A version of `quotient.ind₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma ind₂' {p : quotient s₁ → quotient s₂ → Prop} (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) (q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ := quotient.ind₂ h q₁ q₂ /-- A version of `quotient.induction_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h /-- A version of `quotient.induction_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ := quotient.induction_on₂ q₁ q₂ h /-- A version of `quotient.induction_on₃` taking `{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ := quotient.induction_on₃ q₁ q₂ q₃ h /-- Recursion on a `quotient` argument `a`, result type depends on `⟦a⟧`. -/ protected def hrec_on' {φ : quotient s₁ → Sort*} (qa : quotient s₁) (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) : φ qa := quot.hrec_on qa f c @[simp] lemma hrec_on'_mk' {φ : quotient s₁ → Sort*} (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) (x : α) : (quotient.mk' x).hrec_on' f c = f x := rfl /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂' {φ : quotient s₁ → quotient s₂ → Sort*} (qa : quotient s₁) (qb : quotient s₂) (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quotient.hrec_on₂ qa qb f c @[simp] lemma hrec_on₂'_mk' {φ : quotient s₁ → quotient s₂ → Sort*} (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) (x : α) (qb : quotient s₂) : (quotient.mk' x).hrec_on₂' qb f c = qb.hrec_on' (f x) (λ b₁ b₂, c _ _ _ _ (setoid.refl _)) := rfl /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map' (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ := quot.map f h @[simp] lemma map'_mk' (f : α → β) (h) (x : α) : (quotient.mk' x : quotient s₁).map' f h = (quotient.mk' (f x) : quotient s₂) := rfl /-- A version of `quotient.map₂` using curly braces and unification. -/ protected def map₂' (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ → quotient s₃ := quotient.map₂ f h @[simp] lemma map₂'_mk' (f : α → β → γ) (h) (x : α) : (quotient.mk' x : quotient s₁).map₂' f h = (quotient.map' (f x) (h (setoid.refl x)) : quotient s₂ → quotient s₃) := rfl lemma exact' {a b : α} : (quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b := quotient.exact lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b := quotient.sound @[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b := quotient.eq /-- A version of `quotient.out` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ noncomputable def out' (a : quotient s₁) : α := quotient.out a @[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a := quotient.exact (quotient.out_eq _) end quotient
9903f405866ec36e15d902bf4811dcc18e9c04eb
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/analysis/normed_space/basic.lean
657bfe6632fc6d32bdb41e93b732c7a03ab22291
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,189
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 topology.instances.nnreal import topology.instances.complex import topology.algebra.module import topology.metric_space.antilipschitz /-! # Normed spaces -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators nnreal /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e /-- 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 (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { 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 normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { 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 normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- 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 (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, 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] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] lemma tendsto_norm_cocompact_at_top [proper_space α] : tendsto norm (cocompact α) at_top := by simpa only [dist_zero_right] using tendsto_dist_right_cocompact_at_top (0:α) lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : 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₂ : α) : 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 : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {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₂ : α) : 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₂ : α} {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₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _ lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {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₂ : α) : abs (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 : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl @[nontriviality] lemma norm_of_subsingleton [subsingleton α] (x : α) : ∥x∥ = 0 := by rw [subsingleton.elim x 0, norm_zero] lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {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) @[simp] lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos @[simp] lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {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 : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma eq_of_norm_sub_eq_zero {u v : α} (h : ∥u - v∥ = 0) : u = v := begin apply eq_of_dist_eq_zero, rwa dist_eq_norm end lemma norm_le_insert (u v : α) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ := calc ∥v∥ = ∥u - (u - v)∥ : by abel ... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _ lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma mem_ball_iff_norm {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥h - g∥ < r := by rw [mem_ball, dist_eq_norm] lemma mem_ball_iff_norm' {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥g - h∥ < r := by rw [mem_ball', dist_eq_norm] lemma mem_closed_ball_iff_norm {g h : α} {r : ℝ} : h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r := by rw [mem_closed_ball, dist_eq_norm] lemma mem_closed_ball_iff_norm' {g h : α} {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 : α} {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_lt_of_mem_ball {g h : α} {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 } theorem normed_group.tendsto_nhds_zero {f : γ → α} {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 : α → β} {x : α} {y : β} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm] /-- A homomorphism `f` of normed 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 normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.lipschitz_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real 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 : α → β} {C : ℝ≥0} {s : set α} : 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 : α → β} {C : ℝ≥0} {s : set α} (h : lipschitz_on_with C f s) {x y : α} (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 /-- A homomorphism `f` of normed 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 :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm (a : α) : ℝ≥0 := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : 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₂ : α) : 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 : β → α), nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le end nnnorm lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β} (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 lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (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 lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin 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 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), 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 /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), 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.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnnorm_def (x : α × β) : nnnorm x = max (nnnorm x.1) (nnnorm x.2) := by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {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) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } /-- 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 _).symm, dist_pi_le_iff hr], refl } 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 lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa /-- 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 : γ → α} {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 : γ → α} {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 lim_norm (x : α) : tendsto (λg : α, ∥g - x∥) (𝓝 x) (𝓝 0) := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : tendsto (λg : α, ∥g∥) (𝓝 0) (𝓝 0) := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto.comp continuous_norm.continuous_at h lemma continuous.norm [topological_space γ] {f : γ → α} (hf : continuous f) : continuous (λ x, ∥f x∥) := continuous_norm.comp hf lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) := tendsto.comp continuous_nnnorm.continuous_at h /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ 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 /-- A normed 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 α := ⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩ @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : has_continuous_add α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference end normed_group section normed_ring /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed commutative ring is a commutative ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_comm_ring (α : Type*) extends normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this axiom. -/ class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop := (norm_one : ∥(1:α)∥ = 1) export norm_one_class (norm_one) attribute [simp] norm_one @[simp] lemma nnnorm_one [normed_group α] [has_one α] [norm_one_class α] : nnnorm (1:α) = 1 := nnreal.eq norm_one @[priority 100] -- see Note [lower instance priority] instance normed_comm_ring.to_comm_ring [β : normed_comm_ring α] : comm_ring α := { ..β } @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } instance prod.norm_one_class [normed_group α] [has_one α] [norm_one_class α] [normed_group β] [has_one β] [norm_one_class β] : norm_one_class (α × β) := ⟨by simp [prod.norm_def]⟩ variables [normed_ring α] lemma norm_mul_le (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ∥l.prod∥ ≤ (l.map norm).prod | [] h := (h rfl).elim | [a] _ := by simp | (a :: b :: l) _ := begin rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ∥a∥], refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)), exact list.norm_prod_le' (list.cons_ne_nil b l) end lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ∥l.prod∥ ≤ (l.map norm).prod | [] := by simp | (a::l) := list.norm_prod_le' (list.cons_ne_nil a l) lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, have : l.map f ≠ [], by simpa using hs, simpa using list.norm_prod_le' this end lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, simpa using (l.map f).norm_prod_le end /-- If `α` is a normed ring, then `∥a^n∥≤ ∥a∥^n` for `n > 0`. See also `norm_pow_le`. -/ lemma norm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le' (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) /-- If `α` is a normed ring with `∥1∥=1`, then `∥a^n∥≤ ∥a∥^n`. See also `norm_pow_le'`. -/ lemma norm_pow_le [norm_one_class α] (a : α) : ∀ (n : ℕ), ∥a^n∥ ≤ ∥a∥^n | 0 := by simp | (n+1) := norm_pow_le' a n.zero_lt_succ lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n := eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩ lemma units.norm_pos [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ := norm_pos_iff.mpr (units.ne_zero x) /-- In a normed ring, the left-multiplication `add_monoid_hom` is bounded. -/ lemma mul_left_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ := norm_mul_le x /-- In a normed ring, the right-multiplication `add_monoid_hom` is bounded. -/ lemma mul_right_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ := λ y, by {rw mul_comm, convert norm_mul_le y x} /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance normed_ring_top_monoid [normed_ring α] : has_continuous_mul α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_add_le }, { rw ←zero_add (0 : ℝ), apply tendsto.add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto.mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto.mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ /-- A normed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) namespace normed_field section normed_field variables [normed_field α] @[simp] lemma norm_mul (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b @[priority 100] -- see Note [lower instance priority] instance to_normed_comm_ring : normed_comm_ring α := { norm_mul := λ a b, (norm_mul a b).le, ..‹normed_field α› } @[priority 900] instance to_norm_one_class : norm_one_class α := ⟨mul_left_cancel' (mt norm_eq_zero.1 (@one_ne_zero α _ _)) $ by rw [← norm_mul, mul_one, mul_one]⟩ /-- `norm` as a `monoid_hom`. -/ @[simps] def norm_hom : monoid_with_zero_hom α ℝ := ⟨norm, norm_zero, norm_one, norm_mul⟩ @[simp] lemma norm_pow (a : α) : ∀ (n : ℕ), ∥a ^ n∥ = ∥a∥ ^ n := norm_hom.to_monoid_hom.map_pow a @[simp] lemma norm_prod (s : finset β) (f : β → α) : ∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ := (norm_hom.to_monoid_hom : α →* ℝ).map_prod f s @[simp] lemma norm_div (a b : α) : ∥a / b∥ = ∥a∥ / ∥b∥ := (norm_hom : monoid_with_zero_hom α ℝ).map_div a b @[simp] lemma norm_inv (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := (norm_hom : monoid_with_zero_hom α ℝ).map_inv' a @[simp] lemma nnnorm_inv (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_fpow : ∀ (a : α) (n : ℤ), ∥a^n∥ = ∥a∥^n := (norm_hom : monoid_with_zero_hom α ℝ).map_fpow @[priority 100] -- see Note [lower instance priority] instance : has_continuous_inv' α := begin refine ⟨λ r r0, (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _)⟩, let δ := min (ε/2 * ∥r∥^2) (∥r∥/2), have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0, have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos (half_pos εpos) (pow_pos norm_r_pos 2), have δpos : 0 < δ, by simp [half_pos norm_r_pos, A], refine ⟨δ, δpos, λ x hx, _⟩, have rx : ∥r∥/2 ≤ ∥x∥ := calc ∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring ... ≤ ∥r∥ - ∥r - x∥ : begin apply sub_le_sub (le_refl _), rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_right _ _) end ... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x) ... = ∥x∥ : by simp [sub_sub_cancel], have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx, have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹, by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm, ← mul_assoc, inv_mul_cancel r0, one_mul], calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _ ... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv] ... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, mul_nonneg, (inv_le_inv norm_x_pos norm_r_pos).2, le_refl], show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2, by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) }, show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹, { convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx, rw [inv_div, div_eq_inv_mul, mul_comm] }, show (0 : ℝ) ≤ 2, by norm_num end ... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring } ... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp } end end normed_field variables (α) [nondiscrete_normed_field α] lemma exists_one_lt_norm : ∃x : α, 1 < ∥x∥ := ‹nondiscrete_normed_field α›.non_trivial lemma exists_norm_lt_one : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], rintro rfl, rw norm_zero at hy, exact lt_asymm zero_lt_one hy }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ variable {α} @[instance] lemma punctured_nhds_ne_bot (x : α) : ne_bot (𝓝[{x}ᶜ] x) := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end @[instance] lemma nhds_within_is_unit_ne_bot : ne_bot (𝓝[{x : α | is_unit x}] 0) := by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α) end normed_field instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } namespace real lemma norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl lemma norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥ = x := abs_of_nonneg hx @[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp @[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@zero_lt_two ℝ _ _) @[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp open_locale nnreal @[simp] lemma nnreal.norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x := by rw [real.norm_eq_abs, x.abs_eq] lemma nnnorm_coe_eq_self {x : ℝ≥0} : nnnorm (x : ℝ) = x := by { ext, exact norm_of_nonneg (zero_le x) } lemma nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : nnnorm x = ⟨x, hx⟩ := @nnnorm_coe_eq_self ⟨x, hx⟩ lemma ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : (nnnorm x : ennreal) = ennreal.of_real x := by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hx] } end real @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_comm_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub], mul_comm := mul_comm } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : norm_one_class ℤ := ⟨by simp [← int.norm_cast_real]⟩ instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : semimodule α β` -- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better -- unification properties. -- see Note[vector space definition] for why we extend `semimodule`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends semimodule α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin classical, by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _ ... = ∥s • x∥ : _, exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _), rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul], rwa [ne.def, norm_eq_zero] } end @[simp] lemma abs_norm_eq_norm (z : β) : abs ∥z∥ = ∥z∥ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq $ dist_smul s x y lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] @[priority 100] -- see Note [lower instance priority] instance normed_space.topological_vector_space : topological_vector_space α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases exists_ne (0 : E) with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos (norm_pos_iff.2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ < ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_fpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], -- TODO: without the next two lines Lean unfolds `≤` to `real.le` add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.semimodule } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } end normed_space section normed_algebra /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := normed_algebra.norm_algebra_map_eq _ variables (𝕜 : Type*) [normed_field 𝕜] variables (𝕜' : Type*) [normed_ring 𝕜'] @[priority 100] instance normed_algebra.to_normed_space [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { norm_algebra_map_eq := by simp, .. algebra.id 𝕜} variables {𝕜'} [normed_algebra 𝕜 𝕜'] include 𝕜 @[simp] lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 := by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜)) lemma normed_algebra.norm_one_class : norm_one_class 𝕜' := ⟨normed_algebra.norm_one 𝕜⟩ lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 := begin refine (norm_pos_iff.mp _).symm, rw @normed_algebra.norm_one 𝕜, norm_num, end lemma normed_algebra.nontrivial : nontrivial 𝕜' := ⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜⟩⟩ end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [normed_group E] [normed_space 𝕜' E] /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `semimodule.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..restrict_scalars.semimodule 𝕜 𝕜' E } instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] : normed_group (restrict_scalars 𝕜 𝕜' E) := I instance semimodule.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := (normed_space.restrict_scalars 𝕜 𝕜' E : normed_space 𝕜 E) end restrict_scalars section summable open_locale classical open finset filter variables [normed_group α] [normed_group β] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := begin rw [cauchy_seq_finset_iff_vanishing, nhds_basis_ball.forall_iff], { simp only [ball_0_eq, set.mem_set_of_eq] }, { rintros s t hst ⟨s', hs'⟩, exact ⟨s', λ t' ht', hst $ hs' _ ht'⟩ } end lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥∑ i in t, g i∥ < ε := hs t ht, have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, ∑ a in s, f a) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : γ → finset ι} {p : filter γ} [ne_bot p] (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha /-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) := begin by_cases h : summable f, { have h₁ : tendsto (λs:finset ι, ∥∑ i in s, f i∥) at_top (𝓝 ∥(∑' i, f i)∥) := (continuous_norm.tendsto _).comp h.has_sum, have h₂ : tendsto (λs:finset ι, ∑ i in s, ∥f i∥) at_top (𝓝 (∑' i, ∥f i∥)) := hf.has_sum, exact le_of_tendsto_of_tendsto' h₁ h₂ (assume s, norm_sum_le _ _) }, { rw tsum_eq_zero_of_not_summable h, simp [tsum_nonneg] } end lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩ /-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded [complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥(∑' i, f i)∥ ≤ (∑' i, g i)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_norm_bounded {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀i, ∥f i∥ ≤ g i) : ∥(∑' (i:ι), f i)∥ ≤ a := begin have h' : summable (λ (i : ι), ∥f i∥), { let f' : ι → ℝ := λ i, ∥f i∥, have h'' : ∀ i, ∥f' i∥ ≤ g i, { intros i, convert h i, simp }, simpa [f'] using summable_of_norm_bounded g hg.summable h'' }, have h1 : ∥(∑' (i:ι), f i)∥ ≤ ∑' (i:ι), ∥f i∥ := by simpa using norm_tsum_le_tsum_norm h', have h2 := tsum_le_tsum h h' hg.summable, have h3 : a = ∑' (i:ι), g i := (has_sum.tsum_eq hg).symm, linarith end variable [complete_space α] /-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded_eventually {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f := begin replace h := mem_cofinite.1 h, refine h.summable_compl_iff.mp _, refine summable_of_norm_bounded _ (h.summable_compl_iff.mpr hg) _, rintros ⟨a, h'⟩, simpa using h' end lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g) (h : ∀i, nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable
f111f7dae6ed71d9641f16b8d79e5c4dde836ac6
7b02c598aa57070b4cf4fbfe2416d0479220187f
/homotopy/3x3.hlean
646421b034b2fab9f5d3e894744d7f03e35195f9
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,018
hlean
-- WIP import ..move_to_lib open function eq namespace pushout section -- structure span2 : Type := -- {A₀₀ A₀₂ A₀₄ A₂₀ A₂₂ A₂₄ A₄₀ A₄₂ A₄₄ : Type} -- {f₀₁ : A₀₂ → A₀₀} {f₂₁ : A₂₂ → A₂₀} {f₄₁ : A₄₂ → A₄₀} -- {f₀₃ : A₀₂ → A₀₄} {f₂₃ : A₂₂ → A₂₄} {f₄₃ : A₄₂ → A₄₄} -- {f₁₀ : A₂₀ → A₀₀} {f₁₂ : A₂₂ → A₀₂} {f₁₄ : A₂₄ → A₀₄} -- {f₃₀ : A₂₀ → A₄₀} {f₃₂ : A₂₂ → A₄₂} {f₃₄ : A₂₄ → A₄₄} -- (s₁₁ : f₀₁ ∘ f₁₂ ~ f₁₀ ∘ f₂₁) (s₃₁ : f₄₁ ∘ f₃₂ ~ f₃₀ ∘ f₂₁) -- (s₁₃ : f₀₃ ∘ f₁₂ ~ f₁₄ ∘ f₂₃) (s₃₃ : f₄₃ ∘ f₃₂ ~ f₃₄ ∘ f₂₃) parameters {A₀₀ A₀₂ A₀₄ A₂₀ A₂₂ A₂₄ A₄₀ A₄₂ A₄₄ : Type} {f₀₁ : A₀₂ → A₀₀} {f₂₁ : A₂₂ → A₂₀} {f₄₁ : A₄₂ → A₄₀} {f₀₃ : A₀₂ → A₀₄} {f₂₃ : A₂₂ → A₂₄} {f₄₃ : A₄₂ → A₄₄} {f₁₀ : A₂₀ → A₀₀} {f₁₂ : A₂₂ → A₀₂} {f₁₄ : A₂₄ → A₀₄} {f₃₀ : A₂₀ → A₄₀} {f₃₂ : A₂₂ → A₄₂} {f₃₄ : A₂₄ → A₄₄} (s₁₁ : f₀₁ ∘ f₁₂ ~ f₁₀ ∘ f₂₁) (s₃₁ : f₄₁ ∘ f₃₂ ~ f₃₀ ∘ f₂₁) (s₁₃ : f₀₃ ∘ f₁₂ ~ f₁₄ ∘ f₂₃) (s₃₃ : f₄₃ ∘ f₃₂ ~ f₃₄ ∘ f₂₃) definition pushout2 : Type := pushout (pushout.functor f₂₁ f₀₁ f₄₁ s₁₁ s₃₁) (pushout.functor f₂₃ f₀₃ f₄₃ s₁₃ s₃₃) definition pushout2' : Type := pushout (pushout.functor f₁₂ f₁₀ f₁₄ s₁₁⁻¹ʰᵗʸ s₁₃⁻¹ʰᵗʸ) (pushout.functor f₃₂ f₃₀ f₃₄ s₃₁⁻¹ʰᵗʸ s₃₃⁻¹ʰᵗʸ) end end pushout
1e5281e1543a3a5635ceb820b263cdbdafaeabff
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/limits/shapes/zero.lean
931afaf6827a87d315f2475ab4a63fe58e58cc99
[ "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
15,031
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.products import category_theory.limits.shapes.images /-! # Zero morphisms and zero objects A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra structure, not merely a property.) A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object. ## References * https://en.wikipedia.org/wiki/Zero_morphism * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ universes v u open category_theory open category_theory.category namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. -/ class has_zero_morphisms := [has_zero : Π X Y : C, has_zero (X ⟶ Y)] (comp_zero' : ∀ {X Y : C} (f : X ⟶ Y) (Z : C), f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) . obviously) (zero_comp' : ∀ (X : C) {Y Z : C} (f : Y ⟶ Z), (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) . obviously) attribute [instance] has_zero_morphisms.has_zero restate_axiom has_zero_morphisms.comp_zero' attribute [simp] has_zero_morphisms.comp_zero restate_axiom has_zero_morphisms.zero_comp' attribute [simp, reassoc] has_zero_morphisms.zero_comp instance has_zero_morphisms_pempty : has_zero_morphisms (discrete pempty) := { has_zero := by tidy } instance has_zero_morphisms_punit : has_zero_morphisms (discrete punit) := { has_zero := by tidy } namespace has_zero_morphisms variables {C} /-- This lemma will be immediately superseded by `ext`, below. -/ private lemma ext_aux (I J : has_zero_morphisms C) (w : ∀ X Y : C, (@has_zero_morphisms.has_zero _ _ I X Y).zero = (@has_zero_morphisms.has_zero _ _ J X Y).zero) : I = J := begin casesI I, casesI J, congr, { ext X Y, exact w X Y }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, } end /-- If you're tempted to use this lemma "in the wild", you should probably carefully consider whether you've made a mistake in allowing two instances of `has_zero_morphisms` to exist at all. See, particularly, the note on `zero_morphisms_of_zero_object` below. -/ lemma ext (I J : has_zero_morphisms C) : I = J := begin apply ext_aux, intros X Y, rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero, rw @has_zero_morphisms.zero_comp _ _ J, end instance : subsingleton (has_zero_morphisms C) := ⟨ext⟩ end has_zero_morphisms open has_zero_morphisms section variables {C} [has_zero_morphisms C] lemma zero_of_comp_mono {X Y Z : C} {f : X ⟶ Y} (g : Y ⟶ Z) [mono g] (h : f ≫ g = 0) : f = 0 := by { rw [←zero_comp X g, cancel_mono] at h, exact h } lemma zero_of_epi_comp {X Y Z : C} (f : X ⟶ Y) {g : Y ⟶ Z} [epi f] (h : f ≫ g = 0) : g = 0 := by { rw [←comp_zero f Z, cancel_epi] at h, exact h } lemma eq_zero_of_image_eq_zero {X Y : C} {f : X ⟶ Y} [has_image f] (w : image.ι f = 0) : f = 0 := by rw [←image.fac f, w, has_zero_morphisms.comp_zero] lemma nonzero_image_of_nonzero {X Y : C} {f : X ⟶ Y} [has_image f] (w : f ≠ 0) : image.ι f ≠ 0 := λ h, w (eq_zero_of_image_eq_zero h) end section universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms C] [has_zero_morphisms D] lemma equivalence_preserves_zero_morphisms (F : C ≌ D) (X Y : C) : F.functor.map (0 : X ⟶ Y) = (0 : F.functor.obj X ⟶ F.functor.obj Y) := begin have t : F.functor.map (0 : X ⟶ Y) = F.functor.map (0 : X ⟶ Y) ≫ (0 : F.functor.obj Y ⟶ F.functor.obj Y), { apply faithful.map_injective (F.inverse), rw [functor.map_comp, equivalence.inv_fun_map], dsimp, rw [zero_comp, comp_zero, zero_comp], }, exact t.trans (by simp) end @[simp] lemma is_equivalence_preserves_zero_morphisms (F : C ⥤ D) [is_equivalence F] (X Y : C) : F.map (0 : X ⟶ Y) = 0 := by rw [←functor.as_equivalence_functor F, equivalence_preserves_zero_morphisms] end /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object := (zero : C) (unique_to : Π X : C, unique (zero ⟶ X)) (unique_from : Π X : C, unique (X ⟶ zero)) instance has_zero_object_punit : has_zero_object (discrete punit) := { zero := punit.star, unique_to := by tidy, unique_from := by tidy, } variables {C} namespace has_zero_object variables [has_zero_object C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero : has_zero C := { zero := has_zero_object.zero } local attribute [instance] has_zero_object.has_zero local attribute [instance] has_zero_object.unique_to has_zero_object.unique_from @[ext] lemma to_zero_ext {X : C} (f g : X ⟶ 0) : f = g := by rw [(has_zero_object.unique_from X).uniq f, (has_zero_object.unique_from X).uniq g] @[ext] lemma from_zero_ext {X : C} (f g : 0 ⟶ X) : f = g := by rw [(has_zero_object.unique_to X).uniq f, (has_zero_object.unique_to X).uniq g] instance (X : C) : subsingleton (X ≅ 0) := by tidy instance {X : C} (f : 0 ⟶ X) : mono f := { right_cancellation := λ Z g h w, by ext, } instance {X : C} (f : X ⟶ 0) : epi f := { left_cancellation := λ Z g h w, by ext, } /-- A category with a zero object has zero morphisms. It is rarely a good idea to use this. Many categories that have a zero object have zero morphisms for some other reason, for example from additivity. Library code that uses `zero_morphisms_of_zero_object` will then be incompatible with these categories because the `has_zero_morphisms` instances will not be definitionally equal. For this reason library code should generally ask for an instance of `has_zero_morphisms` separately, even if it already asks for an instance of `has_zero_objects`. -/ def zero_morphisms_of_zero_object : has_zero_morphisms C := { has_zero := λ X Y, { zero := inhabited.default (X ⟶ 0) ≫ inhabited.default (0 ⟶ Y) }, zero_comp' := λ X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, }, comp_zero' := λ X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }} /-- A zero object is in particular initial. -/ def has_initial : has_initial C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ def has_terminal : has_terminal C := has_terminal_of_unique 0 end has_zero_object section variables [has_zero_object C] [has_zero_morphisms C] local attribute [instance] has_zero_object.has_zero @[simp] lemma id_zero : 𝟙 (0 : C) = (0 : 0 ⟶ 0) := by ext /-- An arrow ending in the zero object is zero -/ -- This can't be a `simp` lemma because the left hand side would be a metavariable. lemma zero_of_to_zero {X : C} (f : X ⟶ 0) : f = 0 := by ext lemma zero_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : f = 0 := begin have h : f = f ≫ i.hom ≫ 𝟙 0 ≫ i.inv := by simp only [iso.hom_inv_id, id_comp, comp_id], simpa using h, end /-- An arrow starting at the zero object is zero -/ lemma zero_of_from_zero {X : C} (f : 0 ⟶ X) : f = 0 := by ext lemma zero_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : f = 0 := begin have h : f = i.hom ≫ 𝟙 0 ≫ i.inv ≫ f := by simp only [iso.hom_inv_id_assoc, id_comp, comp_id], simpa using h, end lemma mono_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : mono f := ⟨λ Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]⟩ lemma epi_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : epi f := ⟨λ Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]⟩ /-- An object `X` has `𝟙 X = 0` if and only if it is isomorphic to the zero object. Because `X ≅ 0` contains data (even if a subsingleton), we express this `↔` as an `≃`. -/ def id_zero_equiv_iso_zero (X : C) : (𝟙 X = 0) ≃ (X ≅ 0) := { to_fun := λ h, { hom := 0, inv := 0, }, inv_fun := λ i, zero_of_target_iso_zero (𝟙 X) i, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma id_zero_equiv_iso_zero_apply_hom (X : C) (h : 𝟙 X = 0) : ((id_zero_equiv_iso_zero X) h).hom = 0 := rfl @[simp] lemma id_zero_equiv_iso_zero_apply_inv (X : C) (h : 𝟙 X = 0) : ((id_zero_equiv_iso_zero X) h).inv = 0 := rfl end section is_iso variables [has_zero_morphisms C] /-- A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if the identities on both `X` and `Y` are zero. -/ @[simps] def is_iso_zero_equiv (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (𝟙 X = 0 ∧ 𝟙 Y = 0) := { to_fun := begin introsI i, rw ←is_iso.hom_inv_id (0 : X ⟶ Y), rw ←is_iso.inv_hom_id (0 : X ⟶ Y), simp, end, inv_fun := λ h, { inv := (0 : Y ⟶ X), }, left_inv := by tidy, right_inv := by tidy, } /-- A zero morphism `0 : X ⟶ X` is an isomorphism if and only if the identity on `X` is zero. -/ def is_iso_zero_self_equiv (X : C) : is_iso (0 : X ⟶ X) ≃ (𝟙 X = 0) := by simpa using is_iso_zero_equiv X X variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if `X` and `Y` are isomorphic to the zero object. -/ def is_iso_zero_equiv_iso_zero (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (X ≅ 0) × (Y ≅ 0) := begin -- This is lame, because `prod` can't cope with `Prop`, so we can't use `equiv.prod_congr`. refine (is_iso_zero_equiv X Y).trans _, symmetry, fsplit, { rintros ⟨eX, eY⟩, fsplit, exact (id_zero_equiv_iso_zero X).symm eX, exact (id_zero_equiv_iso_zero Y).symm eY, }, { rintros ⟨hX, hY⟩, fsplit, exact (id_zero_equiv_iso_zero X) hX, exact (id_zero_equiv_iso_zero Y) hY, }, { tidy, }, { tidy, }, end /-- A zero morphism `0 : X ⟶ X` is an isomorphism if and only if `X` is isomorphic to the zero object. -/ def is_iso_zero_self_equiv_iso_zero (X : C) : is_iso (0 : X ⟶ X) ≃ (X ≅ 0) := (is_iso_zero_equiv_iso_zero X X).trans subsingleton_prod_self_equiv end is_iso /-- If there are zero morphisms, any initial object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_initial_object [has_zero_morphisms C] [has_initial C] : has_zero_object C := { zero := ⊥_ C, unique_to := λ X, ⟨⟨0⟩, by tidy⟩, unique_from := λ X, ⟨⟨0⟩, λ f, calc f = f ≫ 𝟙 _ : (category.comp_id _).symm ... = f ≫ 0 : by congr ... = 0 : has_zero_morphisms.comp_zero _ _ ⟩ } /-- If there are zero morphisms, any terminal object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_terminal_object [has_zero_morphisms C] [has_terminal C] : has_zero_object C := { zero := ⊤_ C, unique_from := λ X, ⟨⟨0⟩, by tidy⟩, unique_to := λ X, ⟨⟨0⟩, λ f, calc f = 𝟙 _ ≫ f : (category.id_comp _).symm ... = 0 ≫ f : by congr ... = 0 : has_zero_morphisms.zero_comp _ _ ⟩ } section image variable [has_zero_morphisms C] lemma image_ι_comp_eq_zero {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f] [epi (factor_thru_image f)] (h : f ≫ g = 0) : image.ι f ≫ g = 0 := zero_of_epi_comp (factor_thru_image f) $ by simp [h] variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The zero morphism has a `mono_factorisation` through the zero object. -/ @[simps] def mono_factorisation_zero (X Y : C) : mono_factorisation (0 : X ⟶ Y) := { I := 0, m := 0, e := 0, } /-- Any zero morphism has an image. We don't set this as an instance, as it is only intended for use inside the following proofs. -/ def has_image.zero (X Y : C) : has_image (0 : X ⟶ Y) := { F := mono_factorisation_zero X Y, is_image := { lift := λ F', 0 }} /-- The image of a zero morphism is the zero object. -/ def image_zero {X Y : C} [has_image (0 : X ⟶ Y)] : image (0 : X ⟶ Y) ≅ 0 := is_image.iso_ext (image.is_image (0 : X ⟶ Y)) (has_image.zero X Y).is_image /-- The image of a morphism which is equal to zero is the zero object. -/ def image_zero' {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image f ≅ 0 := begin haveI := has_image.zero X Y, exact image.eq_to_iso h ≪≫ image_zero, end @[simp] lemma image.ι_zero {X Y : C} [has_image (0 : X ⟶ Y)] : image.ι (0 : X ⟶ Y) = 0 := begin rw ←image.lift_fac (mono_factorisation_zero X Y), simp, end /-- If we know `f = 0`, it requires a little work to conclude `image.ι f = 0`, because `f = g` only implies `image f ≅ image g`. -/ @[simp] lemma image.ι_zero' [has_equalizers C] {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image.ι f = 0 := begin haveI := has_image.zero X Y, rw image.eq_fac h, simp, end end image /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_sigma_ι {β : Type v} [decidable_eq β] [has_zero_morphisms C] (f : β → C) [has_colimit (discrete.functor f)] (b : β) : split_mono (sigma.ι f b) := { retraction := sigma.desc (λ b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_pi_π {β : Type v} [decidable_eq β] [has_zero_morphisms C] (f : β → C) [has_limit (discrete.functor f)] (b : β) : split_epi (pi.π f b) := { section_ := pi.lift (λ b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inl [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inl : X ⟶ X ⨿ Y) := { retraction := coprod.desc (𝟙 X) 0, } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inr [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inr : Y ⟶ X ⨿ Y) := { retraction := coprod.desc 0 (𝟙 Y), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_fst [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.fst : X ⨯ Y ⟶ X) := { section_ := prod.lift (𝟙 X) 0, } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_snd [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.snd : X ⨯ Y ⟶ Y) := { section_ := prod.lift 0 (𝟙 Y), } end category_theory.limits
88b630cc199edb09c101994185701844225b0e7c
367134ba5a65885e863bdc4507601606690974c1
/src/data/setoid/basic.lean
a52a98afd17ac6be01039ec9d397016fbb119670
[ "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
16,337
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen -/ import order.galois_connection /-! # Equivalence relations This file defines the complete lattice of equivalence relations on a type, results about the inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism theorems for quotients of arbitrary types. ## Implementation notes The function `rel` and lemmas ending in ' make it easier to talk about different equivalence relations on the same type. The complete lattice instance for equivalence relations could have been defined by lifting the Galois insertion of equivalence relations on α into binary relations on α, and then using `complete_lattice.copy` to define a complete lattice instance with more appropriate definitional equalities (a similar example is `filter.complete_lattice` in `order/filter/basic.lean`). This does not save space, however, and is less clear. Partitions are not defined as a separate structure here; users are encouraged to reason about them using the existing `setoid` and its infrastructure. ## Tags setoid, equivalence, iseqv, relation, equivalence relation -/ variables {α : Type*} {β : Type*} /-- A version of `setoid.r` that takes the equivalence relation as an explicit argument. -/ def setoid.rel (r : setoid α) : α → α → Prop := @setoid.r _ r /-- A version of `quotient.eq'` compatible with `setoid.rel`, to make rewriting possible. -/ lemma quotient.eq_rel {r : setoid α} {x y} : ⟦x⟧ = ⟦y⟧ ↔ r.rel x y := quotient.eq' namespace setoid @[ext] lemma ext' {r s : setoid α} (H : ∀ a b, r.rel a b ↔ s.rel a b) : r = s := ext H lemma ext_iff {r s : setoid α} : r = s ↔ ∀ a b, r.rel a b ↔ s.rel a b := ⟨λ h a b, h ▸ iff.rfl, ext'⟩ /-- Two equivalence relations are equal iff their underlying binary operations are equal. -/ theorem eq_iff_rel_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.rel = r₂.rel := ⟨λ h, h ▸ rfl, λ h, setoid.ext' $ λ x y, h ▸ iff.rfl⟩ /-- Defining `≤` for equivalence relations. -/ instance : has_le (setoid α) := ⟨λ r s, ∀ ⦃x y⦄, r.rel x y → s.rel x y⟩ theorem le_def {r s : setoid α} : r ≤ s ↔ ∀ {x y}, r.rel x y → s.rel x y := iff.rfl @[refl] lemma refl' (r : setoid α) (x) : r.rel x x := r.2.1 x @[symm] lemma symm' (r : setoid α) : ∀ {x y}, r.rel x y → r.rel y x := λ _ _ h, r.2.2.1 h @[trans] lemma trans' (r : setoid α) : ∀ {x y z}, r.rel x y → r.rel y z → r.rel x z := λ _ _ _ hx, r.2.2.2 hx /-- The kernel of a function is an equivalence relation. -/ def ker (f : α → β) : setoid α := ⟨λ x y, f x = f y, ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h, h.trans⟩⟩ /-- The kernel of the quotient map induced by an equivalence relation r equals r. -/ @[simp] lemma ker_mk_eq (r : setoid α) : ker (@quotient.mk _ r) = r := ext' $ λ x y, quotient.eq lemma ker_def {f : α → β} {x y : α} : (ker f).rel x y ↔ f x = f y := iff.rfl /-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`: `(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁` by `r` and `x₂` is related to `y₂` by `s`. -/ protected def prod (r : setoid α) (s : setoid β) : setoid (α × β) := { r := λ x y, r.rel x.1 y.1 ∧ s.rel x.2 y.2, iseqv := ⟨λ x, ⟨r.refl' x.1, s.refl' x.2⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩ } /-- The infimum of two equivalence relations. -/ instance : has_inf (setoid α) := ⟨λ r s, ⟨λ x y, r.rel x y ∧ s.rel x y, ⟨λ x, ⟨r.refl' x, s.refl' x⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩ /-- The infimum of 2 equivalence relations r and s is the same relation as the infimum of the underlying binary operations. -/ lemma inf_def {r s : setoid α} : (r ⊓ s).rel = r.rel ⊓ s.rel := rfl theorem inf_iff_and {r s : setoid α} {x y} : (r ⊓ s).rel x y ↔ r.rel x y ∧ s.rel x y := iff.rfl /-- The infimum of a set of equivalence relations. -/ instance : has_Inf (setoid α) := ⟨λ S, ⟨λ x y, ∀ r ∈ S, rel r x y, ⟨λ x r hr, r.refl' x, λ _ _ h r hr, r.symm' $ h r hr, λ _ _ _ h1 h2 r hr, r.trans' (h1 r hr) $ h2 r hr⟩⟩⟩ /-- The underlying binary operation of the infimum of a set of equivalence relations is the infimum of the set's image under the map to the underlying binary operation. -/ theorem Inf_def {s : set (setoid α)} : (Inf s).rel = Inf (rel '' s) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } instance : partial_order (setoid α) := { le := (≤), lt := λ r s, r ≤ s ∧ ¬s ≤ r, le_refl := λ _ _ _, id, le_trans := λ _ _ _ hr hs _ _ h, hs $ hr h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ r s h1 h2, setoid.ext' $ λ x y, ⟨λ h, h1 h, λ h, h2 h⟩ } /-- The complete lattice of equivalence relations on a type, with bottom element `=` and top element the trivial equivalence relation. -/ instance complete_lattice : complete_lattice (setoid α) := { inf := has_inf.inf, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ h1 h2 _ _ h, ⟨h1 h, h2 h⟩, top := ⟨λ _ _, true, ⟨λ _, trivial, λ _ _ h, h, λ _ _ _ h1 h2, h1⟩⟩, le_top := λ _ _ _ _, trivial, bot := ⟨(=), ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩⟩, bot_le := λ r x y h, h ▸ r.2.1 x, .. complete_lattice_of_Inf (setoid α) $ assume s, ⟨λ r hr x y h, h _ hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The inductively defined equivalence closure of a binary relation r is the infimum of the set of all equivalence relations containing r. -/ theorem eqv_gen_eq (r : α → α → Prop) : eqv_gen.setoid r = Inf {s : setoid α | ∀ ⦃x y⦄, r x y → s.rel x y} := le_antisymm (λ _ _ H, eqv_gen.rec (λ _ _ h _ hs, hs h) (refl' _) (λ _ _ _, symm' _) (λ _ _ _ _ _, trans' _) H) (Inf_le $ λ _ _ h, eqv_gen.rel _ _ h) /-- The supremum of two equivalence relations r and s is the equivalence closure of the binary relation `x is related to y by r or s`. -/ lemma sup_eq_eqv_gen (r s : setoid α) : r ⊔ s = eqv_gen.setoid (λ x y, r.rel x y ∨ s.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of 2 equivalence relations r and s is the equivalence closure of the supremum of the underlying binary operations. -/ lemma sup_def {r s : setoid α} : r ⊔ s = eqv_gen.setoid (r.rel ⊔ s.rel) := by rw sup_eq_eqv_gen; refl /-- The supremum of a set S of equivalence relations is the equivalence closure of the binary relation `there exists r ∈ S relating x and y`. -/ lemma Sup_eq_eqv_gen (S : set (setoid α)) : Sup S = eqv_gen.setoid (λ x y, ∃ r : setoid α, r ∈ S ∧ r.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [upper_bounds, le_def, and_imp, exists_imp_distrib], ext, exact ⟨λ H x y r hr, H hr, λ H r hr x y, H r hr⟩ end /-- The supremum of a set of equivalence relations is the equivalence closure of the supremum of the set's image under the map to the underlying binary operation. -/ lemma Sup_def {s : set (setoid α)} : Sup s = eqv_gen.setoid (Sup (rel '' s)) := begin rw [Sup_eq_eqv_gen, Sup_image], congr' with x y, simp only [supr_apply, supr_Prop_eq, exists_prop] end /-- The equivalence closure of an equivalence relation r is r. -/ @[simp] lemma eqv_gen_of_setoid (r : setoid α) : eqv_gen.setoid r.r = r := le_antisymm (by rw eqv_gen_eq; exact Inf_le (λ _ _, id)) eqv_gen.rel /-- Equivalence closure is idempotent. -/ @[simp] lemma eqv_gen_idem (r : α → α → Prop) : eqv_gen.setoid (eqv_gen.setoid r).rel = eqv_gen.setoid r := eqv_gen_of_setoid _ /-- The equivalence closure of a binary relation r is contained in any equivalence relation containing r. -/ theorem eqv_gen_le {r : α → α → Prop} {s : setoid α} (h : ∀ x y, r x y → s.rel x y) : eqv_gen.setoid r ≤ s := by rw eqv_gen_eq; exact Inf_le h /-- Equivalence closure of binary relations is monotonic. -/ theorem eqv_gen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) : eqv_gen.setoid r ≤ eqv_gen.setoid s := eqv_gen_le $ λ _ _ hr, eqv_gen.rel _ _ $ h _ _ hr /-- There is a Galois insertion of equivalence relations on α into binary relations on α, with equivalence closure the lower adjoint. -/ def gi : @galois_insertion (α → α → Prop) (setoid α) _ _ eqv_gen.setoid rel := { choice := λ r h, eqv_gen.setoid r, gc := λ r s, ⟨λ H _ _ h, H $ eqv_gen.rel _ _ h, λ H, eqv_gen_of_setoid s ▸ eqv_gen_mono H⟩, le_l_u := λ x, (eqv_gen_of_setoid x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } open function /-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice of equivalence relations on α. -/ theorem injective_iff_ker_bot (f : α → β) : injective f ↔ ker f = ⊥ := (@eq_bot_iff (setoid α) _ (ker f)).symm /-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/ lemma ker_iff_mem_preimage {f : α → β} {x y} : (ker f).rel x y ↔ x ∈ f ⁻¹' {f y} := iff.rfl /-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions `quotient r → β`. -/ def lift_equiv (r : setoid α) : {f : α → β // r ≤ ker f} ≃ (quotient r → β) := { to_fun := λ f, quotient.lift (f : α → β) f.2, inv_fun := λ f, ⟨f ∘ quotient.mk, λ x y h, by simp [ker_def, quotient.sound h]⟩, left_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ x, rfl, right_inv := λ f, funext $ λ x, quotient.induction_on' x $ λ x, rfl } /-- The uniqueness part of the universal property for quotients of an arbitrary type. -/ theorem lift_unique {r : setoid α} {f : α → β} (H : r ≤ ker f) (g : quotient r → β) (Hg : f = g ∘ quotient.mk) : quotient.lift f H = g := begin ext ⟨x⟩, erw [quotient.lift_mk f H, Hg], refl end /-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is injective. -/ lemma ker_lift_injective (f : α → β) : injective (@quotient.lift _ _ (ker f) f (λ _ _ h, h)) := λ x y, quotient.induction_on₂' x y $ λ a b h, quotient.sound' h /-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose induced map from the quotient of α to β is injective. -/ lemma ker_eq_lift_of_injective {r : setoid α} (f : α → β) (H : ∀ x y, r.rel x y → f x = f y) (h : injective (quotient.lift f H)) : ker f = r := le_antisymm (λ x y hk, quotient.exact $ h $ show quotient.lift f H ⟦x⟧ = quotient.lift f H ⟦y⟧, from hk) H variables (r : setoid α) (f : α → β) /-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f bijects with f's image. -/ noncomputable def quotient_ker_equiv_range : quotient (ker f) ≃ set.range f := equiv.of_bijective (@quotient.lift _ (set.range f) (ker f) (λ x, ⟨f x, set.mem_range_self x⟩) $ λ _ _ h, subtype.ext_val h) ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨@quotient.mk _ (ker f) z, by rw quotient.lift_mk; exact subtype.ext_iff_val.2 hz⟩⟩ /-- The quotient of α by the kernel of a surjective function f bijects with f's codomain. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : surjective f) : quotient (ker f) ≃ β := (quotient_ker_equiv_range f).trans $ equiv.subtype_univ_equiv hf variables {r f} /-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `r`.' -/ def map (r : setoid α) (f : α → β) : setoid β := eqv_gen.setoid $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b /-- Given a surjective function f whose kernel is contained in an equivalence relation r, the equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to the elements of f⁻¹(y) by r. -/ def map_of_surjective (r) (f : α → β) (h : ker f ≤ r) (hf : surjective f) : setoid β := ⟨λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b, ⟨λ x, let ⟨y, hy⟩ := hf x in ⟨y, y, hy, hy, r.refl' y⟩, λ _ _ ⟨x, y, hx, hy, h⟩, ⟨y, x, hy, hx, r.symm' h⟩, λ _ _ _ ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩, ⟨x, z, hx, hz, r.trans' h₁ $ r.trans' (h $ by rwa ←hy' at hy) h₂⟩⟩⟩ /-- A special case of the equivalence closure of an equivalence relation r equalling r. -/ lemma map_of_surjective_eq_map (h : ker f ≤ r) (hf : surjective f) : map r f = map_of_surjective r f h hf := by rw ←eqv_gen_of_setoid (map_of_surjective r f h hf); refl /-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. -/ def comap (f : α → β) (r : setoid β) : setoid α := ⟨λ x y, r.rel (f x) (f y), ⟨λ _, r.refl' _, λ _ _ h, r.symm' h, λ _ _ _ h1, r.trans' h1⟩⟩ /-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/ lemma comap_eq {f : α → β} {r : setoid β} : comap f r = ker (@quotient.mk _ r ∘ f) := ext $ λ x y, show _ ↔ ⟦_⟧ = ⟦_⟧, by rw quotient.eq; refl /-- The second isomorphism theorem for sets. -/ noncomputable def comap_quotient_equiv (f : α → β) (r : setoid β) : quotient (comap f r) ≃ set.range (@quotient.mk _ r ∘ f) := (quotient.congr_right $ ext_iff.1 comap_eq).trans $ quotient_ker_equiv_range $ quotient.mk ∘ f variables (r f) /-- The third isomorphism theorem for sets. -/ def quotient_quotient_equiv_quotient (s : setoid α) (h : r ≤ s) : quotient (ker (quot.map_right h)) ≃ quotient s := { to_fun := λ x, quotient.lift_on' x (λ w, quotient.lift_on' w (@quotient.mk _ s) $ λ x y H, quotient.sound $ h H) $ λ x y, quotient.induction_on₂' x y $ λ w z H, show @quot.mk _ _ _ = @quot.mk _ _ _, from H, inv_fun := λ x, quotient.lift_on' x (λ w, @quotient.mk _ (ker $ quot.map_right h) $ @quotient.mk _ r w) $ λ x y H, quotient.sound' $ show @quot.mk _ _ _ = @quot.mk _ _ _, from quotient.sound H, left_inv := λ x, quotient.induction_on' x $ λ y, quotient.induction_on' y $ λ w, by show ⟦_⟧ = _; refl, right_inv := λ x, quotient.induction_on' x $ λ y, by show ⟦_⟧ = _; refl } variables {r f} open quotient /-- Given an equivalence relation `r` on `α`, the order-preserving bijection between the set of equivalence relations containing `r` and the equivalence relations on the quotient of `α` by `r`. -/ def correspondence (r : setoid α) : {s // r ≤ s} ≃o setoid (quotient r) := { to_fun := λ s, map_of_surjective s.1 quotient.mk ((ker_mk_eq r).symm ▸ s.2) exists_rep, inv_fun := λ s, ⟨comap quotient.mk s, λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw eq_rel.2 h⟩, left_inv := λ s, subtype.ext_iff_val.2 $ ext' $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in s.1.trans' (s.1.symm' $ s.2 $ eq_rel.1 hx) $ s.1.trans' H $ s.2 $ eq_rel.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ s, let Hm : ker quotient.mk ≤ comap quotient.mk s := λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw (@eq_rel _ r x y).2 ((ker_mk_eq r) ▸ h) in ext' $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, quotient.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h x y hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨x, y, 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, λ h x y hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end setoid
05999bf236e687e8e71a7bfc556174e5c0b8d8b1
d757fb8bb0d538df3510904d3c09a0da191d06b9
/sf_weekdays.lean
b8b31b1be398396dd7d63cb558fa03740ef2e21d
[]
no_license
happy-bracket/lean_playground
188f64c2a431dec5617c75e33c7a75e475b9c23d
137b76966001091c445f6f472d27bbe5a8cf5d49
refs/heads/master
1,600,889,668,807
1,575,375,570,000
1,575,375,570,000
225,569,694
2
0
null
null
null
null
UTF-8
Lean
false
false
400
lean
inductive day : Type | monday | tuesday | wednesday | thursday | friday | saturday | sunday def next_weekday : day -> day | day.monday := day.tuesday | day.tuesday := day.wednesday | day.wednesday := day.thursday | day.thursday := day.friday | day.friday := day.saturday | day.saturday := day.sunday | day.sunday := day.monday example : next_weekday (next_weekday day.saturday) = day.monday := rfl
dd4b6099c8fd5280bd48c51d42dcdb66f213d147
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/algebra/order/compact.lean
c7e46e18e122e81b85903b4be221930c8701fd2e
[ "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
19,243
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Yury Kudryashov -/ import topology.algebra.order.intermediate_value import topology.local_extr /-! # Compactness of a closed interval > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that a closed interval in a conditionally complete linear ordered type with order topology (or a product of such types) is compact. We prove the extreme value theorem (`is_compact.exists_forall_le`, `is_compact.exists_forall_ge`): a continuous function on a compact set takes its minimum and maximum values. We provide many variations of this theorem. We also prove that the image of a closed interval under a continuous map is a closed interval, see `continuous_on.image_Icc`. ## Tags compact, extreme value theorem -/ open filter order_dual topological_space function set open_locale filter topology /-! ### Compactness of a closed interval In this section we define a typeclass `compact_Icc_space α` saying that all closed intervals in `α` are compact. Then we provide an instance for a `conditionally_complete_linear_order` and prove that the product (both `α × β` and an indexed product) of spaces with this property inherits the property. We also prove some simple lemmas about spaces with this property. -/ /-- This typeclass says that all closed intervals in `α` are compact. This is true for all conditionally complete linear orders with order topology and products (finite or infinite) of such spaces. -/ class compact_Icc_space (α : Type*) [topological_space α] [preorder α] : Prop := (is_compact_Icc : ∀ {a b : α}, is_compact (Icc a b)) export compact_Icc_space (is_compact_Icc) /-- A closed interval in a conditionally complete linear order is compact. -/ @[priority 100] instance conditionally_complete_linear_order.to_compact_Icc_space (α : Type*) [conditionally_complete_linear_order α] [topological_space α] [order_topology α] : compact_Icc_space α := begin refine ⟨λ a b, _⟩, cases le_or_lt a b with hab hab, swap, { simp [hab] }, refine is_compact_iff_ultrafilter_le_nhds.2 (λ f hf, _), contrapose! hf, rw [le_principal_iff], have hpt : ∀ x ∈ Icc a b, {x} ∉ f, from λ x hx hxf, hf x hx ((le_pure_iff.2 hxf).trans (pure_le_nhds x)), set s := {x ∈ Icc a b | Icc a x ∉ f}, have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2, have sbd : bdd_above s, from ⟨b, hsb⟩, have ha : a ∈ s, by simp [hpt, hab], rcases hab.eq_or_lt with rfl|hlt, { exact ha.2 }, set c := Sup s, have hsc : is_lub s c, from is_lub_cSup ⟨a, ha⟩ sbd, have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩, specialize hf c hc, have hcs : c ∈ s, { cases hc.1.eq_or_lt with heq hlt, { rwa ← heq }, refine ⟨hc, λ hcf, hf (λ U hU, _)⟩, rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' hlt).1 (mem_nhds_within_of_mem_nhds hU) with ⟨x, hxc, hxU⟩, rcases ((hsc.frequently_mem ⟨a, ha⟩).and_eventually (Ioc_mem_nhds_within_Iic ⟨hxc, le_rfl⟩)).exists with ⟨y, ⟨hyab, hyf⟩, hy⟩, refine mem_of_superset(f.diff_mem_iff.2 ⟨hcf, hyf⟩) (subset.trans _ hxU), rw diff_subset_iff, exact subset.trans Icc_subset_Icc_union_Ioc (union_subset_union subset.rfl $ Ioc_subset_Ioc_left hy.1.le) }, cases hc.2.eq_or_lt with heq hlt, { rw ← heq, exact hcs.2 }, contrapose! hf, intros U hU, rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds hU) with ⟨y, hxy, hyU⟩, refine mem_of_superset _ hyU, clear_dependent U, have hy : y ∈ Icc a b, from ⟨hc.1.trans hxy.1.le, hxy.2⟩, by_cases hay : Icc a y ∈ f, { refine mem_of_superset (f.diff_mem_iff.2 ⟨f.diff_mem_iff.2 ⟨hay, hcs.2⟩, hpt y hy⟩) _, rw [diff_subset_iff, union_comm, Ico_union_right hxy.1.le, diff_subset_iff], exact Icc_subset_Icc_union_Icc }, { exact ((hsc.1 ⟨hy, hay⟩).not_lt hxy.1).elim }, end instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)] [Π i, compact_Icc_space (α i)] : compact_Icc_space (Π i, α i) := ⟨λ a b, pi_univ_Icc a b ▸ is_compact_univ_pi $ λ i, is_compact_Icc⟩ instance pi.compact_Icc_space' {α β : Type*} [preorder β] [topological_space β] [compact_Icc_space β] : compact_Icc_space (α → β) := pi.compact_Icc_space instance {α β : Type*} [preorder α] [topological_space α] [compact_Icc_space α] [preorder β] [topological_space β] [compact_Icc_space β] : compact_Icc_space (α × β) := ⟨λ a b, (Icc_prod_eq a b).symm ▸ is_compact_Icc.prod is_compact_Icc⟩ /-- An unordered closed interval is compact. -/ lemma is_compact_uIcc {α : Type*} [linear_order α] [topological_space α] [compact_Icc_space α] {a b : α} : is_compact (uIcc a b) := is_compact_Icc /-- A complete linear order is a compact space. We do not register an instance for a `[compact_Icc_space α]` because this would only add instances for products (indexed or not) of complete linear orders, and we have instances with higher priority that cover these cases. -/ @[priority 100] -- See note [lower instance priority] instance compact_space_of_complete_linear_order {α : Type*} [complete_linear_order α] [topological_space α] [order_topology α] : compact_space α := ⟨by simp only [← Icc_bot_top, is_compact_Icc]⟩ section variables {α : Type*} [preorder α] [topological_space α] [compact_Icc_space α] instance compact_space_Icc (a b : α) : compact_space (Icc a b) := is_compact_iff_compact_space.mp is_compact_Icc end /-! ### Min and max elements of a compact set -/ variables {α β γ : Type*} [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [topological_space β] [topological_space γ] lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Inf s ∈ s := hs.is_closed.cInf_mem ne_s hs.bdd_below lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Sup s ∈ s := @is_compact.Inf_mem αᵒᵈ _ _ _ _ hs ne_s lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_glb s (Inf s) := is_glb_cInf ne_s hs.bdd_below lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_lub s (Sup s) := @is_compact.is_glb_Inf αᵒᵈ _ _ _ _ hs ne_s lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_least s (Inf s) := ⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩ lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_greatest s (Sup s) := @is_compact.is_least_Inf αᵒᵈ _ _ _ _ hs ne_s lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_least s x := ⟨_, hs.is_least_Inf ne_s⟩ lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_greatest s x := ⟨_, hs.is_greatest_Sup ne_s⟩ lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_glb s x := ⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩ lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_lub s x := ⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩ lemma is_compact.exists_Inf_image_eq_and_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃ x ∈ s, Inf (f '' s) = f x ∧ ∀ y ∈ s, f x ≤ f y := let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f) in ⟨x, hxs, hx.symm, λ y hy, hx.trans_le $ cInf_le (hs.image_of_continuous_on hf).bdd_below $ mem_image_of_mem f hy⟩ lemma is_compact.exists_Sup_image_eq_and_ge {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃ x ∈ s, Sup (f '' s) = f x ∧ ∀ y ∈ s, f y ≤ f x := @is_compact.exists_Inf_image_eq_and_le αᵒᵈ _ _ _ _ _ _ hs ne_s _ hf lemma is_compact.exists_Inf_image_eq {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃ x ∈ s, Inf (f '' s) = f x := let ⟨x, hxs, hx, _⟩ := hs.exists_Inf_image_eq_and_le ne_s hf in ⟨x, hxs, hx⟩ lemma is_compact.exists_Sup_image_eq : ∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s → ∃ x ∈ s, Sup (f '' s) = f x := @is_compact.exists_Inf_image_eq αᵒᵈ _ _ _ _ _ lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) : s = Icc (Inf s) (Sup s) := eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed /-! ### Extreme value theorem -/ /-- The **extreme value theorem**: a continuous function realizes its minimum on a compact set. -/ lemma is_compact.exists_forall_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃x∈s, ∀y∈s, f x ≤ f y := begin rcases (hs.image_of_continuous_on hf).exists_is_least (ne_s.image f) with ⟨_, ⟨x, hxs, rfl⟩, hx⟩, exact ⟨x, hxs, ball_image_iff.1 hx⟩ end /-- The **extreme value theorem**: a continuous function realizes its maximum on a compact set. -/ lemma is_compact.exists_forall_ge : ∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s → ∃x∈s, ∀y∈s, f y ≤ f x := @is_compact.exists_forall_le αᵒᵈ _ _ _ _ _ /-- The **extreme value theorem**: if a function `f` is continuous on a closed set `s` and it is larger than a value in its image away from compact sets, then it has a minimum on this set. -/ lemma continuous_on.exists_forall_le' {s : set β} {f : β → α} (hf : continuous_on f s) (hsc : is_closed s) {x₀ : β} (h₀ : x₀ ∈ s) (hc : ∀ᶠ x in cocompact β ⊓ 𝓟 s, f x₀ ≤ f x) : ∃ x ∈ s, ∀ y ∈ s, f x ≤ f y := begin rcases (has_basis_cocompact.inf_principal _).eventually_iff.1 hc with ⟨K, hK, hKf⟩, have hsub : insert x₀ (K ∩ s) ⊆ s, from insert_subset.2 ⟨h₀, inter_subset_right _ _⟩, obtain ⟨x, hx, hxf⟩ : ∃ x ∈ insert x₀ (K ∩ s), ∀ y ∈ insert x₀ (K ∩ s), f x ≤ f y := ((hK.inter_right hsc).insert x₀).exists_forall_le (insert_nonempty _ _) (hf.mono hsub), refine ⟨x, hsub hx, λ y hy, _⟩, by_cases hyK : y ∈ K, exacts [hxf _ (or.inr ⟨hyK, hy⟩), (hxf _ (or.inl rfl)).trans (hKf ⟨hyK, hy⟩)] end /-- The **extreme value theorem**: if a function `f` is continuous on a closed set `s` and it is smaller than a value in its image away from compact sets, then it has a maximum on this set. -/ lemma continuous_on.exists_forall_ge' {s : set β} {f : β → α} (hf : continuous_on f s) (hsc : is_closed s) {x₀ : β} (h₀ : x₀ ∈ s) (hc : ∀ᶠ x in cocompact β ⊓ 𝓟 s, f x ≤ f x₀) : ∃ x ∈ s, ∀ y ∈ s, f y ≤ f x := @continuous_on.exists_forall_le' αᵒᵈ _ _ _ _ _ _ _ hf hsc _ h₀ hc /-- The **extreme value theorem**: if a continuous function `f` is larger than a value in its range away from compact sets, then it has a global minimum. -/ lemma _root_.continuous.exists_forall_le' {f : β → α} (hf : continuous f) (x₀ : β) (h : ∀ᶠ x in cocompact β, f x₀ ≤ f x) : ∃ (x : β), ∀ (y : β), f x ≤ f y := let ⟨x, _, hx⟩ := hf.continuous_on.exists_forall_le' is_closed_univ (mem_univ x₀) (by rwa [principal_univ, inf_top_eq]) in ⟨x, λ y, hx y (mem_univ y)⟩ /-- The **extreme value theorem**: if a continuous function `f` is smaller than a value in its range away from compact sets, then it has a global maximum. -/ lemma _root_.continuous.exists_forall_ge' {f : β → α} (hf : continuous f) (x₀ : β) (h : ∀ᶠ x in cocompact β, f x ≤ f x₀) : ∃ (x : β), ∀ (y : β), f y ≤ f x := @continuous.exists_forall_le' αᵒᵈ _ _ _ _ _ _ hf x₀ h /-- The **extreme value theorem**: if a continuous function `f` tends to infinity away from compact sets, then it has a global minimum. -/ lemma _root_.continuous.exists_forall_le [nonempty β] {f : β → α} (hf : continuous f) (hlim : tendsto f (cocompact β) at_top) : ∃ x, ∀ y, f x ≤ f y := by { inhabit β, exact hf.exists_forall_le' default (hlim.eventually $ eventually_ge_at_top _) } /-- The **extreme value theorem**: if a continuous function `f` tends to negative infinity away from compact sets, then it has a global maximum. -/ lemma continuous.exists_forall_ge [nonempty β] {f : β → α} (hf : continuous f) (hlim : tendsto f (cocompact β) at_bot) : ∃ x, ∀ y, f y ≤ f x := @continuous.exists_forall_le αᵒᵈ _ _ _ _ _ _ _ hf hlim lemma is_compact.Sup_lt_iff_of_continuous {f : β → α} {K : set β} (hK : is_compact K) (h0K : K.nonempty) (hf : continuous_on f K) (y : α) : Sup (f '' K) < y ↔ ∀ x ∈ K, f x < y := begin refine ⟨λ h x hx, (le_cSup (hK.bdd_above_image hf) $ mem_image_of_mem f hx).trans_lt h, λ h, _⟩, obtain ⟨x, hx, h2x⟩ := hK.exists_forall_ge h0K hf, refine (cSup_le (h0K.image f) _).trans_lt (h x hx), rintro _ ⟨x', hx', rfl⟩, exact h2x x' hx' end lemma is_compact.lt_Inf_iff_of_continuous {α β : Type*} [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [topological_space β] {f : β → α} {K : set β} (hK : is_compact K) (h0K : K.nonempty) (hf : continuous_on f K) (y : α) : y < Inf (f '' K) ↔ ∀ x ∈ K, y < f x := @is_compact.Sup_lt_iff_of_continuous αᵒᵈ β _ _ _ _ _ _ hK h0K hf y /-- A continuous function with compact support has a global minimum. -/ @[to_additive "A continuous function with compact support has a global minimum."] lemma continuous.exists_forall_le_of_has_compact_mul_support [nonempty β] [has_one α] {f : β → α} (hf : continuous f) (h : has_compact_mul_support f) : ∃ (x : β), ∀ (y : β), f x ≤ f y := begin obtain ⟨_, ⟨x, rfl⟩, hx⟩ := (h.is_compact_range hf).exists_is_least (range_nonempty _), rw [mem_lower_bounds, forall_range_iff] at hx, exact ⟨x, hx⟩, end /-- A continuous function with compact support has a global maximum. -/ @[to_additive "A continuous function with compact support has a global maximum."] lemma continuous.exists_forall_ge_of_has_compact_mul_support [nonempty β] [has_one α] {f : β → α} (hf : continuous f) (h : has_compact_mul_support f) : ∃ (x : β), ∀ (y : β), f y ≤ f x := @continuous.exists_forall_le_of_has_compact_mul_support αᵒᵈ _ _ _ _ _ _ _ _ hf h lemma is_compact.continuous_Sup {f : γ → β → α} {K : set β} (hK : is_compact K) (hf : continuous ↿f) : continuous (λ x, Sup (f x '' K)) := begin rcases eq_empty_or_nonempty K with rfl|h0K, { simp_rw [image_empty], exact continuous_const }, rw [continuous_iff_continuous_at], intro x, obtain ⟨y, hyK, h2y, hy⟩ := hK.exists_Sup_image_eq_and_ge h0K (show continuous (λ y, f x y), from hf.comp $ continuous.prod.mk x).continuous_on, rw [continuous_at, h2y, tendsto_order], have := tendsto_order.mp ((show continuous (λ x, f x y), from hf.comp $ continuous_id.prod_mk continuous_const).tendsto x), refine ⟨λ z hz, _, λ z hz, _⟩, { refine (this.1 z hz).mono (λ x' hx', hx'.trans_le $ le_cSup _ $ mem_image_of_mem (f x') hyK), exact hK.bdd_above_image (hf.comp $ continuous.prod.mk x').continuous_on }, { have h : ({x} : set γ) ×ˢ K ⊆ ↿f ⁻¹' (Iio z), { rintro ⟨x', y'⟩ ⟨hx', hy'⟩, cases hx', exact (hy y' hy').trans_lt hz }, obtain ⟨u, v, hu, hv, hxu, hKv, huv⟩ := generalized_tube_lemma is_compact_singleton hK (is_open_Iio.preimage hf) h, refine eventually_of_mem (hu.mem_nhds (singleton_subset_iff.mp hxu)) (λ x' hx', _), rw [hK.Sup_lt_iff_of_continuous h0K (show continuous (f x'), from (hf.comp $ continuous.prod.mk x')).continuous_on], exact λ y' hy', huv (mk_mem_prod hx' (hKv hy')) } end lemma is_compact.continuous_Inf {f : γ → β → α} {K : set β} (hK : is_compact K) (hf : continuous ↿f) : continuous (λ x, Inf (f x '' K)) := @is_compact.continuous_Sup αᵒᵈ β γ _ _ _ _ _ _ _ hK hf namespace continuous_on /-! ### Image of a closed interval -/ variables [densely_ordered α] [conditionally_complete_linear_order β] [order_topology β] {f : α → β} {a b c : α} open_locale interval lemma image_Icc (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (is_compact_Icc.image_of_continuous_on h) lemma image_uIcc_eq_Icc (h : continuous_on f $ [a, b]) : f '' [a, b] = Icc (Inf (f '' [a, b])) (Sup (f '' [a, b])) := begin cases le_total a b with h2 h2, { simp_rw [uIcc_of_le h2] at h ⊢, exact h.image_Icc h2 }, { simp_rw [uIcc_of_ge h2] at h ⊢, exact h.image_Icc h2 }, end lemma image_uIcc (h : continuous_on f $ [a, b]) : f '' [a, b] = [Inf (f '' [a, b]), Sup (f '' [a, b])] := begin refine h.image_uIcc_eq_Icc.trans (uIcc_of_le _).symm, refine cInf_le_cSup _ _ (nonempty_uIcc.image _); rw h.image_uIcc_eq_Icc, exacts [bdd_below_Icc, bdd_above_Icc] end lemma Inf_image_Icc_le (h : continuous_on f $ Icc a b) (hc : c ∈ Icc a b) : Inf (f '' (Icc a b)) ≤ f c := begin rw h.image_Icc (nonempty_Icc.mp (set.nonempty_of_mem hc)), exact cInf_le bdd_below_Icc (mem_Icc.mpr ⟨cInf_le (is_compact_Icc.bdd_below_image h) ⟨c, hc, rfl⟩, le_cSup (is_compact_Icc.bdd_above_image h) ⟨c, hc, rfl⟩⟩), end lemma le_Sup_image_Icc (h : continuous_on f $ Icc a b) (hc : c ∈ Icc a b) : f c ≤ Sup (f '' (Icc a b)) := begin rw h.image_Icc (nonempty_Icc.mp (set.nonempty_of_mem hc)), exact le_cSup bdd_above_Icc (mem_Icc.mpr ⟨cInf_le (is_compact_Icc.bdd_below_image h) ⟨c, hc, rfl⟩, le_cSup (is_compact_Icc.bdd_above_image h) ⟨c, hc, rfl⟩⟩), end end continuous_on lemma is_compact.exists_local_min_on_mem_subset {f : β → α} {s t : set β} {z : β} (ht : is_compact t) (hf : continuous_on f t) (hz : z ∈ t) (hfz : ∀ z' ∈ t \ s, f z < f z') : ∃ x ∈ s, is_local_min_on f t x := begin obtain ⟨x, hx, hfx⟩ : ∃ x ∈ t, ∀ y ∈ t, f x ≤ f y := ht.exists_forall_le ⟨z, hz⟩ hf, have key : ∀ ⦃y⦄, y ∈ t → (∀ z' ∈ t \ s, f y < f z') → y ∈ s := λ y hy hfy, by { by_contra; simpa using ((hfy y ((mem_diff y).mpr ⟨hy,h⟩))) }, have h1 : ∀ z' ∈ t \ s, f x < f z' := λ z' hz', (hfx z hz).trans_lt (hfz z' hz'), have h2 : x ∈ s := key hx h1, refine ⟨x, h2, eventually_nhds_within_of_forall hfx⟩ end lemma is_compact.exists_local_min_mem_open {f : β → α} {s t : set β} {z : β} (ht : is_compact t) (hst : s ⊆ t) (hf : continuous_on f t) (hz : z ∈ t) (hfz : ∀ z' ∈ t \ s, f z < f z') (hs : is_open s) : ∃ x ∈ s, is_local_min f x := begin obtain ⟨x, hx, hfx⟩ := ht.exists_local_min_on_mem_subset hf hz hfz, exact ⟨x, hx, hfx.is_local_min (filter.mem_of_superset (hs.mem_nhds hx) hst)⟩ end
ddcbdeac7e1b5d60a0f17dd53eb487805f5c3cfa
222111140d2023e142b07e9cd5119ac2829b36f5
/src/row_equivalence_fields.lean
fc4e8bd7cf310d163ed001c4b1a58383bc16ea05
[]
no_license
jjcrawford/lean-gaussian-elimination
740dfdf2de89dc99c088c53e5221d9dfad3c0b92
c473d33c07fa6f141d17d9dc42ad07956c33dd03
refs/heads/master
1,585,793,867,436
1,540,443,865,000
1,540,443,865,000
153,901,939
0
0
null
null
null
null
UTF-8
Lean
false
false
3,430
lean
import ring_theory.matrix import row_equivalence import .finset_sum universes u variables {m n : ℕ} variable {α : Type u} variable [division_ring α] variable [decidable_eq α] def elementary.inv : (elementary α m) → (elementary α m) := begin intros e, cases e with i₁ s hs i₁ i₂ i₁ s i₂ h_ne, from elementary.scale i₁ s⁻¹ (inv_ne_zero hs), from @elementary.swap α _ _ _ i₂ i₁, from @elementary.linear_add α _ _ m i₁ (-s) i₂ h_ne, end instance elementary.has_inv : has_inv (elementary α m) := ⟨elementary.inv⟩ @[simp] lemma elementary.inv_inv : Π {e : elementary α m}, (e⁻¹)⁻¹ = e := begin intros e, cases e;{simp[has_inv.inv, elementary.inv], try{apply division_ring.inv_inv, assumption}} end theorem elementary.inv_apply_implements : Π {M N : matrix (fin m) (fin n) α} {e : elementary α m}, (elementary.apply e) M = N → M = (elementary.apply e⁻¹) N := begin intros M N e h, rw ←h, cases e with i₁ s hs i₁ i₂ i₁ s i₂ i_ne, -- scale case { simp[has_inv.inv, elementary.inv], simp[elementary.apply], funext i j, split_ifs with h₁, rw ←mul_assoc, erw inv_mul_cancel hs, simp, }, -- swap case { simp[has_inv.inv, elementary.inv], simp[elementary.apply], funext i j, split_ifs with h₁ h₂ h₃; {try{simp[h₁]}, try{simp[h₂], try{simp[h₃]}}}, }, -- linear_add case { simp[has_inv.inv, elementary.inv], simp[elementary.apply], funext i j, split_ifs with h₁ h₂;try{try{simp[h₁]}, try{simp[h₂]}}, exfalso, subst h₁, from i_ne (eq.symm h₂) } end theorem elementary.inv_apply_implements_iff_apply_implements : Π {M N : matrix (fin m) (fin n) α} {e : elementary α m}, (elementary.apply e) M = N ↔ M = (elementary.apply e⁻¹) N := begin intros M N e, split, apply elementary.inv_apply_implements, let e₁ := e⁻¹, have h₁ : e = e₁⁻¹, simp[e₁], rw h₁, simp, have H₁, from λ h₂, eq.symm ((@elementary.inv_apply_implements m n α _ _ N M (e⁻¹)) (eq.symm h₂)), rw elementary.inv_inv at H₁, from H₁ end theorem elementary.inv_matrix_implements_iff_matrix_implements : Π {M N : matrix (fin m) (fin n) α} {e : elementary α m}, matrix.mul (elementary.to_matrix e) M = N ↔ M = matrix.mul (elementary.to_matrix e⁻¹) N := begin intros M N e, simp[elementary.mul_eq_apply], apply elementary.inv_apply_implements_iff_apply_implements, end theorem inv_matrix_implements : Π {M N : matrix (fin m) (fin n) α} {e : elementary α m}, matrix.mul (elementary.to_matrix e) M = N → M = matrix.mul (elementary.to_matrix e⁻¹) N := λ M N e, iff.elim_left elementary.inv_matrix_implements_iff_matrix_implements def row_equivalent_step.symm : Π {M N : matrix (fin m) (fin n) α}, row_equivalent_step M N → row_equivalent_step N M := begin intros M N r, cases r with elem implements, constructor, from eq.symm (inv_matrix_implements implements), end def row_equivalent.symm : Π {M N : matrix (fin m) (fin n) α}, row_equivalent M N → row_equivalent N M | M N (row_equivalent.nil) := row_equivalent.nil | M N (row_equivalent.cons r₁ r₂) := r₁.symm.precons r₂.symm
c5f740012c5195ee1f6956a25b5299d454b88aa3
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/lie/skew_adjoint.lean
16e91f11ac0ca83d2f38125a8fb9758865ec137e
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
7,181
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.matrix import linear_algebra.bilinear_form /-! # Lie algebras of skew-adjoint endomorphisms of a bilinear form When a module carries a bilinear form, the Lie algebra of endomorphisms of the module contains a distinguished Lie subalgebra: the skew-adjoint endomorphisms. Such subalgebras are important because they provide a simple, explicit construction of the so-called classical Lie algebras. This file defines the Lie subalgebra of skew-adjoint endomorphims cut out by a bilinear form on a module and proves some basic related results. It also provides the corresponding definitions and results for the Lie algebra of square matrices. ## Main definitions * `skew_adjoint_lie_subalgebra` * `skew_adjoint_lie_subalgebra_equiv` * `skew_adjoint_matrices_lie_subalgebra` * `skew_adjoint_matrices_lie_subalgebra_equiv` ## Tags lie algebra, skew-adjoint, bilinear form -/ universes u v w w₁ section skew_adjoint_endomorphisms open bilin_form variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables (B : bilin_form R M) lemma bilin_form.is_skew_adjoint_bracket (f g : module.End R M) (hf : f ∈ B.skew_adjoint_submodule) (hg : g ∈ B.skew_adjoint_submodule) : ⁅f, g⁆ ∈ B.skew_adjoint_submodule := begin rw mem_skew_adjoint_submodule at *, have hfg : is_adjoint_pair B B (f * g) (g * f), { rw ←neg_mul_neg g f, exact hf.mul hg, }, have hgf : is_adjoint_pair B B (g * f) (f * g), { rw ←neg_mul_neg f g, exact hg.mul hf, }, change bilin_form.is_adjoint_pair B B (f * g - g * f) (-(f * g - g * f)), rw neg_sub, exact hfg.sub hgf, end /-- Given an `R`-module `M`, equipped with a bilinear form, the skew-adjoint endomorphisms form a Lie subalgebra of the Lie algebra of endomorphisms. -/ def skew_adjoint_lie_subalgebra : lie_subalgebra R (module.End R M) := { lie_mem' := B.is_skew_adjoint_bracket, ..B.skew_adjoint_submodule } variables {N : Type w} [add_comm_group N] [module R N] (e : N ≃ₗ[R] M) /-- An equivalence of modules with bilinear forms gives equivalence of Lie algebras of skew-adjoint endomorphisms. -/ def skew_adjoint_lie_subalgebra_equiv : skew_adjoint_lie_subalgebra (B.comp (↑e : N →ₗ[R] M) ↑e) ≃ₗ⁅R⁆ skew_adjoint_lie_subalgebra B := begin apply lie_equiv.of_subalgebras _ _ e.lie_conj, ext f, simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact (bilin_form.is_pair_self_adjoint_equiv (-B) B e f).symm, end @[simp] lemma skew_adjoint_lie_subalgebra_equiv_apply (f : skew_adjoint_lie_subalgebra (B.comp ↑e ↑e)) : ↑(skew_adjoint_lie_subalgebra_equiv B e f) = e.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] @[simp] lemma skew_adjoint_lie_subalgebra_equiv_symm_apply (f : skew_adjoint_lie_subalgebra B) : ↑((skew_adjoint_lie_subalgebra_equiv B e).symm f) = e.symm.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] end skew_adjoint_endomorphisms section skew_adjoint_matrices open_locale matrix variables {R : Type u} {n : Type w} [comm_ring R] [decidable_eq n] [fintype n] variables (J : matrix n n R) lemma matrix.lie_transpose (A B : matrix n n R) : ⁅A, B⁆ᵀ = ⁅Bᵀ, Aᵀ⁆ := show (A * B - B * A)ᵀ = (Bᵀ * Aᵀ - Aᵀ * Bᵀ), by simp lemma matrix.is_skew_adjoint_bracket (A B : matrix n n R) (hA : A ∈ skew_adjoint_matrices_submodule J) (hB : B ∈ skew_adjoint_matrices_submodule J) : ⁅A, B⁆ ∈ skew_adjoint_matrices_submodule J := begin simp only [mem_skew_adjoint_matrices_submodule] at *, change ⁅A, B⁆ᵀ ⬝ J = J ⬝ -⁅A, B⁆, change Aᵀ ⬝ J = J ⬝ -A at hA, change Bᵀ ⬝ J = J ⬝ -B at hB, simp only [←matrix.mul_eq_mul] at *, rw [matrix.lie_transpose, lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, sub_mul, mul_assoc, mul_assoc, hA, hB, ←mul_assoc, ←mul_assoc, hA, hB], noncomm_ring, end /-- The Lie subalgebra of skew-adjoint square matrices corresponding to a square matrix `J`. -/ def skew_adjoint_matrices_lie_subalgebra : lie_subalgebra R (matrix n n R) := { lie_mem' := J.is_skew_adjoint_bracket, ..(skew_adjoint_matrices_submodule J) } @[simp] lemma mem_skew_adjoint_matrices_lie_subalgebra (A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra J ↔ A ∈ skew_adjoint_matrices_submodule J := iff.rfl /-- An invertible matrix `P` gives a Lie algebra equivalence between those endomorphisms that are skew-adjoint with respect to a square matrix `J` and those with respect to `PᵀJP`. -/ noncomputable def skew_adjoint_matrices_lie_subalgebra_equiv (P : matrix n n R) (h : is_unit P) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (Pᵀ ⬝ J ⬝ P) := lie_equiv.of_subalgebras _ _ (P.lie_conj h).symm begin ext A, suffices : P.lie_conj h A ∈ skew_adjoint_matrices_submodule J ↔ A ∈ skew_adjoint_matrices_submodule (Pᵀ ⬝ J ⬝ P), { simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact this, }, simp [matrix.is_skew_adjoint, J.is_adjoint_pair_equiv _ _ P h], end lemma skew_adjoint_matrices_lie_subalgebra_equiv_apply (P : matrix n n R) (h : is_unit P) (A : skew_adjoint_matrices_lie_subalgebra J) : ↑(skew_adjoint_matrices_lie_subalgebra_equiv J P h A) = P⁻¹ ⬝ ↑A ⬝ P := by simp [skew_adjoint_matrices_lie_subalgebra_equiv] /-- An equivalence of matrix algebras commuting with the transpose endomorphisms restricts to an equivalence of Lie algebras of skew-adjoint matrices. -/ def skew_adjoint_matrices_lie_subalgebra_equiv_transpose {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (e J) := lie_equiv.of_subalgebras _ _ e.to_lie_equiv begin ext A, suffices : J.is_skew_adjoint (e.symm A) ↔ (e J).is_skew_adjoint A, by simpa [this], simp [matrix.is_skew_adjoint, matrix.is_adjoint_pair, ← matrix.mul_eq_mul, ← h, ← function.injective.eq_iff e.injective], end @[simp] lemma skew_adjoint_matrices_lie_subalgebra_equiv_transpose_apply {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) (A : skew_adjoint_matrices_lie_subalgebra J) : (skew_adjoint_matrices_lie_subalgebra_equiv_transpose J e h A : matrix m m R) = e A := rfl lemma mem_skew_adjoint_matrices_lie_subalgebra_unit_smul (u : units R) (J A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra (u • J) ↔ A ∈ skew_adjoint_matrices_lie_subalgebra J := begin change A ∈ skew_adjoint_matrices_submodule (u • J) ↔ A ∈ skew_adjoint_matrices_submodule J, simp only [mem_skew_adjoint_matrices_submodule, matrix.is_skew_adjoint, matrix.is_adjoint_pair], split; intros h, { simpa using congr_arg (λ B, u⁻¹ • B) h, }, { simp [h], }, end end skew_adjoint_matrices
2b6d03b03a8ddf8adac02e639f735dadb38cc2bd
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/direct_sum/basic.lean
7ffa3730b81b880188294d790849002fc3409fa4
[ "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
12,061
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.dfinsupp.basic import group_theory.submonoid.operations import group_theory.subgroup.basic /-! # Direct sum This file defines the direct sum of abelian groups, indexed by a discrete type. ## Notation `⨁ i, β i` is the n-ary direct sum `direct_sum`. This notation is in the `direct_sum` locale, accessible after `open_locale direct_sum`. ## References * https://en.wikipedia.org/wiki/Direct_sum -/ open_locale big_operators universes u v w u₁ variables (ι : Type v) [dec_ι : decidable_eq ι] (β : ι → Type w) /-- `direct_sum β` is the direct sum of a family of additive commutative monoids `β i`. Note: `open_locale direct_sum` will enable the notation `⨁ i, β i` for `direct_sum β`. -/ @[derive [add_comm_monoid, inhabited]] def direct_sum [Π i, add_comm_monoid (β i)] : Type* := Π₀ i, β i instance [Π i, add_comm_monoid (β i)] : has_coe_to_fun (direct_sum ι β) (λ _, Π i : ι, β i) := dfinsupp.has_coe_to_fun localized "notation `⨁` binders `, ` r:(scoped f, direct_sum _ f) := r" in direct_sum namespace direct_sum variables {ι} section add_comm_group variables [Π i, add_comm_group (β i)] instance : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group variables {β} @[simp] lemma sub_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := dfinsupp.sub_apply _ _ _ end add_comm_group variables [Π i, add_comm_monoid (β i)] @[simp] lemma zero_apply (i : ι) : (0 : ⨁ i, β i) i = 0 := rfl variables {β} @[simp] lemma add_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := dfinsupp.add_apply _ _ _ variables (β) include dec_ι /-- `mk β s x` is the element of `⨁ i, β i` that is zero outside `s` and has coefficient `x i` for `i` in `s`. -/ def mk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →+ ⨁ i, β i := { to_fun := dfinsupp.mk s, map_add' := λ _ _, dfinsupp.mk_add, map_zero' := dfinsupp.mk_zero, } /-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/ def of (i : ι) : β i →+ ⨁ i, β i := dfinsupp.single_add_hom β i @[simp] lemma of_eq_same (i : ι) (x : β i) : (of _ i x) i = x := dfinsupp.single_eq_same lemma of_eq_of_ne (i j : ι) (x : β i) (h : i ≠ j) : (of _ i x) j = 0 := dfinsupp.single_eq_of_ne h @[simp] lemma support_zero [Π (i : ι) (x : β i), decidable (x ≠ 0)] : (0 : ⨁ i, β i).support = ∅ := dfinsupp.support_zero @[simp] lemma support_of [Π (i : ι) (x : β i), decidable (x ≠ 0)] (i : ι) (x : β i) (h : x ≠ 0) : (of _ i x).support = {i} := dfinsupp.support_single_ne_zero h lemma support_of_subset [Π (i : ι) (x : β i), decidable (x ≠ 0)] {i : ι} {b : β i} : (of _ i b).support ⊆ {i} := dfinsupp.support_single_subset lemma sum_support_of [Π (i : ι) (x : β i), decidable (x ≠ 0)] (x : ⨁ i, β i) : ∑ i in x.support, of β i (x i) = x := dfinsupp.sum_single variables {β} theorem mk_injective (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_injective s theorem of_injective (i : ι) : function.injective (of β i) := dfinsupp.single_injective @[elab_as_eliminator] protected theorem induction_on {C : (⨁ i, β i) → Prop} (x : ⨁ i, β i) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. -/ lemma add_hom_ext {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (of _ i y) = g (of _ i y)) : f = g := dfinsupp.add_hom_ext H /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma add_hom_ext' {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι), f.comp (of _ i) = g.comp (of _ i)) : f = g := add_hom_ext $ λ i, add_monoid_hom.congr_fun $ H i variables {γ : Type u₁} [add_comm_monoid γ] section to_add_monoid variables (φ : Π i, β i →+ γ) (ψ : (⨁ i, β i) →+ γ) /-- `to_add_monoid φ` is the natural homomorphism from `⨁ i, β i` to `γ` induced by a family `φ` of homomorphisms `β i → γ`. -/ def to_add_monoid : (⨁ i, β i) →+ γ := (dfinsupp.lift_add_hom φ) @[simp] lemma to_add_monoid_of (i) (x : β i) : to_add_monoid φ (of β i x) = φ i x := dfinsupp.lift_add_hom_apply_single φ i x theorem to_add_monoid.unique (f : ⨁ i, β i) : ψ f = to_add_monoid (λ i, ψ.comp (of β i)) f := by {congr, ext, simp [to_add_monoid, of]} end to_add_monoid section from_add_monoid /-- `from_add_monoid φ` is the natural homomorphism from `γ` to `⨁ i, β i` induced by a family `φ` of homomorphisms `γ → β i`. Note that this is not an isomorphism. Not every homomorphism `γ →+ ⨁ i, β i` arises in this way. -/ def from_add_monoid : (⨁ i, γ →+ β i) →+ (γ →+ ⨁ i, β i) := to_add_monoid $ λ i, add_monoid_hom.comp_hom (of β i) @[simp] lemma from_add_monoid_of (i : ι) (f : γ →+ β i) : from_add_monoid (of _ i f) = (of _ i).comp f := by { rw [from_add_monoid, to_add_monoid_of], refl } lemma from_add_monoid_of_apply (i : ι) (f : γ →+ β i) (x : γ) : from_add_monoid (of _ i f) x = of _ i (f x) := by rw [from_add_monoid_of, add_monoid_hom.coe_comp] end from_add_monoid variables (β) /-- `set_to_set β S T h` is the natural homomorphism `⨁ (i : S), β i → ⨁ (i : T), β i`, where `h : S ⊆ T`. -/ -- TODO: generalize this to remove the assumption `S ⊆ T`. def set_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), β i) →+ (⨁ (i : T), β i) := to_add_monoid $ λ i, of (λ (i : subtype T), β i) ⟨↑i, H i.prop⟩ variables {β} omit dec_ι /-- A direct sum over an empty type is trivial. -/ instance [is_empty ι] : unique (⨁ i, β i) := dfinsupp.unique /-- The natural equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ protected def id (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [unique ι] : (⨁ (_ : ι), M) ≃+ M := { to_fun := direct_sum.to_add_monoid (λ _, add_monoid_hom.id M), inv_fun := of (λ _, M) default, left_inv := λ x, direct_sum.induction_on x (by rw [add_monoid_hom.map_zero, add_monoid_hom.map_zero]) (λ p x, by rw [unique.default_eq p, to_add_monoid_of]; refl) (λ x y ihx ihy, by rw [add_monoid_hom.map_add, add_monoid_hom.map_add, ihx, ihy]), right_inv := λ x, to_add_monoid_of _ _ _, ..direct_sum.to_add_monoid (λ _, add_monoid_hom.id M) } section congr_left variables {κ : Type*} /--Reindexing terms of a direct sum.-/ def equiv_congr_left (h : ι ≃ κ) : (⨁ i, β i) ≃+ ⨁ k, β (h.symm k) := { map_add' := dfinsupp.comap_domain'_add _ _, ..dfinsupp.equiv_congr_left h } @[simp] lemma equiv_congr_left_apply (h : ι ≃ κ) (f : ⨁ i, β i) (k : κ) : equiv_congr_left h f k = f (h.symm k) := dfinsupp.comap_domain'_apply _ _ _ _ end congr_left section option variables {α : option ι → Type w} [Π i, add_comm_monoid (α i)] include dec_ι /--Isomorphism obtained by separating the term of index `none` of a direct sum over `option ι`.-/ @[simps] noncomputable def add_equiv_prod_direct_sum : (⨁ i, α i) ≃+ α none × ⨁ i, α (some i) := { map_add' := dfinsupp.equiv_prod_dfinsupp_add, ..dfinsupp.equiv_prod_dfinsupp } end option section sigma variables {α : ι → Type u} {δ : Π i, α i → Type w} [Π i j, add_comm_monoid (δ i j)] /--The natural map between `⨁ (i : Σ i, α i), δ i.1 i.2` and `⨁ i (j : α i), δ i j`.-/ noncomputable def sigma_curry : (⨁ (i : Σ i, _), δ i.1 i.2) →+ ⨁ i j, δ i j := { to_fun := @dfinsupp.sigma_curry _ _ δ _, map_zero' := dfinsupp.sigma_curry_zero, map_add' := λ f g, dfinsupp.sigma_curry_add f g } @[simp] lemma sigma_curry_apply (f : ⨁ (i : Σ i, _), δ i.1 i.2) (i : ι) (j : α i) : sigma_curry f i j = f ⟨i, j⟩ := dfinsupp.sigma_curry_apply f i j /--The natural map between `⨁ i (j : α i), δ i j` and `Π₀ (i : Σ i, α i), δ i.1 i.2`, inverse of `curry`.-/ noncomputable def sigma_uncurry : (⨁ i j, δ i j) →+ ⨁ (i : Σ i, _), δ i.1 i.2 := { to_fun := dfinsupp.sigma_uncurry, map_zero' := dfinsupp.sigma_uncurry_zero, map_add' := dfinsupp.sigma_uncurry_add } @[simp] lemma sigma_uncurry_apply (f : ⨁ i j, δ i j) (i : ι) (j : α i) : sigma_uncurry f ⟨i, j⟩ = f i j := dfinsupp.sigma_uncurry_apply f i j /--The natural map between `⨁ (i : Σ i, α i), δ i.1 i.2` and `⨁ i (j : α i), δ i j`.-/ noncomputable def sigma_curry_equiv : (⨁ (i : Σ i, _), δ i.1 i.2) ≃+ ⨁ i j, δ i j := { ..sigma_curry, ..dfinsupp.sigma_curry_equiv } end sigma /-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `add_submonoid M` indexed by `ι`-/ def add_submonoid_coe {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) : (⨁ i, A i) →+ M := to_add_monoid (λ i, (A i).subtype) @[simp] lemma add_submonoid_coe_of {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) (i : ι) (x : A i) : add_submonoid_coe A (of (λ i, A i) i x) = x := to_add_monoid_of _ _ _ lemma coe_of_add_submonoid_apply {M : Type*} [decidable_eq ι] [add_comm_monoid M] {A : ι → add_submonoid M} (i j : ι) (x : A i) : (of _ i x j : M) = if i = j then x else 0 := begin obtain rfl | h := decidable.eq_or_ne i j, { rw [direct_sum.of_eq_same, if_pos rfl], }, { rw [direct_sum.of_eq_of_ne _ _ _ _ h, if_neg h, add_submonoid.coe_zero], }, end /-- The `direct_sum` formed by a collection of `add_submonoid`s of `M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective. See `direct_sum.add_subgroup_is_internal` for the same statement about `add_subgroup`s. -/ def add_submonoid_is_internal {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) : Prop := function.bijective (add_submonoid_coe A) lemma add_submonoid_is_internal.supr_eq_top {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) (h : add_submonoid_is_internal A) : supr A = ⊤ := begin rw [add_submonoid.supr_eq_mrange_dfinsupp_sum_add_hom, add_monoid_hom.mrange_top_iff_surjective], exact function.bijective.surjective h, end /-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `add_subgroup M` indexed by `ι`-/ def add_subgroup_coe {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : (⨁ i, A i) →+ M := to_add_monoid (λ i, (A i).subtype) @[simp] lemma add_subgroup_coe_of {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) (i : ι) (x : A i) : add_subgroup_coe A (of (λ i, A i) i x) = x := to_add_monoid_of _ _ _ lemma coe_of_add_subgroup_apply {M : Type*} [decidable_eq ι] [add_comm_group M] {A : ι → add_subgroup M} (i j : ι) (x : A i) : (of _ i x j : M) = if i = j then x else 0 := begin obtain rfl | h := decidable.eq_or_ne i j, { rw [direct_sum.of_eq_same, if_pos rfl], }, { rw [direct_sum.of_eq_of_ne _ _ _ _ h, if_neg h, add_subgroup.coe_zero], }, end /-- The `direct_sum` formed by a collection of `add_subgroup`s of `M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective. See `direct_sum.submodule_is_internal` for the same statement about `submodules`s. -/ def add_subgroup_is_internal {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : Prop := function.bijective (add_subgroup_coe A) lemma add_subgroup_is_internal.to_add_submonoid {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : add_subgroup_is_internal A ↔ add_submonoid_is_internal (λ i, (A i).to_add_submonoid) := iff.rfl end direct_sum
a1e03cb2067a8d8664beee652ab9bdf2670dfd7c
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/fintype/basic.lean
a5ae272ef743e52e53ce0e56f62ffa36334e0c75
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
40,502
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset import data.array.lemmas universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext' $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ /-- Given a linearly ordered fintype `α` of cardinal `k`, the equiv `mono_equiv_of_fin α h` is the increasing bijection between `fin k` and `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (α) [fintype α] [decidable_linear_order α] {k : ℕ} (h : fintype.card α = k) : fin k ≃ α := have A : bijective (mono_of_fin univ h) := begin apply set.bijective_iff_bij_on_univ.2, rw ← @coe_univ α _, exact mono_of_fin_bij_on (univ : finset α) h end, equiv.of_bijective A instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma fin.univ_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. -/ lemma finset.mono_of_fin_unique' [decidable_linear_order α] {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (fmap : set.maps_to f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin have finj : set.inj_on f set.univ := hmono.injective.inj_on _, apply mono_of_fin_unique h (set.bij_on.mk fmap finj (λ y hy, _)) hmono, simp only [set.image_univ, set.mem_range], rcases surj_on_of_inj_on_of_card_le (λ i (hi : i ∈ finset.univ), f i) (λ i hi, fmap (set.mem_univ i)) (λ i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij) (by simp [h]) y hy with ⟨x, _, hx⟩, exact ⟨x, hx.symm⟩ end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.exists_pair_of_one_lt_card [fintype α] (h : 1 < fintype.card α) : ∃ (a b : α), b ≠ a := begin rcases fintype.card_pos_iff.1 (nat.lt_of_succ_lt h) with a, exact ⟨a, fintype.exists_ne_of_one_lt_card h a⟩, end lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach lemma finset.card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y := begin let t : set α := ↑s, letI : fintype t := finset_coe.fintype s, have : fintype.card t = s.card := fintype.card_coe s, rw [← this, fintype.card_le_one_iff], split, { assume H x y hx hy, exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) }, { assume H x y, exact subtype.eq (H x.2 y.2) } end lemma finset.one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := begin classical, rw ← not_iff_not, push_neg, simpa [classical.or_iff_not_imp_left] using finset.card_le_one_iff end instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) namespace fintype variables [fintype α] [decidable_eq α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := set_fintype _ @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := begin rw [length_cons, nat.fact_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_right_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = finset.singleton x := begin apply symm, apply eq_of_subset_of_card_le (subset_univ (finset.singleton x)), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
817df3dd2ab6215e27d71e056833230bd7988642
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/limits_auto.lean
2c830b3b1e93ab34ffbb7488c3bddddd05224de6
[]
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
92,745
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.adjunction.basic import Mathlib.category_theory.limits.cones import Mathlib.category_theory.reflects_isomorphisms import Mathlib.PostPort universes v u l u' u'' namespace Mathlib /-! # Limits and colimits We set up the general theory of limits and colimits in a category. In this introduction we only describe the setup for limits; it is repeated, with slightly different names, for colimits. The three main structures involved are * `is_limit c`, for `c : cone F`, `F : J ⥤ C`, expressing that `c` is a limit cone, * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit F`, asserting the mere existence of some limit cone for `F`. `has_limit` is a propositional typeclass (it's important that it is a proposition merely asserting the existence of a limit, as otherwise we would have non-defeq problems from incompatible instances). Typically there are two different ways one can use the limits library: 1. working with particular cones, and terms of type `is_limit` 2. working solely with `has_limit`. While `has_limit` only asserts the existence of a limit cone, we happily use the axiom of choice in mathlib, so there are convenience functions all depending on `has_limit F`: * `limit F : C`, producing some limit object (of course all such are isomorphic) * `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit, * `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc. Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j` for every `j`. This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using automation (e.g. `tidy`). There are abbreviations `has_limits_of_shape J C` and `has_limits C` asserting the existence of classes of limits. Later more are introduced, for finite limits, special shapes of limits, etc. Ideally, many results about limits should be stated first in terms of `is_limit`, and then a result in terms of `has_limit` derived from this. At this point, however, this is far from uniformly achieved in mathlib --- often statements are only written in terms of `has_limit`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ namespace category_theory.limits /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. See https://stacks.math.columbia.edu/tag/002E. -/ structure is_limit {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (t : cone F) where lift : (s : cone F) → cone.X s ⟶ cone.X t fac' : autoParam (∀ (s : cone F) (j : J), lift s ≫ nat_trans.app (cone.π t) j = nat_trans.app (cone.π s) j) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) uniq' : autoParam (∀ (s : cone F) (m : cone.X s ⟶ cone.X t), (∀ (j : J), m ≫ nat_trans.app (cone.π t) j = nat_trans.app (cone.π s) j) → m = lift s) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem is_limit.fac {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (c : is_limit t) (s : cone F) (j : J) : is_limit.lift c s ≫ nat_trans.app (cone.π t) j = nat_trans.app (cone.π s) j := sorry @[simp] theorem is_limit.fac_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (c : is_limit t) (s : cone F) (j : J) {X' : C} (f' : functor.obj F j ⟶ X') : is_limit.lift c s ≫ nat_trans.app (cone.π t) j ≫ f' = nat_trans.app (cone.π s) j ≫ f' := sorry theorem is_limit.uniq {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (c : is_limit t) (s : cone F) (m : cone.X s ⟶ cone.X t) (w : ∀ (j : J), m ≫ nat_trans.app (cone.π t) j = nat_trans.app (cone.π s) j) : m = is_limit.lift c s := sorry namespace is_limit protected instance subsingleton {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} : subsingleton (is_limit t) := sorry /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cone point of any cone over `F` to the cone point of a limit cone over `G`. -/ def map {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (s : cone F) {t : cone G} (P : is_limit t) (α : F ⟶ G) : cone.X s ⟶ cone.X t := lift P (functor.obj (cones.postcompose α) s) @[simp] theorem map_π_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (c : cone F) {d : cone G} (hd : is_limit d) (α : F ⟶ G) (j : J) {X' : C} (f' : functor.obj G j ⟶ X') : map c hd α ≫ nat_trans.app (cone.π d) j ≫ f' = nat_trans.app (cone.π c) j ≫ nat_trans.app α j ≫ f' := sorry theorem lift_self {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {c : cone F} (t : is_limit c) : lift t c = 𝟙 := Eq.symm (uniq t c 𝟙 fun (j : J) => category.id_comp (nat_trans.app (cone.π c) j)) /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from any other cone to a limit cone. -/ @[simp] theorem lift_cone_morphism_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (h : is_limit t) (s : cone F) : cone_morphism.hom (lift_cone_morphism h s) = lift h s := Eq.refl (cone_morphism.hom (lift_cone_morphism h s)) theorem uniq_cone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} {t : cone F} (h : is_limit t) {f : s ⟶ t} {f' : s ⟶ t} : f = f' := (fun (this : ∀ {g : s ⟶ t}, g = lift_cone_morphism h s) => Eq.trans this (Eq.symm this)) fun (g : s ⟶ t) => cone_morphism.ext g (lift_cone_morphism h s) (uniq h s (cone_morphism.hom g) (cone_morphism.w g)) /-- Alternative constructor for `is_limit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ def mk_cone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (lift : (s : cone F) → s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := mk fun (s : cone F) => cone_morphism.hom (lift s) /-- Limit cones on `F` are unique up to isomorphism. -/ def unique_up_to_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} {t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := iso.mk (lift_cone_morphism Q s) (lift_cone_morphism P t) /-- Any cone morphism between limit cones is an isomorphism. -/ def hom_is_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} {t : cone F} (P : is_limit s) (Q : is_limit t) (f : s ⟶ t) : is_iso f := is_iso.mk (lift_cone_morphism P t) /-- Limits of `F` are unique up to isomorphism. -/ def cone_point_unique_up_to_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} {t : cone F} (P : is_limit s) (Q : is_limit t) : cone.X s ≅ cone.X t := functor.map_iso (cones.forget F) (unique_up_to_iso P Q) @[simp] theorem cone_point_unique_up_to_iso_hom_comp {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} {t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : iso.hom (cone_point_unique_up_to_iso P Q) ≫ nat_trans.app (cone.π t) j = nat_trans.app (cone.π s) j := cone_morphism.w (iso.hom (unique_up_to_iso P Q)) j @[simp] theorem cone_point_unique_up_to_iso_inv_comp_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} {t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) {X' : C} (f' : functor.obj F j ⟶ X') : iso.inv (cone_point_unique_up_to_iso P Q) ≫ nat_trans.app (cone.π s) j ≫ f' = nat_trans.app (cone.π t) j ≫ f' := sorry @[simp] theorem lift_comp_cone_point_unique_up_to_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {s : cone F} {t : cone F} (P : is_limit s) (Q : is_limit t) : lift P r ≫ iso.hom (cone_point_unique_up_to_iso P Q) = lift Q r := sorry @[simp] theorem lift_comp_cone_point_unique_up_to_iso_inv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {s : cone F} {t : cone F} (P : is_limit s) (Q : is_limit t) : lift Q r ≫ iso.inv (cone_point_unique_up_to_iso P Q) = lift P r := sorry /-- Transport evidence that a cone is a limit cone across an isomorphism of cones. -/ def of_iso_limit {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := mk_cone_morphism (fun (s : cone F) => lift_cone_morphism P s ≫ iso.hom i) sorry @[simp] theorem of_iso_limit_lift {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {t : cone F} (P : is_limit r) (i : r ≅ t) (s : cone F) : lift (of_iso_limit P i) s = lift P s ≫ cone_morphism.hom (iso.hom i) := rfl /-- Isomorphism of cones preserves whether or not they are limiting cones. -/ def equiv_iso_limit {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {t : cone F} (i : r ≅ t) : is_limit r ≃ is_limit t := equiv.mk (fun (h : is_limit r) => of_iso_limit h i) (fun (h : is_limit t) => of_iso_limit h (iso.symm i)) sorry sorry @[simp] theorem equiv_iso_limit_apply {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {t : cone F} (i : r ≅ t) (P : is_limit r) : coe_fn (equiv_iso_limit i) P = of_iso_limit P i := rfl @[simp] theorem equiv_iso_limit_symm_apply {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {t : cone F} (i : r ≅ t) (P : is_limit t) : coe_fn (equiv.symm (equiv_iso_limit i)) P = of_iso_limit P (iso.symm i) := rfl /-- If the canonical morphism from a cone point to a limiting cone point is an iso, then the first cone was limiting also. -/ def of_point_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cone F} {t : cone F} (P : is_limit r) [i : is_iso (lift P t)] : is_limit t := of_iso_limit P (iso.symm (as_iso (lift_cone_morphism P t))) theorem hom_lift {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (h : is_limit t) {W : C} (m : W ⟶ cone.X t) : m = lift h (cone.mk W (nat_trans.mk fun (b : J) => m ≫ nat_trans.app (cone.π t) b)) := uniq h (cone.mk W (nat_trans.mk fun (b : J) => m ≫ nat_trans.app (cone.π t) b)) m fun (b : J) => rfl /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ theorem hom_ext {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (h : is_limit t) {W : C} {f : W ⟶ cone.X t} {f' : W ⟶ cone.X t} (w : ∀ (j : J), f ≫ nat_trans.app (cone.π t) j = f' ≫ nat_trans.app (cone.π t) j) : f = f' := sorry /-- Given a right adjoint functor between categories of cones, the image of a limit cone is a limit cone. -/ def of_right_adjoint {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cone G ⥤ cone F) [is_right_adjoint h] {c : cone G} (t : is_limit c) : is_limit (functor.obj h c) := mk_cone_morphism (fun (s : cone F) => coe_fn (adjunction.hom_equiv (adjunction.of_right_adjoint h) s c) (lift_cone_morphism t (functor.obj (left_adjoint h) s))) sorry /-- Given two functors which have equivalent categories of cones, we can transport a limiting cone across the equivalence. -/ def of_cone_equiv {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} : is_limit (functor.obj (equivalence.functor h) c) ≃ is_limit c := equiv.mk (fun (P : is_limit (functor.obj (equivalence.functor h) c)) => of_iso_limit (of_right_adjoint (equivalence.inverse h) P) (iso.app (iso.symm (equivalence.unit_iso h)) c)) (of_right_adjoint (equivalence.functor h)) sorry sorry @[simp] theorem of_cone_equiv_apply_desc {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit (functor.obj (equivalence.functor h) c)) (s : cone G) : lift (coe_fn (of_cone_equiv h) P) s = (cone_morphism.hom (nat_trans.app (iso.hom (equivalence.unit_iso h)) s) ≫ cone_morphism.hom (functor.map (functor.inv (equivalence.functor h)) (lift_cone_morphism P (functor.obj (equivalence.functor h) s)))) ≫ cone_morphism.hom (nat_trans.app (iso.inv (equivalence.unit_iso h)) c) := rfl @[simp] theorem of_cone_equiv_symm_apply_desc {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit c) (s : cone F) : lift (coe_fn (equiv.symm (of_cone_equiv h)) P) s = cone_morphism.hom (nat_trans.app (iso.inv (equivalence.counit_iso h)) s) ≫ cone_morphism.hom (functor.map (equivalence.functor h) (lift_cone_morphism P (functor.obj (equivalence.inverse h) s))) := rfl /-- A cone postcomposed with a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_hom_equiv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : F ≅ G) (c : cone F) : is_limit (functor.obj (cones.postcompose (iso.hom α)) c) ≃ is_limit c := of_cone_equiv (cones.postcompose_equivalence α) /-- A cone postcomposed with the inverse of a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_inv_equiv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : F ≅ G) (c : cone G) : is_limit (functor.obj (cones.postcompose (iso.inv α)) c) ≃ is_limit c := postcompose_hom_equiv (iso.symm α) c /-- The cone points of two limit cones for naturally isomorphic functors are themselves isomorphic. -/ @[simp] theorem cone_points_iso_of_nat_iso_inv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : iso.inv (cone_points_iso_of_nat_iso P Q w) = map t P (iso.inv w) := Eq.refl (iso.inv (cone_points_iso_of_nat_iso P Q w)) theorem cone_points_iso_of_nat_iso_hom_comp_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) {X' : C} (f' : functor.obj G j ⟶ X') : iso.hom (cone_points_iso_of_nat_iso P Q w) ≫ nat_trans.app (cone.π t) j ≫ f' = nat_trans.app (cone.π s) j ≫ nat_trans.app (iso.hom w) j ≫ f' := sorry theorem cone_points_iso_of_nat_iso_inv_comp_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) {X' : C} (f' : functor.obj F j ⟶ X') : iso.inv (cone_points_iso_of_nat_iso P Q w) ≫ nat_trans.app (cone.π s) j ≫ f' = nat_trans.app (cone.π t) j ≫ nat_trans.app (iso.inv w) j ≫ f' := sorry theorem lift_comp_cone_points_iso_of_nat_iso_hom_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {r : cone F} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) {X' : C} (f' : cone.X t ⟶ X') : lift P r ≫ iso.hom (cone_points_iso_of_nat_iso P Q w) ≫ f' = map r Q (iso.hom w) ≫ f' := sorry /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} (P : is_limit s) (e : K ≌ J) : is_limit (cone.whisker (equivalence.functor e) s) := of_right_adjoint (equivalence.functor (cones.whiskering_equivalence e)) P /-- We can prove two cone points `(s : cone F).X` and `(t.cone F).X` are isomorphic if * both cones are limit cones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simp] theorem cone_points_iso_of_equivalence_hom {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {s : cone F} {G : K ⥤ C} {t : cone G} (P : is_limit s) (Q : is_limit t) (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) : iso.hom (cone_points_iso_of_equivalence P Q e w) = lift Q (functor.obj (equivalence.functor (cones.equivalence_of_reindexing (equivalence.symm e) (iso.symm (iso_whisker_left (equivalence.inverse e) w) ≪≫ equivalence.inv_fun_id_assoc e G))) s) := Eq.refl (iso.hom (cone_points_iso_of_equivalence P Q e w)) /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (h : is_limit t) (W : C) : (W ⟶ cone.X t) ≅ functor.obj (functor.const J) W ⟶ F := iso.mk (fun (f : W ⟶ cone.X t) => cone.π (cone.extend t f)) fun (π : functor.obj (functor.const J) W ⟶ F) => lift h (cone.mk W π) @[simp] theorem hom_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (h : is_limit t) {W : C} (f : W ⟶ cone.X t) : iso.hom (hom_iso h W) f = cone.π (cone.extend t f) := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (h : is_limit t) : functor.obj yoneda (cone.X t) ≅ functor.cones F := nat_iso.of_components (fun (W : Cᵒᵖ) => hom_iso h (opposite.unop W)) sorry /-- Another, more explicit, formulation of the universal property of a limit cone. See also `hom_iso`. -/ def hom_iso' {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (h : is_limit t) (W : C) : (W ⟶ cone.X t) ≅ Subtype fun (p : (j : J) → W ⟶ functor.obj F j) => ∀ {j j' : J} (f : j ⟶ j'), p j ≫ functor.map F f = p j' := hom_iso h W ≪≫ iso.mk (fun (π : functor.obj (functor.const J) W ⟶ F) => { val := fun (j : J) => nat_trans.app π j, property := sorry }) fun (p : Subtype fun (p : (j : J) → W ⟶ functor.obj F j) => ∀ {j j' : J} (f : j ⟶ j'), p j ≫ functor.map F f = p j') => nat_trans.mk fun (j : J) => subtype.val p j /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} {D : Type u'} [category D] (G : C ⥤ D) [faithful G] (ht : is_limit (functor.map_cone G t)) (lift : (s : cone F) → cone.X s ⟶ cone.X t) (h : ∀ (s : cone F), functor.map G (lift s) = lift ht (functor.map_cone G s)) : is_limit t := mk lift /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a limit implies `G.map_cone c` is also a limit. -/ def map_cone_equiv {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {K : J ⥤ C} {F : C ⥤ D} {G : C ⥤ D} (h : F ≅ G) {c : cone K} (t : is_limit (functor.map_cone F c)) : is_limit (functor.map_cone G c) := coe_fn (postcompose_inv_equiv (iso_whisker_left K h) (functor.map_cone G c)) (of_iso_limit t (iso.symm (functor.postcompose_whisker_left_map_cone (iso.symm h) c))) /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def iso_unique_cone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} : is_limit t ≅ (s : cone F) → unique (s ⟶ t) := iso.mk (fun (h : is_limit t) (s : cone F) => unique.mk { default := lift_cone_morphism h s } sorry) fun (h : (s : cone F) → unique (s ⟶ t)) => mk fun (s : cone F) => cone_morphism.hom Inhabited.default namespace of_nat_iso /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) {Y : C} (f : Y ⟶ X) : cone F := cone.mk Y (nat_trans.app (iso.hom h) (opposite.op Y) f) /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) (s : cone F) : cone.X s ⟶ X := nat_trans.app (iso.inv h) (opposite.op (cone.X s)) (cone.π s) @[simp] theorem cone_of_hom_of_cone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := sorry @[simp] theorem hom_of_cone_of_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app (iso.hom_inv_id h)) (opposite.op Y)) f /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) : cone F := cone_of_hom h 𝟙 /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ theorem cone_of_hom_fac {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) {Y : C} (f : Y ⟶ X) : cone_of_hom h f = cone.extend (limit_cone h) f := sorry /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ theorem cone_fac {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) (s : cone F) : cone.extend (limit_cone h) (hom_of_cone h s) = s := sorry end of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj yoneda X ≅ functor.cones F) : is_limit (of_nat_iso.limit_cone h) := mk fun (s : cone F) => sorry end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. See https://stacks.math.columbia.edu/tag/002F. -/ structure is_colimit {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (t : cocone F) where desc : (s : cocone F) → cocone.X t ⟶ cocone.X s fac' : autoParam (∀ (s : cocone F) (j : J), nat_trans.app (cocone.ι t) j ≫ desc s = nat_trans.app (cocone.ι s) j) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) uniq' : autoParam (∀ (s : cocone F) (m : cocone.X t ⟶ cocone.X s), (∀ (j : J), nat_trans.app (cocone.ι t) j ≫ m = nat_trans.app (cocone.ι s) j) → m = desc s) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem is_colimit.fac {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (c : is_colimit t) (s : cocone F) (j : J) : nat_trans.app (cocone.ι t) j ≫ is_colimit.desc c s = nat_trans.app (cocone.ι s) j := sorry @[simp] theorem is_colimit.fac_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (c : is_colimit t) (s : cocone F) (j : J) {X' : C} (f' : cocone.X s ⟶ X') : nat_trans.app (cocone.ι t) j ≫ is_colimit.desc c s ≫ f' = nat_trans.app (cocone.ι s) j ≫ f' := sorry theorem is_colimit.uniq {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (c : is_colimit t) (s : cocone F) (m : cocone.X t ⟶ cocone.X s) (w : ∀ (j : J), nat_trans.app (cocone.ι t) j ≫ m = nat_trans.app (cocone.ι s) j) : m = is_colimit.desc c s := sorry namespace is_colimit protected instance subsingleton {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} : subsingleton (is_colimit t) := sorry /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cocone point of a colimit cocone over `F` to the cocone point of any cocone over `G`. -/ def map {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cocone F} (P : is_colimit s) (t : cocone G) (α : F ⟶ G) : cocone.X s ⟶ cocone.X t := desc P (functor.obj (cocones.precompose α) t) @[simp] theorem ι_map {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {c : cocone F} (hc : is_colimit c) (d : cocone G) (α : F ⟶ G) (j : J) : nat_trans.app (cocone.ι c) j ≫ map hc d α = nat_trans.app α j ≫ nat_trans.app (cocone.ι d) j := fac hc (functor.obj (cocones.precompose α) d) j @[simp] theorem desc_self {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) : desc h t = 𝟙 := Eq.symm (uniq h t 𝟙 fun (j : J) => category.comp_id (nat_trans.app (cocone.ι t) j)) /- Repackaging the definition in terms of cocone morphisms. -/ /-- The universal morphism from a colimit cocone to any other cocone. -/ def desc_cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := cocone_morphism.mk (desc h s) theorem uniq_cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} {t : cocone F} (h : is_colimit t) {f : t ⟶ s} {f' : t ⟶ s} : f = f' := (fun (this : ∀ {g : t ⟶ s}, g = desc_cocone_morphism h s) => Eq.trans this (Eq.symm this)) fun (g : t ⟶ s) => cocone_morphism.ext g (desc_cocone_morphism h s) (uniq h s (cocone_morphism.hom g) (cocone_morphism.w g)) /-- Alternative constructor for `is_colimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ def mk_cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (desc : (s : cocone F) → t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := mk fun (s : cocone F) => cocone_morphism.hom (desc s) /-- Colimit cocones on `F` are unique up to isomorphism. -/ @[simp] theorem unique_up_to_iso_inv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} {t : cocone F} (P : is_colimit s) (Q : is_colimit t) : iso.inv (unique_up_to_iso P Q) = desc_cocone_morphism Q s := Eq.refl (iso.inv (unique_up_to_iso P Q)) /-- Any cocone morphism between colimit cocones is an isomorphism. -/ def hom_is_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} {t : cocone F} (P : is_colimit s) (Q : is_colimit t) (f : s ⟶ t) : is_iso f := is_iso.mk (desc_cocone_morphism Q s) /-- Colimits of `F` are unique up to isomorphism. -/ def cocone_point_unique_up_to_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} {t : cocone F} (P : is_colimit s) (Q : is_colimit t) : cocone.X s ≅ cocone.X t := functor.map_iso (cocones.forget F) (unique_up_to_iso P Q) @[simp] theorem comp_cocone_point_unique_up_to_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} {t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : nat_trans.app (cocone.ι s) j ≫ iso.hom (cocone_point_unique_up_to_iso P Q) = nat_trans.app (cocone.ι t) j := cocone_morphism.w (iso.hom (unique_up_to_iso P Q)) j @[simp] theorem comp_cocone_point_unique_up_to_iso_inv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} {t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : nat_trans.app (cocone.ι t) j ≫ iso.inv (cocone_point_unique_up_to_iso P Q) = nat_trans.app (cocone.ι s) j := cocone_morphism.w (iso.inv (unique_up_to_iso P Q)) j @[simp] theorem cocone_point_unique_up_to_iso_hom_desc_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {s : cocone F} {t : cocone F} (P : is_colimit s) (Q : is_colimit t) {X' : C} (f' : cocone.X r ⟶ X') : iso.hom (cocone_point_unique_up_to_iso P Q) ≫ desc Q r ≫ f' = desc P r ≫ f' := sorry @[simp] theorem cocone_point_unique_up_to_iso_inv_desc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {s : cocone F} {t : cocone F} (P : is_colimit s) (Q : is_colimit t) : iso.inv (cocone_point_unique_up_to_iso P Q) ≫ desc P r = desc Q r := sorry /-- Transport evidence that a cocone is a colimit cocone across an isomorphism of cocones. -/ def of_iso_colimit {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := mk_cocone_morphism (fun (s : cocone F) => iso.inv i ≫ desc_cocone_morphism P s) sorry @[simp] theorem of_iso_colimit_desc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {t : cocone F} (P : is_colimit r) (i : r ≅ t) (s : cocone F) : desc (of_iso_colimit P i) s = cocone_morphism.hom (iso.inv i) ≫ desc P s := rfl /-- Isomorphism of cocones preserves whether or not they are colimiting cocones. -/ def equiv_iso_colimit {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {t : cocone F} (i : r ≅ t) : is_colimit r ≃ is_colimit t := equiv.mk (fun (h : is_colimit r) => of_iso_colimit h i) (fun (h : is_colimit t) => of_iso_colimit h (iso.symm i)) sorry sorry @[simp] theorem equiv_iso_colimit_apply {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {t : cocone F} (i : r ≅ t) (P : is_colimit r) : coe_fn (equiv_iso_colimit i) P = of_iso_colimit P i := rfl @[simp] theorem equiv_iso_colimit_symm_apply {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {t : cocone F} (i : r ≅ t) (P : is_colimit t) : coe_fn (equiv.symm (equiv_iso_colimit i)) P = of_iso_colimit P (iso.symm i) := rfl /-- If the canonical morphism to a cocone point from a colimiting cocone point is an iso, then the first cocone was colimiting also. -/ def of_point_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {r : cocone F} {t : cocone F} (P : is_colimit r) [i : is_iso (desc P t)] : is_colimit t := of_iso_colimit P (as_iso (desc_cocone_morphism P t)) theorem hom_desc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) {W : C} (m : cocone.X t ⟶ W) : m = desc h (cocone.mk W (nat_trans.mk fun (b : J) => nat_trans.app (cocone.ι t) b ≫ m)) := uniq h (cocone.mk W (nat_trans.mk fun (b : J) => nat_trans.app (cocone.ι t) b ≫ m)) m fun (b : J) => rfl /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ theorem hom_ext {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) {W : C} {f : cocone.X t ⟶ W} {f' : cocone.X t ⟶ W} (w : ∀ (j : J), nat_trans.app (cocone.ι t) j ≫ f = nat_trans.app (cocone.ι t) j ≫ f') : f = f' := sorry /-- Given a left adjoint functor between categories of cocones, the image of a colimit cocone is a colimit cocone. -/ def of_left_adjoint {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cocone G ⥤ cocone F) [is_left_adjoint h] {c : cocone G} (t : is_colimit c) : is_colimit (functor.obj h c) := mk_cocone_morphism (fun (s : cocone F) => coe_fn (equiv.symm (adjunction.hom_equiv (adjunction.of_left_adjoint h) c s)) (desc_cocone_morphism t (functor.obj (right_adjoint h) s))) sorry /-- Given two functors which have equivalent categories of cocones, we can transport a colimiting cocone across the equivalence. -/ def of_cocone_equiv {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} : is_colimit (functor.obj (equivalence.functor h) c) ≃ is_colimit c := equiv.mk (fun (P : is_colimit (functor.obj (equivalence.functor h) c)) => of_iso_colimit (of_left_adjoint (equivalence.inverse h) P) (iso.app (iso.symm (equivalence.unit_iso h)) c)) (of_left_adjoint (equivalence.functor h)) sorry sorry @[simp] theorem of_cocone_equiv_apply_desc {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit (functor.obj (equivalence.functor h) c)) (s : cocone G) : desc (coe_fn (of_cocone_equiv h) P) s = cocone_morphism.hom (nat_trans.app (equivalence.unit h) c) ≫ cocone_morphism.hom (functor.map (equivalence.inverse h) (desc_cocone_morphism P (functor.obj (equivalence.functor h) s))) ≫ cocone_morphism.hom (nat_trans.app (equivalence.unit_inv h) s) := rfl @[simp] theorem of_cocone_equiv_symm_apply_desc {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit c) (s : cocone F) : desc (coe_fn (equiv.symm (of_cocone_equiv h)) P) s = cocone_morphism.hom (functor.map (equivalence.functor h) (desc_cocone_morphism P (functor.obj (equivalence.inverse h) s))) ≫ cocone_morphism.hom (nat_trans.app (equivalence.counit h) s) := rfl /-- A cocone precomposed with a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_hom_equiv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : F ≅ G) (c : cocone G) : is_colimit (functor.obj (cocones.precompose (iso.hom α)) c) ≃ is_colimit c := of_cocone_equiv (cocones.precompose_equivalence α) /-- A cocone precomposed with the inverse of a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_inv_equiv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : F ≅ G) (c : cocone F) : is_colimit (functor.obj (cocones.precompose (iso.inv α)) c) ≃ is_colimit c := precompose_hom_equiv (iso.symm α) c /-- The cocone points of two colimit cocones for naturally isomorphic functors are themselves isomorphic. -/ @[simp] theorem cocone_points_iso_of_nat_iso_inv {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : iso.inv (cocone_points_iso_of_nat_iso P Q w) = map Q s (iso.inv w) := Eq.refl (iso.inv (cocone_points_iso_of_nat_iso P Q w)) theorem comp_cocone_points_iso_of_nat_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) : nat_trans.app (cocone.ι s) j ≫ iso.hom (cocone_points_iso_of_nat_iso P Q w) = nat_trans.app (iso.hom w) j ≫ nat_trans.app (cocone.ι t) j := sorry theorem comp_cocone_points_iso_of_nat_iso_inv_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) {X' : C} (f' : cocone.X s ⟶ X') : nat_trans.app (cocone.ι t) j ≫ iso.inv (cocone_points_iso_of_nat_iso P Q w) ≫ f' = nat_trans.app (iso.inv w) j ≫ nat_trans.app (cocone.ι s) j ≫ f' := sorry theorem cocone_points_iso_of_nat_iso_hom_desc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {s : cocone F} {r : cocone G} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : iso.hom (cocone_points_iso_of_nat_iso P Q w) ≫ desc Q r = map P r (iso.hom w) := sorry /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} (P : is_colimit s) (e : K ≌ J) : is_colimit (cocone.whisker (equivalence.functor e) s) := of_left_adjoint (equivalence.functor (cocones.whiskering_equivalence e)) P /-- We can prove two cocone points `(s : cocone F).X` and `(t.cocone F).X` are isomorphic if * both cocones are colimit ccoones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cocone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simp] theorem cocone_points_iso_of_equivalence_hom {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} {s : cocone F} {G : K ⥤ C} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) : iso.hom (cocone_points_iso_of_equivalence P Q e w) = desc P (functor.obj (equivalence.functor (cocones.equivalence_of_reindexing e w)) t) := Eq.refl (iso.hom (cocone_points_iso_of_equivalence P Q e w)) /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) (W : C) : (cocone.X t ⟶ W) ≅ F ⟶ functor.obj (functor.const J) W := iso.mk (fun (f : cocone.X t ⟶ W) => cocone.ι (cocone.extend t f)) fun (ι : F ⟶ functor.obj (functor.const J) W) => desc h (cocone.mk W ι) @[simp] theorem hom_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) {W : C} (f : cocone.X t ⟶ W) : iso.hom (hom_iso h W) f = cocone.ι (cocone.extend t f) := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) : functor.obj coyoneda (opposite.op (cocone.X t)) ≅ functor.cocones F := nat_iso.of_components (hom_iso h) sorry /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `hom_iso`. -/ def hom_iso' {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (h : is_colimit t) (W : C) : (cocone.X t ⟶ W) ≅ Subtype fun (p : (j : J) → functor.obj F j ⟶ W) => ∀ {j j' : J} (f : j ⟶ j'), functor.map F f ≫ p j' = p j := hom_iso h W ≪≫ iso.mk (fun (ι : F ⟶ functor.obj (functor.const J) W) => { val := fun (j : J) => nat_trans.app ι j, property := sorry }) fun (p : Subtype fun (p : (j : J) → functor.obj F j ⟶ W) => ∀ {j j' : J} (f : j ⟶ j'), functor.map F f ≫ p j' = p j) => nat_trans.mk fun (j : J) => subtype.val p j /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} {D : Type u'} [category D] (G : C ⥤ D) [faithful G] (ht : is_colimit (functor.map_cocone G t)) (desc : (s : cocone F) → cocone.X t ⟶ cocone.X s) (h : ∀ (s : cocone F), functor.map G (desc s) = desc ht (functor.map_cocone G s)) : is_colimit t := mk desc /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a colimit implies `G.map_cone c` is also a colimit. -/ def map_cocone_equiv {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {K : J ⥤ C} {F : C ⥤ D} {G : C ⥤ D} (h : F ≅ G) {c : cocone K} (t : is_colimit (functor.map_cocone F c)) : is_colimit (functor.map_cocone G c) := of_iso_colimit (coe_fn (equiv.symm (precompose_inv_equiv (iso_whisker_left K h) (functor.map_cocone F c))) t) (functor.precompose_whisker_left_map_cocone h c) /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def iso_unique_cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} : is_colimit t ≅ (s : cocone F) → unique (t ⟶ s) := iso.mk (fun (h : is_colimit t) (s : cocone F) => unique.mk { default := desc_cocone_morphism h s } sorry) fun (h : (s : cocone F) → unique (t ⟶ s)) => mk fun (s : cocone F) => cocone_morphism.hom Inhabited.default namespace of_nat_iso /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) {Y : C} (f : X ⟶ Y) : cocone F := cocone.mk Y (nat_trans.app (iso.hom h) Y f) /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) (s : cocone F) : X ⟶ cocone.X s := nat_trans.app (iso.inv h) (cocone.X s) (cocone.ι s) @[simp] theorem cocone_of_hom_of_cocone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := sorry @[simp] theorem hom_of_cocone_of_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app (iso.hom_inv_id h)) Y) f /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) : cocone F := cocone_of_hom h 𝟙 /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ theorem cocone_of_hom_fac {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = cocone.extend (colimit_cocone h) f := sorry /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ theorem cocone_fac {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) (s : cocone F) : cocone.extend (colimit_cocone h) (hom_of_cocone h s) = s := sorry end of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {X : C} (h : functor.obj coyoneda (opposite.op X) ≅ functor.cocones F) : is_colimit (of_nat_iso.colimit_cocone h) := mk fun (s : cocone F) => sorry end is_colimit /-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/ structure limit_cone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) where cone : cone F is_limit : is_limit cone /-- `has_limit F` represents the mere existence of a limit for `F`. -/ class has_limit {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) where mk' :: (exists_limit : Nonempty (limit_cone F)) theorem has_limit.mk {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (d : limit_cone F) : has_limit F := has_limit.mk' (Nonempty.intro d) /-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/ def get_limit_cone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] : limit_cone F := Classical.choice has_limit.exists_limit /-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/ class has_limits_of_shape (J : Type v) [small_category J] (C : Type u) [category C] where has_limit : ∀ (F : J ⥤ C), has_limit F /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits (C : Type u) [category C] where has_limits_of_shape : ∀ (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C protected instance has_limit_of_has_limits_of_shape {C : Type u} [category C] {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F protected instance has_limits_of_shape_of_has_limits {C : Type u} [category C] {J : Type v} [small_category J] [H : has_limits C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- An arbitrary choice of limit cone for a functor. -/ def limit.cone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] : cone F := limit_cone.cone (get_limit_cone F) /-- An arbitrary choice of limit object of a functor. -/ def limit {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] : C := cone.X sorry /-- The projection from the limit object to a value of the functor. -/ def limit.π {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ functor.obj F j := nat_trans.app (cone.π (limit.cone F)) j @[simp] theorem limit.cone_X {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] : cone.X (limit.cone F) = limit F := rfl @[simp] theorem limit.cone_π {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] : nat_trans.app (cone.π (limit.cone F)) = limit.π F := rfl @[simp] theorem limit.w {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] {j : J} {j' : J} (f : j ⟶ j') : limit.π F j ≫ functor.map F f = limit.π F j' := cone.w (limit.cone F) f /-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/ def limit.is_limit {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := limit_cone.is_limit (get_limit_cone F) /-- The morphism from the cone point of any other cone to the limit object. -/ def limit.lift {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (c : cone F) : cone.X c ⟶ limit F := is_limit.lift (limit.is_limit F) c @[simp] theorem limit.is_limit_lift {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (c : cone F) : is_limit.lift (limit.is_limit F) c = limit.lift F c := rfl @[simp] theorem limit.lift_π {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = nat_trans.app (cone.π c) j := is_limit.fac (limit.is_limit F) c j /-- Functoriality of limits. Usually this morphism should be accessed through `lim.map`, but may be needed separately when you have specified limits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def lim_map {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G := is_limit.map (limit.cone F) (limit.is_limit G) α @[simp] theorem lim_map_π {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) : lim_map α ≫ limit.π G j = limit.π F j ≫ nat_trans.app α j := limit.lift_π (functor.obj (cones.postcompose α) (limit.cone F)) j /-- The cone morphism from any cone to the arbitrary choice of limit cone. -/ def limit.cone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ limit.cone F := is_limit.lift_cone_morphism (limit.is_limit F) c @[simp] theorem limit.cone_morphism_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (c : cone F) : cone_morphism.hom (limit.cone_morphism c) = limit.lift F c := rfl theorem limit.cone_morphism_π {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : cone_morphism.hom (limit.cone_morphism c) ≫ limit.π F j = nat_trans.app (cone.π c) j := sorry @[simp] theorem limit.cone_point_unique_up_to_iso_hom_comp {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : iso.hom (is_limit.cone_point_unique_up_to_iso hc (limit.is_limit F)) ≫ limit.π F j = nat_trans.app (cone.π c) j := is_limit.cone_point_unique_up_to_iso_hom_comp hc (limit.is_limit F) j @[simp] theorem limit.cone_point_unique_up_to_iso_inv_comp {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : iso.inv (is_limit.cone_point_unique_up_to_iso (limit.is_limit F) hc) ≫ limit.π F j = nat_trans.app (cone.π c) j := is_limit.cone_point_unique_up_to_iso_inv_comp (limit.is_limit F) hc j /-- Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point. -/ def limit.iso_limit_cone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (t : limit_cone F) : limit F ≅ cone.X (limit_cone.cone t) := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (limit_cone.is_limit t) @[simp] theorem limit.iso_limit_cone_hom_π_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) {X' : C} (f' : functor.obj F j ⟶ X') : iso.hom (limit.iso_limit_cone t) ≫ nat_trans.app (cone.π (limit_cone.cone t)) j ≫ f' = limit.π F j ≫ f' := sorry @[simp] theorem limit.iso_limit_cone_inv_π {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : iso.inv (limit.iso_limit_cone t) ≫ limit.π F j = nat_trans.app (cone.π (limit_cone.cone t)) j := sorry theorem limit.hom_ext {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] {X : C} {f : X ⟶ limit F} {f' : X ⟶ limit F} (w : ∀ (j : J), f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := is_limit.hom_ext (limit.is_limit F) w @[simp] theorem limit.lift_map {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_limit F] [has_limit G] (c : cone F) (α : F ⟶ G) : limit.lift F c ≫ lim_map α = limit.lift G (functor.obj (cones.postcompose α) c) := sorry @[simp] theorem limit.lift_cone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] : limit.lift F (limit.cone F) = 𝟙 := is_limit.lift_self (limit.is_limit F) /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ functor.obj (functor.cones F) (opposite.op W) := is_limit.hom_iso (limit.is_limit F) W @[simp] theorem limit.hom_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : iso.hom (limit.hom_iso F W) f = functor.map (functor.const J) f ≫ cone.π (limit.cone F) := is_limit.hom_iso_hom (limit.is_limit F) f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ Subtype fun (p : (j : J) → W ⟶ functor.obj F j) => ∀ {j j' : J} (f : j ⟶ j'), p j ≫ functor.map F f = p j' := is_limit.hom_iso' (limit.is_limit F) W theorem limit.lift_extend {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ cone.X c) : limit.lift F (cone.extend c f) = f ≫ limit.lift F c := sorry /-- If a functor `F` has a limit, so does any naturally isomorphic functor. -/ theorem has_limit_of_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := has_limit.mk (limit_cone.mk (functor.obj (cones.postcompose (iso.hom α)) (limit.cone F)) (is_limit.mk fun (s : cone G) => limit.lift F (functor.obj (cones.postcompose (iso.inv α)) s))) /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. theorem has_limit.of_cones_iso {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : functor.cones F ≅ functor.cones G) [has_limit F] : has_limit G := has_limit.mk (limit_cone.mk (is_limit.of_nat_iso.limit_cone (is_limit.nat_iso (limit.is_limit F) ≪≫ h)) (is_limit.of_nat_iso (is_limit.nat_iso (limit.is_limit F) ≪≫ h))) /-- The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_limit.iso_of_nat_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) : limit F ≅ limit G := is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w @[simp] theorem has_limit.iso_of_nat_iso_hom_π {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) (j : J) : iso.hom (has_limit.iso_of_nat_iso w) ≫ limit.π G j = limit.π F j ≫ nat_trans.app (iso.hom w) j := is_limit.cone_points_iso_of_nat_iso_hom_comp (limit.is_limit F) (limit.is_limit G) w j @[simp] theorem has_limit.lift_iso_of_nat_iso_hom_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_limit F] [has_limit G] (t : cone F) (w : F ≅ G) {X' : C} (f' : limit G ⟶ X') : limit.lift F t ≫ iso.hom (has_limit.iso_of_nat_iso w) ≫ f' = limit.lift G (functor.obj (cones.postcompose (iso.hom w)) t) ≫ f' := sorry /-- The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_limit.iso_of_equivalence {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) : limit F ≅ limit G := is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w @[simp] theorem has_limit.iso_of_equivalence_hom_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) (k : K) : iso.hom (has_limit.iso_of_equivalence e w) ≫ limit.π G k = limit.π F (functor.obj (equivalence.inverse e) k) ≫ nat_trans.app (iso.inv w) (functor.obj (equivalence.inverse e) k) ≫ functor.map G (nat_trans.app (equivalence.counit e) k) := sorry @[simp] theorem has_limit.iso_of_equivalence_inv_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) (j : J) : iso.inv (has_limit.iso_of_equivalence e w) ≫ limit.π F j = limit.π G (functor.obj (equivalence.functor e) j) ≫ nat_trans.app (iso.hom w) j := sorry /-- The canonical morphism from the limit of `F` to the limit of `E ⋙ F`. -/ def limit.pre {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) (cone.whisker E (limit.cone F)) @[simp] theorem limit.pre_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (functor.obj E k) := sorry @[simp] theorem limit.lift_pre {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (cone.whisker E c) := sorry @[simp] theorem limit.pre_pre {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] {L : Type v} [small_category L] (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := sorry /--- If we have particular limit cones available for `E ⋙ F` and for `F`, we obtain a formula for `limit.pre F E`. -/ theorem limit.pre_eq {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_limit F] {E : K ⥤ J} [has_limit (E ⋙ F)] (s : limit_cone (E ⋙ F)) (t : limit_cone F) : limit.pre F E = iso.hom (limit.iso_limit_cone t) ≫ is_limit.lift (limit_cone.is_limit s) (cone.whisker E (limit_cone.cone t)) ≫ iso.inv (limit.iso_limit_cone s) := sorry /-- The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`. -/ def limit.post {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] : functor.obj G (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) (functor.map_cone G (limit.cone F)) @[simp] theorem limit.post_π_assoc {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] (j : J) {X' : D} (f' : functor.obj (F ⋙ G) j ⟶ X') : limit.post F G ≫ limit.π (F ⋙ G) j ≫ f' = functor.map G (limit.π F j) ≫ f' := sorry @[simp] theorem limit.lift_post {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] (c : cone F) : functor.map G (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (functor.map_cone G c) := sorry @[simp] theorem limit.post_post {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] {E : Type u''} [category E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : functor.map H (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := sorry /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ theorem limit.pre_post {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {D : Type u'} [category D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : functor.map G (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := sorry /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ protected instance has_limit_equivalence_comp {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} (e : K ≌ J) [has_limit F] : has_limit (equivalence.functor e ⋙ F) := has_limit.mk (limit_cone.mk (cone.whisker (equivalence.functor e) (limit.cone F)) (is_limit.whisker_equivalence (limit.is_limit F) e)) /-- If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`. -/ theorem has_limit_of_equivalence_comp {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} (e : K ≌ J) [has_limit (equivalence.functor e ⋙ F)] : has_limit F := has_limit_of_iso (equivalence.inv_fun_id_assoc e F) -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ def lim {J : Type v} [small_category J] {C : Type u} [category C] [has_limits_of_shape J C] : (J ⥤ C) ⥤ C := functor.mk (fun (F : J ⥤ C) => limit F) fun (F G : J ⥤ C) (α : F ⟶ G) => lim_map α -- We generate this manually since `simps` gives it a weird name. @[simp] theorem lim_map_eq_lim_map {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limits_of_shape J C] {G : J ⥤ C} (α : F ⟶ G) : functor.map lim α = lim_map α := rfl theorem limit.map_pre {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_limits_of_shape J C] {G : J ⥤ C} (α : F ⟶ G) [has_limits_of_shape K C] (E : K ⥤ J) : functor.map lim α ≫ limit.pre G E = limit.pre F E ≫ functor.map lim (whisker_left E α) := sorry theorem limit.map_pre' {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] [has_limits_of_shape J C] [has_limits_of_shape K C] (F : J ⥤ C) {E₁ : K ⥤ J} {E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ functor.map lim (whisker_right α F) := sorry theorem limit.id_pre {J : Type v} [small_category J] {C : Type u} [category C] [has_limits_of_shape J C] (F : J ⥤ C) : limit.pre F 𝟭 = functor.map lim (iso.inv (functor.left_unitor F)) := sorry /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs theorem limit.map_post {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_limits_of_shape J C] {G : J ⥤ C} (α : F ⟶ G) {D : Type u'} [category D] [has_limits_of_shape J D] (H : C ⥤ D) : functor.map H (lim_map α) ≫ limit.post G H = limit.post F H ≫ lim_map (whisker_right α H) := sorry H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda {J : Type v} [small_category J] {C : Type u} [category C] [has_limits_of_shape J C] : lim ⋙ yoneda ≅ cones J C := nat_iso.of_components (fun (F : J ⥤ C) => nat_iso.of_components (fun (W : Cᵒᵖ) => limit.hom_iso F (opposite.unop W)) sorry) sorry /-- We can transport limits of shape `J` along an equivalence `J ≌ J'`. -/ theorem has_limits_of_shape_of_equivalence {J : Type v} [small_category J] {C : Type u} [category C] {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := has_limits_of_shape.mk fun (F : J' ⥤ C) => has_limit_of_equivalence_comp e /-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a colimit. -/ structure colimit_cocone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) where cocone : cocone F is_colimit : is_colimit cocone /-- `has_colimit F` represents the mere existence of a colimit for `F`. -/ class has_colimit {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) where mk' :: (exists_colimit : Nonempty (colimit_cocone F)) theorem has_colimit.mk {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F := has_colimit.mk' (Nonempty.intro d) /-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/ def get_colimit_cocone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] : colimit_cocone F := Classical.choice has_colimit.exists_colimit /-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/ class has_colimits_of_shape (J : Type v) [small_category J] (C : Type u) [category C] where has_colimit : ∀ (F : J ⥤ C), has_colimit F /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits (C : Type u) [category C] where has_colimits_of_shape : ∀ (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C protected instance has_colimit_of_has_colimits_of_shape {C : Type u} [category C] {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F protected instance has_colimits_of_shape_of_has_colimits {C : Type u} [category C] {J : Type v} [small_category J] [H : has_colimits C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- An arbitrary choice of colimit cocone of a functor. -/ def colimit.cocone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] : cocone F := colimit_cocone.cocone (get_colimit_cocone F) /-- An arbitrary choice of colimit object of a functor. -/ def colimit {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] : C := cocone.X sorry /-- The coprojection from a value of the functor to the colimit object. -/ def colimit.ι {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (j : J) : functor.obj F j ⟶ colimit F := nat_trans.app (cocone.ι (colimit.cocone F)) j @[simp] theorem colimit.cocone_ι {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (j : J) : nat_trans.app (cocone.ι (colimit.cocone F)) j = colimit.ι F j := rfl @[simp] theorem colimit.cocone_X {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] : cocone.X (colimit.cocone F) = colimit F := rfl @[simp] theorem colimit.w {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] {j : J} {j' : J} (f : j ⟶ j') : functor.map F f ≫ colimit.ι F j' = colimit.ι F j := cocone.w (colimit.cocone F) f /-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/ def colimit.is_colimit {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := colimit_cocone.is_colimit (get_colimit_cocone F) /-- The morphism from the colimit object to the cone point of any other cocone. -/ def colimit.desc {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ cocone.X c := is_colimit.desc (colimit.is_colimit F) c @[simp] theorem colimit.is_colimit_desc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (c : cocone F) : is_colimit.desc (colimit.is_colimit F) c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp] theorem colimit.ι_desc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = nat_trans.app (cocone.ι c) j := is_colimit.fac (colimit.is_colimit F) c j /-- Functoriality of colimits. Usually this morphism should be accessed through `colim.map`, but may be needed separately when you have specified colimits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def colim_map {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G := is_colimit.map (colimit.is_colimit F) (colimit.cocone G) α @[simp] theorem ι_colim_map_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) {X' : C} (f' : colimit G ⟶ X') : colimit.ι F j ≫ colim_map α ≫ f' = nat_trans.app α j ≫ colimit.ι G j ≫ f' := sorry /-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/ def colimit.cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (c : cocone F) : colimit.cocone F ⟶ c := is_colimit.desc_cocone_morphism (colimit.is_colimit F) c @[simp] theorem colimit.cocone_morphism_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (c : cocone F) : cocone_morphism.hom (colimit.cocone_morphism c) = colimit.desc F c := rfl theorem colimit.ι_cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ cocone_morphism.hom (colimit.cocone_morphism c) = nat_trans.app (cocone.ι c) j := sorry @[simp] theorem colimit.comp_cocone_point_unique_up_to_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ iso.hom (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) hc) = nat_trans.app (cocone.ι c) j := is_colimit.comp_cocone_point_unique_up_to_iso_hom (colimit.is_colimit F) hc j @[simp] theorem colimit.comp_cocone_point_unique_up_to_iso_inv_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) {X' : C} (f' : cocone.X c ⟶ X') : colimit.ι F j ≫ iso.inv (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit F)) ≫ f' = nat_trans.app (cocone.ι c) j ≫ f' := sorry /-- Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point. -/ def colimit.iso_colimit_cocone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) : colimit F ≅ cocone.X (colimit_cocone.cocone t) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone.is_colimit t) @[simp] theorem colimit.iso_colimit_cocone_ι_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : colimit.ι F j ≫ iso.hom (colimit.iso_colimit_cocone t) = nat_trans.app (cocone.ι (colimit_cocone.cocone t)) j := sorry @[simp] theorem colimit.iso_colimit_cocone_ι_inv_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) {X' : C} (f' : colimit F ⟶ X') : nat_trans.app (cocone.ι (colimit_cocone.cocone t)) j ≫ iso.inv (colimit.iso_colimit_cocone t) ≫ f' = colimit.ι F j ≫ f' := sorry theorem colimit.hom_ext {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] {X : C} {f : colimit F ⟶ X} {f' : colimit F ⟶ X} (w : ∀ (j : J), colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := is_colimit.hom_ext (colimit.is_colimit F) w @[simp] theorem colimit.desc_cocone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] : colimit.desc F (colimit.cocone F) = 𝟙 := is_colimit.desc_self (colimit.is_colimit F) /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ functor.obj (functor.cocones F) W := is_colimit.hom_iso (colimit.is_colimit F) W @[simp] theorem colimit.hom_iso_hom {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : iso.hom (colimit.hom_iso F W) f = cocone.ι (colimit.cocone F) ≫ functor.map (functor.const J) f := is_colimit.hom_iso_hom (colimit.is_colimit F) f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ Subtype fun (p : (j : J) → functor.obj F j ⟶ W) => ∀ {j j' : J} (f : j ⟶ j'), functor.map F f ≫ p j' = p j := is_colimit.hom_iso' (colimit.is_colimit F) W theorem colimit.desc_extend {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : cocone.X c ⟶ X) : colimit.desc F (cocone.extend c f) = colimit.desc F c ≫ f := sorry /-- If `F` has a colimit, so does any naturally isomorphic functor. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. theorem has_colimit_of_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := has_colimit.mk (colimit_cocone.mk (functor.obj (cocones.precompose (iso.hom α)) (colimit.cocone F)) (is_colimit.mk fun (s : cocone G) => colimit.desc F (functor.obj (cocones.precompose (iso.inv α)) s))) /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ theorem has_colimit.of_cocones_iso {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : functor.cocones F ≅ functor.cocones G) [has_colimit F] : has_colimit G := has_colimit.mk (colimit_cocone.mk (is_colimit.of_nat_iso.colimit_cocone (is_colimit.nat_iso (colimit.is_colimit F) ≪≫ h)) (is_colimit.of_nat_iso (is_colimit.nat_iso (colimit.is_colimit F) ≪≫ h))) /-- The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_colimit.iso_of_nat_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w @[simp] theorem has_colimit.iso_of_nat_iso_ι_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) (j : J) : colimit.ι F j ≫ iso.hom (has_colimit.iso_of_nat_iso w) = nat_trans.app (iso.hom w) j ≫ colimit.ι G j := is_colimit.comp_cocone_points_iso_of_nat_iso_hom (colimit.is_colimit F) (colimit.is_colimit G) w j @[simp] theorem has_colimit.iso_of_nat_iso_hom_desc_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} [has_colimit F] [has_colimit G] (t : cocone G) (w : F ≅ G) {X' : C} (f' : cocone.X t ⟶ X') : iso.hom (has_colimit.iso_of_nat_iso w) ≫ colimit.desc G t ≫ f' = colimit.desc F (functor.obj (cocones.precompose (iso.hom w)) t) ≫ f' := sorry /-- The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_colimit.iso_of_equivalence {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w @[simp] theorem has_colimit.iso_of_equivalence_hom_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) (j : J) : colimit.ι F j ≫ iso.hom (has_colimit.iso_of_equivalence e w) = functor.map F (nat_trans.app (equivalence.unit e) j) ≫ nat_trans.app (iso.inv w) (functor.obj (equivalence.functor e ⋙ equivalence.inverse e) j) ≫ colimit.ι G (functor.obj (equivalence.functor e) (functor.obj (equivalence.functor e ⋙ equivalence.inverse e) j)) := sorry @[simp] theorem has_colimit.iso_of_equivalence_inv_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : equivalence.functor e ⋙ G ≅ F) (k : K) : colimit.ι G k ≫ iso.inv (has_colimit.iso_of_equivalence e w) = functor.map G (nat_trans.app (equivalence.counit_inv e) k) ≫ nat_trans.app (iso.hom w) (functor.obj (equivalence.inverse e) k) ≫ colimit.ι F (functor.obj (equivalence.inverse e) k) := sorry /-- The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`. -/ def colimit.pre {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) (cocone.whisker E (colimit.cocone F)) @[simp] theorem colimit.ι_pre_assoc {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] (k : K) {X' : C} (f' : colimit F ⟶ X') : colimit.ι (E ⋙ F) k ≫ colimit.pre F E ≫ f' = colimit.ι F (functor.obj E k) ≫ f' := sorry @[simp] theorem colimit.pre_desc {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (cocone.whisker E c) := sorry @[simp] theorem colimit.pre_pre {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ C) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] {L : Type v} [small_category L] (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := sorry /--- If we have particular colimit cocones available for `E ⋙ F` and for `F`, we obtain a formula for `colimit.pre F E`. -/ theorem colimit.pre_eq {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_colimit F] {E : K ⥤ J} [has_colimit (E ⋙ F)] (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) : colimit.pre F E = iso.hom (colimit.iso_colimit_cocone s) ≫ is_colimit.desc (colimit_cocone.is_colimit s) (cocone.whisker E (colimit_cocone.cocone t)) ≫ iso.inv (colimit.iso_colimit_cocone t) := sorry /-- The canonical morphism from `G` applied to the colimit of `F ⋙ G` to `G` applied to the colimit of `F`. -/ def colimit.post {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] : colimit (F ⋙ G) ⟶ functor.obj G (colimit F) := colimit.desc (F ⋙ G) (functor.map_cocone G (colimit.cocone F)) @[simp] theorem colimit.ι_post_assoc {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] (j : J) {X' : D} (f' : functor.obj G (colimit F) ⟶ X') : colimit.ι (F ⋙ G) j ≫ colimit.post F G ≫ f' = functor.map G (colimit.ι F j) ≫ f' := sorry @[simp] theorem colimit.post_desc {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] (c : cocone F) : colimit.post F G ≫ functor.map G (colimit.desc F c) = colimit.desc (F ⋙ G) (functor.map_cocone G c) := sorry @[simp] theorem colimit.post_post {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] {E : Type u''} [category E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : colimit.post (F ⋙ G) H ≫ functor.map H (colimit.post F G) = colimit.post F (G ⋙ H) := sorry /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ theorem colimit.pre_post {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {D : Type u'} [category D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : colimit.post (E ⋙ F) G ≫ functor.map G (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := sorry /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ protected instance has_colimit_equivalence_comp {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} (e : K ≌ J) [has_colimit F] : has_colimit (equivalence.functor e ⋙ F) := has_colimit.mk (colimit_cocone.mk (cocone.whisker (equivalence.functor e) (colimit.cocone F)) (is_colimit.whisker_equivalence (colimit.is_colimit F) e)) /-- If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`. -/ theorem has_colimit_of_equivalence_comp {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} (e : K ≌ J) [has_colimit (equivalence.functor e ⋙ F)] : has_colimit F := has_colimit_of_iso (iso.symm (equivalence.inv_fun_id_assoc e F)) /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ def colim {J : Type v} [small_category J] {C : Type u} [category C] [has_colimits_of_shape J C] : (J ⥤ C) ⥤ C := functor.mk (fun (F : J ⥤ C) => colimit F) fun (F G : J ⥤ C) (α : F ⟶ G) => colim_map α @[simp] theorem colimit.ι_map_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimits_of_shape J C] {G : J ⥤ C} (α : F ⟶ G) (j : J) {X' : C} (f' : functor.obj colim G ⟶ X') : colimit.ι F j ≫ functor.map colim α ≫ f' = nat_trans.app α j ≫ colimit.ι G j ≫ f' := sorry @[simp] theorem colimit.map_desc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimits_of_shape J C] {G : J ⥤ C} (α : F ⟶ G) (c : cocone G) : functor.map colim α ≫ colimit.desc G c = colimit.desc F (functor.obj (cocones.precompose α) c) := sorry theorem colimit.pre_map {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ C} [has_colimits_of_shape J C] {G : J ⥤ C} (α : F ⟶ G) [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ functor.map colim α = functor.map colim (whisker_left E α) ≫ colimit.pre G E := sorry theorem colimit.pre_map' {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] [has_colimits_of_shape J C] [has_colimits_of_shape K C] (F : J ⥤ C) {E₁ : K ⥤ J} {E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = functor.map colim (whisker_right α F) ≫ colimit.pre F E₂ := sorry theorem colimit.pre_id {J : Type v} [small_category J] {C : Type u} [category C] [has_colimits_of_shape J C] (F : J ⥤ C) : colimit.pre F 𝟭 = functor.map colim (iso.hom (functor.left_unitor F)) := sorry /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs theorem colimit.map_post {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} [has_colimits_of_shape J C] {G : J ⥤ C} (α : F ⟶ G) {D : Type u'} [category D] [has_colimits_of_shape J D] (H : C ⥤ D) : colimit.post F H ≫ functor.map H (functor.map colim α) = functor.map colim (whisker_right α H) ≫ colimit.post G H := sorry H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ /-- The isomorphism between morphisms from the cone point of the colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda {J : Type v} [small_category J] {C : Type u} [category C] [has_colimits_of_shape J C] : functor.op colim ⋙ coyoneda ≅ cocones J C := nat_iso.of_components (fun (F : J ⥤ Cᵒᵖ) => nat_iso.of_components (colimit.hom_iso (opposite.unop F)) sorry) sorry /-- We can transport colimits of shape `J` along an equivalence `J ≌ J'`. -/ theorem has_colimits_of_shape_of_equivalence {J : Type v} [small_category J] {C : Type u} [category C] {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := has_colimits_of_shape.mk fun (F : J' ⥤ C) => has_colimit_of_equivalence_comp e /-- If `t : cone F` is a limit cone, then `t.op : cocone F.op` is a colimit cocone. -/ def is_limit.op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} (P : is_limit t) : is_colimit (cone.op t) := is_colimit.mk fun (s : cocone (functor.op F)) => has_hom.hom.op (is_limit.lift P (cocone.unop s)) /-- If `t : cocone F` is a colimit cocone, then `t.op : cone F.op` is a limit cone. -/ def is_colimit.op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} (P : is_colimit t) : is_limit (cocone.op t) := is_limit.mk fun (s : cone (functor.op F)) => has_hom.hom.op (is_colimit.desc P (cone.unop s)) /-- If `t : cone F.op` is a limit cone, then `t.unop : cocone F` is a colimit cocone. -/ def is_limit.unop {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone (functor.op F)} (P : is_limit t) : is_colimit (cone.unop t) := is_colimit.mk fun (s : cocone F) => has_hom.hom.unop (is_limit.lift P (cocone.op s)) /-- If `t : cocone F.op` is a colimit cocone, then `t.unop : cone F.` is a limit cone. -/ def is_colimit.unop {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone (functor.op F)} (P : is_colimit t) : is_limit (cocone.unop t) := is_limit.mk fun (s : cone F) => has_hom.hom.unop (is_colimit.desc P (cone.op s)) /-- `t : cone F` is a limit cone if and only is `t.op : cocone F.op` is a colimit cocone. -/ def is_limit_equiv_is_colimit_op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cone F} : is_limit t ≃ is_colimit (cone.op t) := equiv_of_subsingleton_of_subsingleton is_limit.op fun (P : is_colimit (cone.op t)) => is_limit.of_iso_limit (is_colimit.unop P) (cones.ext (iso.refl (cone.X (cocone.unop (cone.op t)))) sorry) /-- `t : cocone F` is a colimit cocone if and only is `t.op : cone F.op` is a limit cone. -/ def is_colimit_equiv_is_limit_op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {t : cocone F} : is_colimit t ≃ is_limit (cocone.op t) := equiv_of_subsingleton_of_subsingleton is_colimit.op fun (P : is_limit (cocone.op t)) => is_colimit.of_iso_colimit (is_limit.unop P) (cocones.ext (iso.refl (cocone.X (cone.unop (cocone.op t)))) sorry) end Mathlib
792363af4478f89612b35c196adfa938fbd8d309
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/bitvec/basic.lean
354ec842d1a930fdbac31837ccc39c94d50bcccb
[ "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
3,652
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.bitvec.core import data.fin.basic import tactic.norm_num import tactic.monotonicity namespace bitvec instance (n : ℕ) : preorder (bitvec n) := preorder.lift bitvec.to_nat /-- convert `fin` to `bitvec` -/ def of_fin {n : ℕ} (i : fin $ 2^n) : bitvec n := bitvec.of_nat _ i.val lemma of_fin_val {n : ℕ} (i : fin $ 2^n) : (of_fin i).to_nat = i.val := by rw [of_fin,to_nat_of_nat,nat.mod_eq_of_lt]; apply i.is_lt /-- convert `bitvec` to `fin` -/ def to_fin {n : ℕ} (i : bitvec n) : fin $ 2^n := fin.of_nat' i.to_nat lemma add_lsb_eq_twice_add_one {x b} : add_lsb x b = 2 * x + cond b 1 0 := by simp [add_lsb,two_mul] lemma to_nat_eq_foldr_reverse {n : ℕ} (v : bitvec n) : v.to_nat = v.to_list.reverse.foldr (flip add_lsb) 0 := by rw [list.foldr_reverse, flip]; refl lemma to_nat_lt {n : ℕ} (v : bitvec n) : v.to_nat < 2^n := begin suffices : v.to_nat + 1 ≤ 2 ^ n, { simpa }, rw to_nat_eq_foldr_reverse, cases v with xs h, dsimp [bitvec.to_nat,bits_to_nat], rw ← list.length_reverse at h, generalize_hyp : xs.reverse = ys at ⊢ h, clear xs, induction ys generalizing n, { simp [← h] }, { simp only [←h, pow_add, flip, list.length, list.foldr, pow_one], rw [add_lsb_eq_twice_add_one], transitivity 2 * list.foldr (λ (x : bool) (y : ℕ), add_lsb y x) 0 ys_tl + 2 * 1, { ac_mono, rw two_mul, mono, cases ys_hd; simp }, { rw ← left_distrib, ac_mono, norm_num, apply ys_ih, refl } }, end lemma add_lsb_div_two {x b} : add_lsb x b / 2 = x := by cases b; simp only [nat.add_mul_div_left, add_lsb, ←two_mul, add_comm, nat.succ_pos', nat.mul_div_right, gt_iff_lt, zero_add, cond]; norm_num lemma to_bool_add_lsb_mod_two {x b} : to_bool (add_lsb x b % 2 = 1) = b := by cases b; simp only [to_bool_iff, nat.add_mul_mod_self_left, add_lsb, ←two_mul, add_comm, bool.to_bool_false, nat.mul_mod_right, zero_add, cond, zero_ne_one]; norm_num lemma of_nat_to_nat {n : ℕ} (v : bitvec n) : bitvec.of_nat _ v.to_nat = v := begin cases v with xs h, ext1, change vector.to_list _ = xs, dsimp [bitvec.to_nat,bits_to_nat], rw ← list.length_reverse at h, rw [← list.reverse_reverse xs,list.foldl_reverse], generalize_hyp : xs.reverse = ys at ⊢ h, clear xs, induction ys generalizing n, { cases h, simp [bitvec.of_nat] }, { simp only [←nat.succ_eq_add_one, list.length] at h, subst n, simp only [bitvec.of_nat, vector.to_list_cons, vector.to_list_nil, list.reverse_cons, vector.to_list_append, list.foldr], erw [add_lsb_div_two, to_bool_add_lsb_mod_two], congr, apply ys_ih, refl } end lemma to_fin_val {n : ℕ} (v : bitvec n) : (to_fin v : ℕ) = v.to_nat := by rw [to_fin, fin.coe_of_nat_eq_mod', nat.mod_eq_of_lt]; apply to_nat_lt lemma to_fin_le_to_fin_of_le {n} {v₀ v₁ : bitvec n} (h : v₀ ≤ v₁) : v₀.to_fin ≤ v₁.to_fin := show (v₀.to_fin : ℕ) ≤ v₁.to_fin, by rw [to_fin_val,to_fin_val]; exact h lemma of_fin_le_of_fin_of_le {n : ℕ} {i j : fin (2^n)} (h : i ≤ j) : of_fin i ≤ of_fin j := show (bitvec.of_nat n i).to_nat ≤ (bitvec.of_nat n j).to_nat, by { simp only [to_nat_of_nat, nat.mod_eq_of_lt, fin.is_lt], exact h } lemma to_fin_of_fin {n} (i : fin $ 2^n) : (of_fin i).to_fin = i := fin.eq_of_veq (by simp [to_fin_val, of_fin, to_nat_of_nat, nat.mod_eq_of_lt, i.is_lt]) lemma of_fin_to_fin {n} (v : bitvec n) : of_fin (to_fin v) = v := by dsimp [of_fin]; rw [to_fin_val, of_nat_to_nat] end bitvec
2fafb771744de8dfab48ad789df0fddd2d1c0bac
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_36.lean
0debe9d82e9f5771e407e9217e7f575ab0928442
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
137
lean
import data.real.basic -- BEGIN #check ∀ x y ε : ℝ, 0 < ε → ε ≤ 1 → abs x < ε → abs y < ε → abs (x * y) < ε -- END
b3d3c77c95accba7fe4f5c7624295dcd39db8069
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/filter/cofinite.lean
5d48989dd924b2c83eac4b26f63c373a985a4c70
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,069
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, Jeremy Avigad, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.filter.at_top_bot import Mathlib.PostPort universes u_1 namespace Mathlib /-! # The cofinite filter In this file we define `cofinite`: the filter of sets with finite complement and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`. ## TODO Define filters for other cardinalities of the complement. -/ namespace filter /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite {α : Type u_1} : filter α := mk (set_of fun (s : set α) => set.finite (sᶜ)) sorry sorry sorry @[simp] theorem mem_cofinite {α : Type u_1} {s : set α} : s ∈ cofinite ↔ set.finite (sᶜ) := iff.rfl @[simp] theorem eventually_cofinite {α : Type u_1} {p : α → Prop} : filter.eventually (fun (x : α) => p x) cofinite ↔ set.finite (set_of fun (x : α) => ¬p x) := iff.rfl protected instance cofinite_ne_bot {α : Type u_1} [infinite α] : ne_bot cofinite := mt (iff.mpr empty_in_sets_eq_bot) (eq.mpr (id ((fun (a a_1 : Prop) (e_1 : a = a_1) => congr_arg Not e_1) (∅ ∈ cofinite) (set.finite set.univ) (Eq.trans (propext mem_cofinite) ((fun (s s_1 : set α) (e_1 : s = s_1) => congr_arg set.finite e_1) (∅ᶜ) set.univ set.compl_empty)))) set.infinite_univ) theorem frequently_cofinite_iff_infinite {α : Type u_1} {p : α → Prop} : filter.frequently (fun (x : α) => p x) cofinite ↔ set.infinite (set_of fun (x : α) => p x) := sorry end filter theorem set.finite.compl_mem_cofinite {α : Type u_1} {s : set α} (hs : set.finite s) : sᶜ ∈ filter.cofinite := iff.mpr filter.mem_cofinite (Eq.symm (compl_compl s) ▸ hs) theorem set.finite.eventually_cofinite_nmem {α : Type u_1} {s : set α} (hs : set.finite s) : filter.eventually (fun (x : α) => ¬x ∈ s) filter.cofinite := set.finite.compl_mem_cofinite hs theorem finset.eventually_cofinite_nmem {α : Type u_1} (s : finset α) : filter.eventually (fun (x : α) => ¬x ∈ s) filter.cofinite := set.finite.eventually_cofinite_nmem (finset.finite_to_set s) theorem set.infinite_iff_frequently_cofinite {α : Type u_1} {s : set α} : set.infinite s ↔ filter.frequently (fun (x : α) => x ∈ s) filter.cofinite := iff.symm filter.frequently_cofinite_iff_infinite theorem filter.eventually_cofinite_ne {α : Type u_1} (x : α) : filter.eventually (fun (a : α) => a ≠ x) filter.cofinite := set.finite.eventually_cofinite_nmem (set.finite_singleton x) /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ theorem nat.cofinite_eq_at_top : filter.cofinite = filter.at_top := sorry theorem nat.frequently_at_top_iff_infinite {p : ℕ → Prop} : filter.frequently (fun (n : ℕ) => p n) filter.at_top ↔ set.infinite (set_of fun (n : ℕ) => p n) := sorry
435e1d3182a42d6ee670d2184df8dedc3d657edf
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/opaque_hint_bug.lean
3c60c133e89e4c594ac53a80d4a3cae8ff7d2d26
[ "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
236
lean
inductive List (T : Type) : Type | nil {} : List | cons : T → List → List section variable {T : Type} definition concat (s t : List T) : List T := List.rec t (fun x l u, List.cons x u) s attribute concat [reducible] end
2fd7b28441059586f955f44c2b64d11cafde9aca
b794ca1df49bc5a3bd3fd5552eed3bc4f63b8b93
/src/mywork/practice_1.lean
42045c8f59f0e44062770a378143e9f5e07ad6db
[]
no_license
akraisinger/cs2120f21
8235ac98375e04ffcec504cff5cab7833ee69e54
4ef83d7151bb6a284028092aa4f1d509c0eb8237
refs/heads/main
1,691,714,771,612
1,632,889,465,000
1,632,889,465,000
399,946,508
0
0
null
null
null
null
UTF-8
Lean
false
false
6,204
lean
/- EQUALITY (due before class WED! (9/15/2021)) -/ /- #1 Suppose that x, y, z, and w are arbitrary objects of some type, T; and suppose further that we know (have proofs of the facts) that x = y, y = z, and w = z. Give a very, very short English proof of the conjecture that z = w. You can use not only the axioms of equality, but either of the theorems about properties of equality that we have proven. Hint: There's something about this question that makes it much easier to answer than it might at first appear. -/ /- The conjecture z = w is true via the symmetric property of equality. -/ /- #2 Give a formal statement of the conjecture (proposition) from #1 by filling in the "hole" in the following definition. The def is a keyword. The name you're binding to your proposition is prop_1. The type of the value is Prop (which is the type of all propositions in Lean). -/ def prop_1 : Prop := ∀ (T : Type) (x y z w : T), w = z → z = w /- #3 (extra credit) Give a formal proof of the proposition from #2 by filling in the hole in this next definition. Hint: Use Lean's versions of the axioms and basic theorems concerning equality. They are, again, called eq.refl, eq.subst, eq.symm, eq.trans. -/ theorem prop_1_proof : prop_1 := begin assume T w z, assume h1 h2, apply eq.symm, end /- FOR ALL: ∀. -/ /- #4 Give a very brief explanation in English of the introduction rule for ∀. For example, suppose you need to prove (∀ x, P x); what do you do? (I'm being a little informal in leaving out the type of X.) -/ /- When dealing with ∀ statements, you must make an assumption that if you are able to prove it true for an abitrary object of that type, then it is true for all objects of that nature. -/ /- #5 Suppose you have a proof, let's call it pf, of the proposition, (∀ x, P x), and you need a proof of P t, for some particular t. Write an expression then uses the elimination rule for ∀ to get such a proof. Complete the answer by replacing the underscores in the following expression: (∀ t, P t). -/ /- IMPLIES: → In the "code" that follows, we define two predicates, each taking one natural number as an argument. We call them ev and odd. When applied to any value, n, ev yields the proposition that n is even (n % 2 = 0), while odd yields the proposition that n is odd (n % 2 = 1). -/ def ev (n : ℕ) := n % 2 = 0 def odd (n : ℕ) := n % 2 = 1 /- #6 Write a formal version of the proposition that, for *any* natural number n, *if* n is even, *then* n + 1 is odd. Give your answer by filling the hole in the following definition. Hint: put parenthesis around "n + 1" in your answer. -/ def successor_of_even_is_odd : Prop := ∀ (n : ℕ), ev n → odd (n + 1) /- #7 Suppose that "its_raining" and "the_streets_are_wet" are propositions. (We formalize these assumptions as axioms in what follows. Then give a formal definition of the (larger) proposition, "if it's raining out then the streets are wet") by filling in the hole -/ axioms (raining streets_wet : Prop) axiom if_raining_then_streets_wet : raining → streets_wet /- #9 Now suppose that in addition, its_raining is true, and we have a proof of it, pf_its_raining. Again, we again give you this assumption formally as an axiom below. Finish the formal proof that the streets must be wet. Hint: here you are asked to use the elimination rule for →. -/ axiom pf_raining : raining example : streets_wet := begin apply if_raining_then_streets_wet, apply pf_raining, end /- AND: ∧ -/ /- #10 In our last class, we proved that "∧ is *commutative*." That is, for any given *propositions*, P and Q, (P ∧ Q) → (Q ∧ P). The way we proved it was to *assume* that we're given such a P, Q, and proof, pq, of (P ∧ Q) -- applying the introduction rules for ∀ and →). In this context, we *use* the proof, pq, to derive separate proofs, let's call them p, a proof of P, and q, a proof of Q. With these in hand, we then apply the introduction rule for ∧ to put them back together into a proof of (Q ∧ P). We give you a formal version of this proof as a reminder, next. -/ theorem and_commutative : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := begin assume P Q pq, apply and.intro _ _, exact (and.elim_right pq), exact (and.elim_left pq), end /- Your task now is to prove the theorem, "∧ is *associative*." What this means is that for arbitrary propositions, P, Q, and R, if (P ∧ (Q ∧ R)) is true, then ((P ∧ Q) ∧ R) is true, *and vice versa*. You just need to prove it in the first direction. Hint, if you have a proof, p_qr, of (P ∧ (Q ∧ R)), then the application of and.elim_left will give you a proof of P, and and.elim_right will give you a proof of (Q ∧ R). To help you along, we give you the first part of the proof, including an example of a new Lean tactic called have, which allows you to give a name to a new value in the middle of a proof script. -/ theorem and_associative : ∀ (P Q R : Prop), (P ∧ (Q ∧ R)) → ((P ∧ Q) ∧ R) := begin intros P Q R h, have p : P := and.elim_left h, have qr := and.elim_right h, apply and.intro, apply and.intro, exact p, exact and.elim_left qr, exact and.elim_right qr, end /- #11 Give an English language proof of the preceding theorem. Do it by finishing off the following partial "proof explanation." Proof. We assume that P, Q, and R are arbitrary but specific propositions, and that we have a proof, let's call it p_qr, of (P ∧ (Q ∧ R)) [by application of ∧ and → introduction.] What now remains to be proved is ((P ∧ Q) ∧ R). We can construct a proof of this proposition by applying _introduction rule of and_ to a proof of (P ∧ Q) and a proof of R. What remains, then, is to obtain these proofs. But this is easily done by the application of _the elimination rule of and_ to _P ∧ Q ∧ R_. QED. -/ /- Note that Lean includes versions of these theorems (and many, many, many others) in its extensive library of formalized maths, as the following check commands reveal. Note the difference in naming relative to the definitions we give in this file. -/ #check @and.comm #check @and.assoc
0876925fb3bce8aba28a07d905b8280389405e6c
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/mv_polynomial/comm_ring.lean
1133761292e2b80a1304ae20ff18e68610fcf0b8
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
5,008
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.variables /-! # Multivariate polynomials over a ring Many results about polynomials hold when the coefficient ring is a commutative semiring. Some stronger results can be derived when we assume this semiring is a ring. This file does not define any new operations, but proves some of these stronger results. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_ring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_ring variable [comm_ring R] variables {p q : mv_polynomial σ R} instance : comm_ring (mv_polynomial σ R) := add_monoid_algebra.comm_ring variables (σ a a') @[simp] lemma C_sub : (C (a - a') : mv_polynomial σ R) = C a - C a' := ring_hom.map_sub _ _ _ @[simp] lemma C_neg : (C (-a) : mv_polynomial σ R) = -C a := ring_hom.map_neg _ _ @[simp] lemma coeff_neg (m : σ →₀ ℕ) (p : mv_polynomial σ R) : coeff m (-p) = -coeff m p := finsupp.neg_apply _ _ @[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply _ _ _ @[simp] lemma monomial_neg (m : σ →₀ ℕ) (a : R) : -(monomial m a) = monomial m (-a) := single_neg.symm @[simp] lemma monomial_sub (m : σ →₀ ℕ) (a b : R) : monomial m a - monomial m b = monomial m (a - b) := single_sub.symm @[simp] lemma support_neg : (- p).support = p.support := finsupp.support_neg variables {σ} (p) section degrees lemma degrees_neg (p : mv_polynomial σ R) : (- p).degrees = p.degrees := by rw [degrees, support_neg]; refl lemma degrees_sub (p q : mv_polynomial σ R) : (p - q).degrees ≤ p.degrees ⊔ q.degrees := by simpa only [sub_eq_add_neg] using le_trans (degrees_add p (-q)) (by rw degrees_neg) end degrees section vars variables (p q) @[simp] lemma vars_neg : (-p).vars = p.vars := by simp [vars, degrees_neg] lemma vars_sub_subset : (p - q).vars ⊆ p.vars ∪ q.vars := by convert vars_add_subset p (-q) using 2; simp [sub_eq_add_neg] variables {p q} @[simp] lemma vars_sub_of_disjoint (hpq : disjoint p.vars q.vars) : (p - q).vars = p.vars ∪ q.vars := begin rw ←vars_neg q at hpq, convert vars_add_of_disjoint hpq using 2; simp [sub_eq_add_neg] end end vars section eval₂ variables [comm_ring S] variables (f : R →+* S) (g : σ → S) @[simp] lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := (eval₂_hom f g).map_sub _ _ @[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := (eval₂_hom f g).map_neg _ lemma hom_C (f : mv_polynomial σ ℤ →+* S) (n : ℤ) : f (C n) = (n : S) := (f.comp C).eq_int_cast n /-- A ring homomorphism f : Z[X_1, X_2, ...] → R is determined by the evaluations f(X_1), f(X_2), ... -/ @[simp] lemma eval₂_hom_X {R : Type u} (c : ℤ →+* S) (f : mv_polynomial R ℤ →+* S) (x : mv_polynomial R ℤ) : eval₂ c (f ∘ X) x = f x := mv_polynomial.induction_on x (λ n, by { rw [hom_C f, eval₂_C], exact c.eq_int_cast n }) (λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (f.map_add _ _).symm }) (λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (f.map_mul _ _).symm }) /-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as functions out of the type `σ`, -/ def hom_equiv : (mv_polynomial σ ℤ →+* S) ≃ (σ → S) := { to_fun := λ f, ⇑f ∘ X, inv_fun := λ f, eval₂_hom (int.cast_ring_hom S) f, left_inv := λ f, ring_hom.ext $ eval₂_hom_X _ _, right_inv := λ f, funext $ λ x, by simp only [coe_eval₂_hom, function.comp_app, eval₂_X] } end eval₂ section total_degree @[simp] lemma total_degree_neg (a : mv_polynomial σ R) : (-a).total_degree = a.total_degree := by simp only [total_degree, support_neg] lemma total_degree_sub (a b : mv_polynomial σ R) : (a - b).total_degree ≤ max a.total_degree b.total_degree := calc (a - b).total_degree = (a + -b).total_degree : by rw sub_eq_add_neg ... ≤ max a.total_degree (-b).total_degree : total_degree_add a (-b) ... = max a.total_degree b.total_degree : by rw total_degree_neg end total_degree end comm_ring end mv_polynomial
e38562cca0f1bff2728e5f8d34a081a76e4c59a3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_geometry/limits.lean
21a2b67b861308832ea10473751697b1fc746a7a
[ "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
4,637
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 algebraic_geometry.pullbacks import algebraic_geometry.AffineScheme import category_theory.limits.constructions.finite_products_of_binary_products import category_theory.limits.constructions.equalizers /-! # (Co)Limits of Schemes We construct various limits and colimits in the category of schemes. * The existence of fibred products was shown in `algebraic_geometry/pullbacks.lean`. * `Spec ℤ` is the terminal object. * The preceding two results imply that `Scheme` has all finite limits. * The empty scheme is the (strict) initial object. ## Todo * Coproducts exists (and the forgetful functors preserve them). -/ universe u open category_theory category_theory.limits opposite topological_space namespace algebraic_geometry /-- `Spec ℤ` is the terminal object in the category of schemes. -/ noncomputable def Spec_Z_is_terminal : is_terminal (Scheme.Spec.obj (op $ CommRing.of ℤ)) := @@is_terminal.is_terminal_obj _ _ Scheme.Spec _ infer_instance (terminal_op_of_initial CommRing.Z_is_initial) instance : has_terminal Scheme := has_terminal_of_has_terminal_of_preserves_limit Scheme.Spec instance : is_affine (⊤_ Scheme.{u}) := is_affine_of_iso (preserves_terminal.iso Scheme.Spec).inv instance : has_finite_limits Scheme := has_finite_limits_of_has_terminal_and_pullbacks section initial /-- The map from the empty scheme. -/ @[simps] def Scheme.empty_to (X : Scheme.{u}) : ∅ ⟶ X := ⟨{ base := ⟨λ x, pempty.elim x, by continuity⟩, c := { app := λ U, CommRing.punit_is_terminal.from _ } }, λ x, pempty.elim x⟩ @[ext] lemma Scheme.empty_ext {X : Scheme.{u}} (f g : ∅ ⟶ X) : f = g := by { ext a, exact pempty.elim a } lemma Scheme.eq_empty_to {X : Scheme.{u}} (f : ∅ ⟶ X) : f = Scheme.empty_to X := Scheme.empty_ext f (Scheme.empty_to X) instance (X : Scheme.{u}) : unique (∅ ⟶ X) := ⟨⟨Scheme.empty_to _⟩, λ _, Scheme.empty_ext _ _⟩ /-- The empty scheme is the initial object in the category of schemes. -/ def empty_is_initial : is_initial (∅ : Scheme.{u}) := is_initial.of_unique _ @[simp] lemma empty_is_initial_to : empty_is_initial.to = Scheme.empty_to := rfl instance : is_empty Scheme.empty.carrier := show is_empty pempty, by apply_instance instance Spec_punit_is_empty : is_empty (Scheme.Spec.obj (op $ CommRing.of punit)).carrier := ⟨prime_spectrum.punit⟩ @[priority 100] instance is_open_immersion_of_is_empty {X Y : Scheme} (f : X ⟶ Y) [is_empty X.carrier] : is_open_immersion f := begin apply_with is_open_immersion.of_stalk_iso { instances := ff }, { apply open_embedding_of_continuous_injective_open, { continuity }, { rintro (i : X.carrier), exact is_empty_elim i }, { intros U hU, convert is_open_empty, ext, apply (iff_false _).mpr, exact λ x, is_empty_elim (show X.carrier, from x.some) } }, { rintro (i : X.carrier), exact is_empty_elim i } end @[priority 100] instance is_iso_of_is_empty {X Y : Scheme} (f : X ⟶ Y) [is_empty Y.carrier] : is_iso f := begin haveI : is_empty X.carrier := ⟨λ x, is_empty_elim (show Y.carrier, from f.1.base x)⟩, haveI : epi f.1.base, { rw Top.epi_iff_surjective, rintro (x : Y.carrier), exact is_empty_elim x }, apply is_open_immersion.to_iso end /-- A scheme is initial if its underlying space is empty . -/ noncomputable def is_initial_of_is_empty {X : Scheme} [is_empty X.carrier] : is_initial X := empty_is_initial.of_iso (as_iso $ empty_is_initial.to _) /-- `Spec 0` is the initial object in the category of schemes. -/ noncomputable def Spec_punit_is_initial : is_initial (Scheme.Spec.obj (op $ CommRing.of punit)) := empty_is_initial.of_iso (as_iso $ empty_is_initial.to _) @[priority 100] instance is_affine_of_is_empty {X : Scheme} [is_empty X.carrier] : is_affine X := is_affine_of_iso (inv (empty_is_initial.to X) ≫ empty_is_initial.to (Scheme.Spec.obj (op $ CommRing.of punit))) instance : has_initial Scheme := has_initial_of_unique Scheme.empty instance initial_is_empty : is_empty (⊥_ Scheme).carrier := ⟨λ x, ((initial.to Scheme.empty : _).1.base x).elim⟩ lemma bot_is_affine_open (X : Scheme) : is_affine_open (⊥ : opens X.carrier) := begin convert range_is_affine_open_of_open_immersion (initial.to X), ext, exact (false_iff _).mpr (λ x, is_empty_elim (show (⊥_ Scheme).carrier, from x.some)), end instance : has_strict_initial_objects Scheme := has_strict_initial_objects_of_initial_is_strict (λ A f, by apply_instance) end initial end algebraic_geometry
56dad3a3ead3ced901ed20044ba580cecac6d5db
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world7/level7.lean
fda5f1338c260c49a6600ce5ed5ddc02b1ed5759
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
768
lean
import game.world7.level6 -- hide /- # Advanced proposition world. ## Level 7: `or_symm` Proving that $(P\lor Q)\implies(Q\lor P)$ involves an element of danger. `intro h,` is the obvious start. But now, even though the goal is an `∨` statement, both `left` and `right` put you in a situation with an impossible goal. Fortunately, after `intro h,` you can do `cases h with p q`. Then something new happens: because there are two ways to prove `P ∨ Q` (namely, proving `P` or proving `Q`), the `cases` tactic turns one goal into two, one for each case. You should be able to make it home from there. -/ /- Lemma If $P$ and $Q$ are true/false statements, then $$P\lor Q\implies Q\lor P.$$ -/ lemma or_symm (P Q : Prop) : P ∨ Q → Q ∨ P := begin end
f40d45bda9c68383d342013915ba173faa14c8ea
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/set/disjointed.lean
c03ae4e53216f89caeecf810dacc5643ff3428cc
[ "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
3,426
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 Disjointed sets -/ import data.set.lattice data.nat.basic tactic.wlog open set classical lattice local attribute [instance] prop_decidable universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {s t u : set α} /-- A relation `p` holds pairwise if `p i j` for all `i ≠ j`. -/ def pairwise {α : Type*} (p : α → α → Prop) := ∀i j, i ≠ j → p i j theorem pairwise_on_bool {r} (hr : symmetric r) {a b : α} : pairwise (r on (λ c, cond c a b)) ↔ r a b := by simp [pairwise, bool.forall_bool, function.on_fun]; exact and_iff_right_of_imp (@hr _ _) theorem pairwise_disjoint_on_bool [semilattice_inf_bot α] {a b : α} : pairwise (disjoint on (λ c, cond c a b)) ↔ disjoint a b := pairwise_on_bool $ λ _ _, disjoint.symm namespace set /-- If `f : ℕ → set α` is a sequence of sets, then `disjointed f` is the sequence formed with each set subtracted from the later ones in the sequence, to form a disjoint sequence. -/ def disjointed (f : ℕ → set α) (n : ℕ) : set α := f n ∩ (⋂i<n, - f i) lemma disjoint_disjointed {f : ℕ → set α} : pairwise (disjoint on disjointed f) := λ i j h, begin wlog h' : i ≤ j; [skip, {revert a, exact (this h.symm).symm}], rintro a ⟨⟨h₁, _⟩, h₂, h₃⟩, simp at h₃, exact h₃ _ (lt_of_le_of_ne h' h) h₁ end lemma Union_lt_succ {f : ℕ → set α} {n} : (⋃i < nat.succ n, f i) = f n ∪ (⋃i < n, f i) := ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, or_comm] lemma Inter_lt_succ {f : ℕ → set α} {n} : (⋂i < nat.succ n, f i) = f n ∩ (⋂i < n, f i) := ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_imp_distrib, forall_and_distrib, and_comm] lemma Union_disjointed {f : ℕ → set α} : (⋃n, disjointed f n) = (⋃n, f n) := subset.antisymm (Union_subset_Union $ assume i, inter_subset_left _ _) $ assume x h, have ∃n, x ∈ f n, from mem_Union.mp h, have hn : ∀ (i : ℕ), i < nat.find this → x ∉ f i, from assume i, nat.find_min this, mem_Union.mpr ⟨nat.find this, nat.find_spec this, by simp; assumption⟩ lemma disjointed_induct {f : ℕ → set α} {n : ℕ} {p : set α → Prop} (h₁ : p (f n)) (h₂ : ∀t i, p t → p (t \ f i)) : p (disjointed f n) := begin rw disjointed, generalize_hyp : f n = t at h₁ ⊢, induction n, case nat.zero { simp [nat.not_lt_zero, h₁] }, case nat.succ : n ih { rw [Inter_lt_succ, inter_comm (-f n), ← inter_assoc], exact h₂ _ n ih } end lemma disjointed_of_mono {f : ℕ → set α} {n : ℕ} (hf : monotone f) : disjointed f (n + 1) = f (n + 1) \ f n := have (⋂i (h : i < n + 1), -f i) = - f n, from le_antisymm (infi_le_of_le n $ infi_le_of_le (nat.lt_succ_self _) $ subset.refl _) (le_infi $ assume i, le_infi $ assume hi, neg_le_neg $ hf $ nat.le_of_succ_le_succ hi), by simp [disjointed, this, diff_eq] lemma Union_disjointed_of_mono {f : ℕ → set α} (hf : monotone f) : ∀ n : ℕ, (⋃i<n.succ, disjointed f i) = f n | 0 := by rw [Union_lt_succ]; simp [disjointed, nat.not_lt_zero] | (n+1) := by rw [Union_lt_succ, disjointed_of_mono hf, Union_disjointed_of_mono n, diff_union_self, union_eq_self_of_subset_right (hf (nat.le_succ _))] end set
5bbfcd0b0edd02260d062190300aeed1e2d1c13d
33340b3a23ca62ef3c8a7f6a2d4e14c07c6d3354
/lia/remove_neg.lean
c89530dbb3cc55bad38d5512d5e2e575d62551b3
[]
no_license
lclem/cooper
79554e72ced343c64fed24b2d892d24bf9447dfe
812afc6b158821f2e7dac9c91d3b6123c7a19faf
refs/heads/master
1,607,554,257,488
1,578,694,133,000
1,578,694,133,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,579
lean
import .wf open list def remove_neg : atom → atom | (atom.le i ks) := atom.le (1 - i) (map_neg ks) | (atom.dvd d i ks) := atom.ndvd d i ks | (atom.ndvd d i ks) := atom.dvd d i ks meta def neg_prsv_normal_aux := `[unfold remove_neg at hb, rewrite (eq_of_mem_singleton hb), trivial] lemma wf_remove_neg : ∀ {a : atom}, a.wf → (remove_neg a).wf | (atom.le i ks) h := begin simp [remove_neg] end | (atom.dvd d i ks) h := begin simp [remove_neg], apply h end | (atom.ndvd d i ks) h := begin simp [remove_neg], apply h end lemma eval_remove_neg : ∀ (a : atom) (xs : list znum), (remove_neg a).eval xs ↔ (¬ (a.eval xs)) | (atom.le i ks) xs := begin simp only [remove_neg, atom.eval], apply calc (1 - i ≤ znum.dot_prod (map_neg ks) xs) ↔ (-(znum.dot_prod (map_neg ks) xs) ≤ -(1 - i)) : begin apply iff.intro, apply (@neg_le_neg znum _), apply (@le_of_neg_le_neg znum _) end ... ↔ (znum.dot_prod ks xs ≤ -(1 - i)) : begin rw [znum.map_neg_dot_prod], simp, end ... ↔ (znum.dot_prod ks xs ≤ i - 1) : by rewrite neg_sub ... ↔ (znum.dot_prod ks xs < i) : begin apply iff.intro, apply znum.lt_of_le_sub_one, apply znum.le_sub_one_of_lt end ... ↔ ¬i ≤ znum.dot_prod ks xs : begin apply iff.intro, apply not_le_of_gt, apply lt_of_not_ge end end | (atom.dvd d i ks) xs := by refl | (atom.ndvd d i ks) xs := by apply not_not_iff.symm
977542362009c204fd17de3a069387e009b9bb2b
618003631150032a5676f229d13a079ac875ff77
/src/algebra/ring.lean
4a7a27b85ba786c5d9a0f920d86d8cca359938a0
[ "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
37,105
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, Floris van Doorn, Amelia Livingston -/ import algebra.group.hom import algebra.group.units import tactic.norm_cast import tactic.split_ifs /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines homomorphisms of semirings and rings, both unbundled (e.g. `is_semiring_hom f`) and bundled (e.g. `ring_hom a β`, a.k.a. `α →+* β`). The unbundled ones are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions is_semiring_hom (deprecated), is_ring_hom (deprecated), ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. Throughout the section on `ring_hom` implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `ring_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags is_ring_hom, is_semiring_hom, ring_hom, semiring_hom, semiring, comm_semiring, ring, comm_ring, domain, integral_domain, nonzero, units -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are division-free." @[protect_proj, ancestor has_mul has_add] class distrib (α : Type u) extends has_mul α, has_add α := (left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib α] (a b c : α) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c def mul_add := @left_distrib lemma right_distrib [distrib α] (a b c : α) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c def add_mul := @right_distrib @[protect_proj, ancestor has_mul has_zero] class mul_zero_class (α : Type u) extends has_mul α, has_zero α := (zero_mul : ∀ a : α, 0 * a = 0) (mul_zero : ∀ a : α, a * 0 = 0) @[ematch, simp] lemma zero_mul [mul_zero_class α] (a : α) : 0 * a = 0 := mul_zero_class.zero_mul a @[ematch, simp] lemma mul_zero [mul_zero_class α] (a : α) : a * 0 = 0 := mul_zero_class.mul_zero a /-- Predicate typeclass for expressing that a (semi)ring or similar algebraic structure is nonzero. -/ @[protect_proj] class nonzero (α : Type u) [has_zero α] [has_one α] : Prop := (zero_ne_one : 0 ≠ (1:α)) @[simp] lemma zero_ne_one [has_zero α] [has_one α] [nonzero α] : 0 ≠ (1:α) := nonzero.zero_ne_one @[simp] lemma one_ne_zero [has_zero α] [has_one α] [nonzero α] : (1:α) ≠ 0 := zero_ne_one.symm /- semiring -/ @[protect_proj, ancestor add_comm_monoid monoid distrib mul_zero_class] class semiring (α : Type u) extends add_comm_monoid α, monoid α, distrib α, mul_zero_class α section semiring variables [semiring α] lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma ne_zero_of_mul_ne_zero_right {a b : α} (h : a * b ≠ 0) : a ≠ 0 := assume : a = 0, have a * b = 0, by rw [this, zero_mul], h this lemma ne_zero_of_mul_ne_zero_left {a b : α} (h : a * b ≠ 0) : b ≠ 0 := assume : b = 0, have a * b = 0, by rw [this, mul_zero], h this lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `s.sum (λ x, f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp variable (α) /-- Either zero and one are nonequal in a semiring, or the semiring is the zero ring. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) := by haveI := classical.dec; refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm /-- If zero equals one in a semiring, the semiring is the zero ring. -/ lemma eq_zero_of_zero_eq_one (h : (0 : α) = 1) : (∀a:α, a = 0) := (zero_ne_one_or_forall_eq_0 α).neg_resolve_left h /-- If zero equals one in a semiring, all elements of that semiring are equal. -/ theorem subsingleton_of_zero_eq_one (h : (0 : α) = 1) : subsingleton α := ⟨λa b, by rw [eq_zero_of_zero_eq_one α h a, eq_zero_of_zero_eq_one α h b]⟩ end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : (mul_right r : R → R) a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := ring_hom @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp, norm_cast] lemma coe_add_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →+ β) = f := rfl namespace ring_hom variables [rα : semiring α] [rβ : semiring β] section include rα rβ @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl variables (f : α →+* β) {x y : α} {rα rβ} theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ theorem coe_add_monoid_hom_inj : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, coe_inj $ show ((f : α →+ β) : α → β) = (g : α →+ β), from congr_arg coe_fn h theorem coe_monoid_hom_inj : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, coe_inj $ show ((f : α →* β) : α → β) = (g : α →* β), from congr_arg coe_fn h /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} instance comm_semiring_has_dvd : has_dvd α := has_dvd.mk (λ a b, ∃ c, b = a * c) -- TODO: this used to not have c explicit, but that seems to be important -- for use with tactics, similar to exist.intro theorem dvd.intro (c : α) (h : a * c = b) : a ∣ b := exists.intro c h^.symm def dvd_of_mul_right_eq := @dvd.intro theorem dvd.intro_left (c : α) (h : c * a = b) : a ∣ b := dvd.intro _ (begin rewrite mul_comm at h, apply h end) def dvd_of_mul_left_eq := @dvd.intro_left theorem exists_eq_mul_right_of_dvd (h : a ∣ b) : ∃ c, b = a * c := h theorem dvd.elim {P : Prop} {a b : α} (H₁ : a ∣ b) (H₂ : ∀ c, b = a * c → P) : P := exists.elim H₁ H₂ theorem exists_eq_mul_left_of_dvd (h : a ∣ b) : ∃ c, b = c * a := dvd.elim h (assume c, assume H1 : b = a * c, exists.intro c (eq.trans H1 (mul_comm a c))) theorem dvd.elim_left {P : Prop} (h₁ : a ∣ b) (h₂ : ∀ c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd h₁) (assume c, assume h₃ : b = c * a, h₂ c h₃) @[refl, simp] theorem dvd_refl (a : α) : a ∣ a := dvd.intro 1 (by simp) local attribute [simp] mul_assoc mul_comm mul_left_comm @[trans] theorem dvd_trans (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄]⟩ end def dvd.trans := @dvd_trans theorem eq_zero_of_zero_dvd (h : 0 ∣ a) : a = 0 := dvd.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (zero_mul c)) /-- Given an element a of a commutative semiring, there exists another element whose product with zero equals a iff a equals zero. -/ @[simp] lemma zero_dvd_iff : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, λ h, by rw h⟩ @[simp] theorem dvd_zero (a : α) : a ∣ 0 := dvd.intro 0 (by simp) @[simp] theorem one_dvd (a : α) : 1 ∣ a := dvd.intro a (by simp) @[simp] theorem dvd_mul_right (a b : α) : a ∣ a * b := dvd.intro b rfl @[simp] theorem dvd_mul_left (a b : α) : a ∣ b * a := dvd.intro b (by simp) theorem dvd_mul_of_dvd_left (h : a ∣ b) (c : α) : a ∣ b * c := dvd.elim h (λ d h', begin rw [h', mul_assoc], apply dvd_mul_right end) theorem dvd_mul_of_dvd_right (h : a ∣ b) (c : α) : a ∣ c * b := begin rw mul_comm, exact dvd_mul_of_dvd_left h _ end theorem mul_dvd_mul : ∀ {a b c d : α}, a ∣ b → c ∣ d → a * c ∣ b * d | a ._ c ._ ⟨e, rfl⟩ ⟨f, rfl⟩ := ⟨e * f, by simp⟩ theorem mul_dvd_mul_left (a : α) {b c : α} (h : b ∣ c) : a * b ∣ a * c := mul_dvd_mul (dvd_refl a) h theorem mul_dvd_mul_right (h : a ∣ b) (c : α) : a * c ∣ b * c := mul_dvd_mul h (dvd_refl c) theorem dvd_add (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) theorem dvd_of_mul_right_dvd (h : a * b ∣ c) : a ∣ c := dvd.elim h (begin intros d h₁, rw [h₁, mul_assoc], apply dvd_mul_right end) theorem dvd_of_mul_left_dvd (h : a * b ∣ c) : b ∣ c := dvd.elim h (λ d ceq, dvd.intro (a * d) (by simp [ceq])) lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /- ring -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} lemma ring.mul_zero (a : α) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rw left_distrib, show a * 0 = 0, from (add_left_cancel this).symm lemma ring.zero_mul (a : α) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add_left_cancel this).symm instance ring.to_semiring : semiring α := { mul_zero := ring.mul_zero, zero_mul := ring.zero_mul, ..‹ring α› } /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ attribute [instance, priority 200] ring.to_semiring lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp [sub_eq_add_neg] def mul_sub := @mul_sub_left_distrib lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp [sub_eq_add_neg] def sub_mul := @mul_sub_right_distrib /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end /-- If the product of two elements of a ring is nonzero, both elements are nonzero. -/ theorem ne_zero_and_ne_zero_of_mul_ne_zero (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, { intro ha, apply h, simp [ha] }, { intro hb, apply h, simp [hb] } end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [ring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} local attribute [simp] add_assoc add_comm add_left_comm mul_comm lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := begin simp [right_distrib, left_distrib, sub_eq_add_neg] end lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := begin simp [right_distrib, left_distrib, sub_eq_add_neg], rw [add_left_comm, add_comm (-a), add_left_comm a], simp end lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [right_distrib, left_distrib] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := dvd_add h₁ (dvd_neg_of_dvd h₂) theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end end comm_ring lemma succ_ne_self [ring α] [nonzero α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nonzero α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_inj ((add_right_inj a).mp (by { convert h, simp }))) /-- An element of the unit group of a nonzero semiring represented as an element of the semiring is nonzero. -/ lemma units.coe_ne_zero [semiring α] [nonzero α] (u : units α) : (u : α) ≠ 0 := λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3 /-- Proves that a semiring that contains at least two distinct elements is nonzero. -/ theorem nonzero.of_ne [semiring α] {x y : α} (h : x ≠ y) : nonzero α := { zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul] } @[protect_proj] class no_zero_divisors (α : Type u) [has_mul α] [has_zero α] : Prop := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) lemma eq_zero_or_eq_zero_of_mul_eq_zero [has_mul α] [has_zero α] [no_zero_divisors α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero a b h lemma eq_zero_of_mul_self_eq_zero [has_mul α] [has_zero α] [no_zero_divisors α] {a : α} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h', h') (assume h', h') /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) (zero_ne_one : (0 : α) ≠ 1) section domain variable [domain α] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ instance domain.to_nonzero : nonzero α := ⟨domain.zero_ne_one⟩ /-- Simplification theorems for the definition of a domain. -/ @[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ @[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, mul_eq_zero] lemma mul_self_eq_zero {α} [domain α] {x : α} : x * x = 0 ↔ x = 0 := by simp lemma zero_eq_mul_self {α} [domain α] {x : α} : 0 = x * x ↔ x = 0 := by simp /-- The product of two nonzero elements of a domain is nonzero. -/ theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂ /-- Right multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- Left multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- An element of a domain fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁); rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂] /-- An element of a domain fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁); rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂] /-- For elements `a`, `b` of a domain, if `a*b` is nonzero, so is `b*a`. -/ theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h) end domain /- integral domains -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} lemma mul_eq_zero_iff_eq_zero_or_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ lemma mul_ne_zero (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h₃, h₁ h₃) (assume h₄, h₂ h₄) lemma eq_of_mul_eq_mul_right (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, from sub_eq_zero_of_eq h, have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this lemma eq_of_mul_eq_mul_left (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, from sub_eq_zero_of_eq h, have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this lemma eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := have hb : b - 1 ≠ 0, from assume : b - 1 = 0, have b = 0 + 1, from eq_add_of_sub_eq this, have b = 1, by rwa zero_add at this, h₁ this, have a * b - a = 0, by simp [h₂], have a * (b - 1) = 0, by rwa [mul_sub_left_distrib, mul_one], show a = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hb lemma eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right h₁ (by rwa mul_comm at h₂) lemma mul_self_eq_mul_self_iff (a b : α) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (assume : a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul_comm, ← mul_self_sub_mul_self_eq, this, sub_self], have a - b = 0 ∨ a + b = 0, from eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (assume : a - b = 0, or.inl (eq_of_sub_eq_zero this)) (assume : a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (assume : a = b ∨ a = -b, or.elim this (assume : a = b, by rewrite this) (assume : a = -b, by rewrite [this, neg_mul_neg])) lemma mul_self_eq_one_iff (a : α) : a * a = 1 ↔ a = 1 ∨ a = -1 := have a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rwa mul_one at this /-- Right multiplcation by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_right_of_ne_zero (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this /-- Left multiplication by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_left_of_ne_zero (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this /-- Given two elements b, c of an integral domain and a nonzero element a, a*b divides a*c iff b divides c. -/ theorem mul_dvd_mul_iff_left (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, domain.mul_right_inj ha] /-- Given two elements a, b of an integral domain and a nonzero element c, a*c divides b*c iff a divides b. -/ theorem mul_dvd_mul_iff_right (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, domain.mul_left_inj hc] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by conv {to_lhs, rw [inv_eq_iff_mul_eq_one, ← mul_one (1 : units α), units.ext_iff, units.coe_mul, units.coe_mul, mul_self_eq_mul_self_iff, ← units.ext_iff, ← units.coe_neg, ← units.ext_iff] } end integral_domain /- units in various rings -/ namespace units section semiring variables [semiring α] @[simp] theorem mul_left_eq_zero_iff_eq_zero {r : α} (u : units α) : r * u = 0 ↔ r = 0 := ⟨λ h, (mul_left_inj u).1 $ (zero_mul (u : α)).symm ▸ h, λ h, h.symm ▸ zero_mul (u : α)⟩ @[simp] theorem mul_right_eq_zero_iff_eq_zero {r : α} (u : units α) : (u : α) * r = 0 ↔ r = 0 := ⟨λ h, (mul_right_inj u).1 $ (mul_zero (u : α)).symm ▸ h, λ h, h.symm ▸ mul_zero (u : α)⟩ end semiring section comm_semiring variables [comm_semiring α] (a b : α) (u : units α) /-- Elements of the unit group of a commutative semiring represented as elements of the semiring divide any element of the semiring. -/ @[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a commutative semiring, an element a divides an element b iff a divides all associates of b. -/ @[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) /-- An element of a commutative semiring divides a unit iff the element divides one. -/ @[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 := suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa, dvd_coe_mul _ _ _ /-- In a commutative semiring, an element a divides an element b iff all associates of a divide b.-/ @[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩) (assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _)) end comm_semiring end units namespace is_unit section semiring variables [semiring α] theorem mul_left_eq_zero_iff_eq_zero {r u : α} (hu : is_unit u) : r * u = 0 ↔ r = 0 := by cases hu with u hu; exact hu ▸ units.mul_left_eq_zero_iff_eq_zero u theorem mul_right_eq_zero_iff_eq_zero {r u : α} (hu : is_unit u) : u * r = 0 ↔ r = 0 := by cases hu with u hu; exact hu ▸ units.mul_right_eq_zero_iff_eq_zero u end semiring end is_unit /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) (zero_ne_one : (0 : R) ≠ 1) /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) }
e653ea57fa8ffc89bcdd99a07b453ed666034834
6dbfa3fb323bb2e2c3917c61d46053dd0de739cd
/src/lemmas2.lean
0a2b97786a6e09857a798c20398d76242638681a
[]
no_license
amichaelsen/Lean-Chinese-Remainder-Theorem
b054fc32e0f5383eb83ec7155932c50d92de1038
9efb4b97da30e5aedb6af3c95d5132ac300f2902
refs/heads/master
1,680,787,277,127
1,619,155,524,000
1,619,155,524,000
275,883,966
0
0
null
null
null
null
UTF-8
Lean
false
false
3,747
lean
import data.nat.basic import data.nat.modeq import data.nat.gcd import data.zmod.basic import tactic import algebra.euclidean_domain import data.int.basic import data.equiv.ring noncomputable theory open nat nat.modeq zmod euclidean_domain namespace lemmas2 /- LEMMAS FOR CHINESE REMAINDER THEOREM WITH 2 CONGRUENCE RELATIONS -/ /-- Two natural numbers are equal if and only if they are mutual divisors -/ lemma eq_iff_dvd_dvd {n m : ℕ } : n = m ↔ m ∣ n ∧ n ∣ m := begin split, intro H, rw H, split; refl, intro H, rcases H with ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, rw hd, rw hc at hd, induction m with x hx, rw zero_mul at hc, rw hc, ring, rw mul_assoc at hd, have hd' : x.succ * (c * d) = x.succ, linarith, rw mul_right_eq_self_iff at hd', have h : d = 1, rw nat.mul_eq_one_iff at hd', exact hd'.2, rw h, ring, exact succ_pos', end /-- Given coprime natural numbers M1 M2, find the inverse of M2 M1 assuming that both are nonzero so avoid (1,0) case which is silly. -/ lemma nat_inv (M1 M2 : ℕ ) (M1pos : 0 < M1) (M2pos : 0 < M2) (H : coprime M1 M2) : ∃ b1 : ℕ, modeq M1 (b1 * M2) 1 := begin -- first cast to Z/M1 Z and get the group inverse have hb1 := mul_inv_eq_gcd (M2 : zmod M1), have H' := coprime.symm H, unfold coprime at *, rw val_nat_cast M2 at hb1, have H'' : (M2 % M1).gcd M1 = M2.gcd M1, begin have qr := div_add_mod (M2 : ℤ) (M1 : ℤ ), have qr' : (M1 * (M2 / M1) + M2 % M1) = M2, begin rw [← int.coe_nat_div M2 M1, ← int.coe_nat_mod M2 M1, ← int.coe_nat_mul _ _ , ← int.coe_nat_add _ _ , int.coe_nat_inj'] at qr, exact qr, end, -- want to show M2.gcd M1 ∣ (M2 % M1).gcd M1, have div1 : M2.gcd M1 ∣ (M2 % M1).gcd M1, begin have f1 := gcd_dvd_left M2 M1, have f2 := gcd_dvd_right M2 M1, have f3 : M2.gcd M1 ∣ M1 * (M2 / M1), {cases f2 with c hc, use c * (M2 / M1), rw ← mul_assoc, rw ← hc,}, have f4 : M2.gcd M1∣ M1 * (M2 / M1) + M2 % M1, {rw qr', exact f1,}, rw nat.dvd_add_right f3 at f4, exact dvd_gcd f4 f2, end, -- want to show (M2 % M1).gcd M1 ∣ M2.gcd M1, have div2 : (M2 % M1).gcd M1 ∣ M2.gcd M1, begin have f1 := gcd_dvd_right (M2 % M1) M1, have f2 := gcd_dvd_left (M2 % M1) M1, have f3 := dvd_mul_of_dvd_left f1 (M2 / M1), have f4 : (M2 % M1).gcd M1 ∣ M2, begin have k := (nat.dvd_add_right f3).2 f2, rw qr' at k, exact k, end, exact dvd_gcd f4 f1, end, have div : M2.gcd M1 ∣ (M2 % M1).gcd M1 ∧ (M2 % M1).gcd M1 ∣ M2.gcd M1, exact ⟨div1, div2⟩, rw ← eq_iff_dvd_dvd at div, exact div, end, -- use coprimeness and equality of gcd's to get as an actual inverse rw [H'',H'] at hb1, use (M2 : zmod M1)⁻¹.val, --translate this to zmod M1 rw ← nat_coe_eq_nat_coe_iff _ _ _, simp at *, rw mul_comm, have fact : (((M2 : zmod M1)⁻¹.val) : zmod M1) = (M2 : zmod M1)⁻¹, begin rw @nat_cast_zmod_val _ _, use M1pos, end, rw fact, exact hb1, end /- LEMMAS FOR CHINESE REMAINDER THEOREM WITH K CONGRUENCE RELATIONS -/ end lemmas2
ac1631a2baa48dfc06006b6ae70852bd544b812a
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/DiscrTree.lean
4c9e6b7aced4d5e3799a72b769e69ea8555a4397
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,746
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.Meta.Basic import Lean.Meta.FunInfo import Lean.Meta.InferType namespace Lean.Meta.DiscrTree /- (Imperfect) discrimination trees. We use a hybrid representation. - A `PersistentHashMap` for the root node which usually contains many children. - A sorted array of key/node pairs for inner nodes. The edges are labeled by keys: - Constant names (and arity). Universe levels are ignored. - Free variables (and arity). Thus, an entry in the discrimination tree may reference hypotheses from the local context. - Literals - Star/Wildcard. We use them to represent metavariables and terms we want to ignore. We ignore implicit arguments and proofs. - Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc). We reduce terms using `TransparencyMode.reducible`. Thus, all reducible definitions in an expression `e` are unfolded before we insert it into the discrimination tree. Recall that projections from classes are **NOT** reducible. For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x` and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys respctively ``` ⟨Add.add, 4⟩, *, *, *, * ⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩ ``` That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`. We say the `Add.add` applications are the de-facto canonical forms in the metaprogramming framework. Moreover, it is the metaprogrammer's responsibility to re-pack applications such as `Nat.add a b` into `Add.add Nat inst a b`. Remark: we store the arity in the keys 1- To be able to implement the "skip" operation when retrieving "candidate" unifiers. 2- Distinguish partial applications `f a`, `f a b`, and `f a b c`. -/ def Key.ctorIdx : Key → Nat | Key.star => 0 | Key.other => 1 | Key.lit _ => 2 | Key.fvar _ _ => 3 | Key.const _ _ => 4 def Key.lt : Key → Key → Bool | Key.lit v₁, Key.lit v₂ => v₁ < v₂ | Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx instance : HasLess Key := ⟨fun a b => Key.lt a b⟩ instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b)) def Key.format : Key → Format | Key.star => "*" | Key.other => "◾" | Key.lit (Literal.natVal v) => fmt v | Key.lit (Literal.strVal v) => repr v | Key.const k _ => fmt k | Key.fvar k _ => fmt k instance : ToFormat Key := ⟨Key.format⟩ def Key.arity : Key → Nat | Key.const _ a => a | Key.fvar _ a => a | _ => 0 instance {α} : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩ def empty {α} : DiscrTree α := { root := {} } /- The discrimination tree ignores implicit arguments and proofs. We use the following auxiliary id as a "mark". -/ private def tmpMVarId : MVarId := `_discr_tree_tmp private def tmpStar := mkMVar tmpMVarId instance {α} : Inhabited (DiscrTree α) := ⟨{}⟩ /-- Return true iff the argument should be treated as a "wildcard" by the discrimination tree. - We ignore proofs because of proof irrelevance. It doesn't make sense to try to index their structure. - We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical. Moreover, we may have many definitionally equal terms floating around. Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`. - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them, and may not even understand why some simplification rule is not firing. However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`, where `Nat` is an implicit argument. Thus, we would add the path ``` Decidable -> Eq -> * -> * -> * -> [Nat.decEq] ``` to the discrimination tree IF we ignored the implict `Nat` argument. This would be BAD since **ALL** decidable equality instances would be in the same path. So, we index implicit arguments if they are types. This setting seems sensible for simplification lemmas such as: ``` forall (x y : Unit), (@Eq Unit x y) = true ``` If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate simplification lemma for any equality in our goal. Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation, and `ignoreArg` would return true for any term of the form `noIndexing t`. -/ private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := if h : i < infos.size then let info := infos.get ⟨i, h⟩ if info.instImplicit then pure true else if info.implicit then not <$> isType a else isProof a else isProof a private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr) | i, Expr.app f a _, todo => do if (← ignoreArg a i infos) then pushArgsAux infos (i-1) f (todo.push tmpStar) else pushArgsAux infos (i-1) f (todo.push a) | _, _, todo => pure todo private partial def whnfEta (e : Expr) : MetaM Expr := do let e ← whnf e match e.etaExpandedStrict? with | some e => whnfEta e | none => pure e /- TODO: add a parameter (wildcardConsts : NameSet) to `DiscrTree.insert`. Then, `DiscrTree` users may control which symbols should be treated as wildcards. Different `DiscrTree` users may populate this set using, for example, attributes. -/ private def shouldAddAsStar (constName : Name) : Bool := constName == `Nat.zero || constName == `Nat.succ || constName == `Nat.add || constName == `Add.add private def pushArgs (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do let e ← whnfEta e let fn := e.getAppFn let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do let info ← getFunInfoNArgs fn nargs let todo ← pushArgsAux info.paramInfo (nargs-1) e todo pure (k, todo) match fn with | Expr.lit v _ => pure (Key.lit v, todo) | Expr.const c _ _ => if shouldAddAsStar c then pure (Key.star, todo) else let nargs := e.getAppNumArgs push (Key.const c nargs) nargs | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs push (Key.fvar fvarId nargs) nargs | Expr.mvar mvarId _ => if mvarId == tmpMVarId then -- We use `tmp to mark implicit arguments and proofs pure (Key.star, todo) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then pure (Key.other, todo) else pure (Key.star, todo) | _ => pure (Key.other, todo) partial def mkPathAux (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do if todo.isEmpty then pure keys else let e := todo.back let todo := todo.pop let (k, todo) ← pushArgs todo e mkPathAux todo (keys.push k) private def initCapacity := 8 def mkPath (e : Expr) : MetaM (Array Key) := withReducible do let todo : Array Expr := Array.mkEmpty initCapacity let keys : Array Key := Array.mkEmpty initCapacity mkPathAux (todo.push e) keys private partial def createNodes {α} (keys : Array Key) (v : α) (i : Nat) : Trie α := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := createNodes keys v (i+1) Trie.node #[] #[(k, c)] else Trie.node #[v] #[] private def insertVal {α} [BEq α] (vs : Array α) (v : α) : Array α := if vs.contains v then vs else vs.push v private partial def insertAux {α} [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α | i, Trie.node vs cs => if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing (fun _ => let c := createNodes keys v (i+1); (k, c)) (k, arbitrary) Trie.node vs c else Trie.node (insertVal vs v) cs def insertCore {α} [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α := if keys.isEmpty then panic! "invalid key sequence" else let k := keys[0] match d.root.find? k with | none => let c := createNodes keys v 1 { root := d.root.insert k c } | some c => let c := insertAux keys v 1 c { root := d.root.insert k c } def insert {α} [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do let keys ← mkPath e pure $ d.insertCore keys v partial def Trie.format {α} [ToFormat α] : Trie α → Format | Trie.node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs) ++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ format c)) instance {α} [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩ partial def format {α} [ToFormat α] (d : DiscrTree α) : Format := let (_, r) := d.root.foldl (fun (p : Bool × Format) k c => (false, p.2 ++ (if p.1 == true then Format.nil else Format.line) ++ Format.paren (fmt k ++ " => " ++ fmt c))) -- TODO: fix p.1 == true (true, Format.nil) Format.group r instance {α} [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩ private def getKeyArgs (e : Expr) (isMatch? : Bool) : MetaM (Key × Array Expr) := do let e ← whnfEta e match e.getAppFn with | Expr.lit v _ => pure (Key.lit v, #[]) | Expr.const c _ _ => let nargs := e.getAppNumArgs pure (Key.const c nargs, e.getAppRevArgs) | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs pure (Key.fvar fvarId nargs, e.getAppRevArgs) | Expr.mvar mvarId _ => if isMatch? then pure (Key.other, #[]) else do let ctx ← read if ctx.config.isDefEqStuckEx then /- When the configuration flag `isDefEqStuckEx` is set to true, we want `isDefEq` to throw an exception whenever it tries to assign a read-only metavariable. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`. That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)` where `?m` is a read-only metavariable, and the discrimination tree contains the keys `HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as a regular metavariable here, otherwise we return the empty set of candidates. This is incorrect because it is equivalent to saying that there is no solution even if the caller assigns `?m` and try again. -/ pure (Key.star, #[]) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then pure (Key.other, #[]) else pure (Key.star, #[]) | _ => pure (Key.other, #[]) private abbrev getMatchKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e true private abbrev getUnifyKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e false private partial def getMatchAux {α} : Array Expr → Trie α → Array α → MetaM (Array α) | todo, Trie.node vs cs, result => if todo.isEmpty then pure $ result ++ vs else if cs.isEmpty then pure result else do let e := todo.back let todo := todo.pop let first := cs[0] /- Recall that `Key.star` is the minimal key -/ let (k, args) ← getMatchKeyArgs e /- We must always visit `Key.star` edges since they are wildcards. Thus, `todo` is not used linearly when there is `Key.star` edge and there is an edge for `k` and `k != Key.star`. -/ let visitStarChild (result : Array α) : MetaM (Array α) := if first.1 == Key.star then getMatchAux todo first.2 result else pure result match k with | Key.star => visitStarChild result | _ => match cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1) with | none => visitStarChild result | some c => let result ← visitStarChild result getMatchAux (todo ++ args) c.2 result private def getStarResult {α} (d : DiscrTree α) : Array α := let result : Array α := Array.mkEmpty initCapacity match d.root.find? Key.star with | none => result | some (Trie.node vs _) => result ++ vs def getMatch {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let result := getStarResult d let (k, args) ← getMatchKeyArgs e match k with | Key.star => pure result | _ => match d.root.find? k with | none => pure result | some c => getMatchAux args c result private partial def getUnifyAux {α} : Nat → Array Expr → Trie α → (Array α) → MetaM (Array α) | skip+1, todo, Trie.node vs cs, result => if cs.isEmpty then pure result else cs.foldlM (fun result ⟨k, c⟩ => getUnifyAux (skip + k.arity) todo c result) result | 0, todo, Trie.node vs cs, result => do if todo.isEmpty then pure (result ++ vs) else if cs.isEmpty then pure result else let e := todo.back let todo := todo.pop let (k, args) ← getUnifyKeyArgs e match k with | Key.star => cs.foldlM (fun result ⟨k, c⟩ => getUnifyAux k.arity todo c result) result | _ => let first := cs[0] let visitStarChild (result : Array α) : MetaM (Array α) := if first.1 == Key.star then getUnifyAux 0 todo first.2 result else pure result match cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1) with | none => visitStarChild result | some c => let result ← visitStarChild result getUnifyAux 0 (todo ++ args) c.2 result def getUnify {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let (k, args) ← getUnifyKeyArgs e match k with | Key.star => d.root.foldlM (fun result k c => getUnifyAux k.arity #[] c result) #[] | _ => let result := getStarResult d match d.root.find? k with | none => pure result | some c => getUnifyAux 0 args c result end Lean.Meta.DiscrTree
f112a3ec95bde0d47df97b5a708c2ae7aed028f5
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Server/FileWorker/Utils.lean
8b8b33f2def7c541c8a5a6e29ee57fa60ca74306
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,557
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Server.Utils import Lean.Server.Snapshots import Lean.Server.AsyncList namespace Lean.Server.FileWorker open Snapshots open IO private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit := IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`" inductive ElabTaskError where | aborted | eof | ioError (e : IO.Error) instance : Coe IO.Error ElabTaskError := ⟨ElabTaskError.ioError⟩ structure CancelToken where ref : IO.Ref Bool deriving Inhabited namespace CancelToken def new : IO CancelToken := CancelToken.mk <$> IO.mkRef false def check [MonadExceptOf ElabTaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do let c ← tk.ref.get if c then throw ElabTaskError.aborted def set (tk : CancelToken) : IO Unit := tk.ref.set true end CancelToken /-- A document editable in the sense that we track the environment and parser state after each command so that edits can be applied without recompiling code appearing earlier in the file. -/ structure EditableDocument where meta : DocumentMeta /- The first snapshot is that after the header. -/ headerSnap : Snapshot /- Subsequent snapshots occur after each command. -/ cmdSnaps : AsyncList ElabTaskError Snapshot cancelTk : CancelToken deriving Inhabited end Lean.Server.FileWorker
11afc48a1a01b61c551fcd7f332f85f8a0cfd7a9
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/linear_algebra/dimension.lean
7596f469e8fa96c39476204db73bb8dc008231f2
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
18,076
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Johannes Hölzl, Sander Dahmen -/ import linear_algebra.basis import set_theory.ordinal /-! # Dimension of modules and vector spaces ## Main definitions * The dimension of a vector space is defined as `vector_space.dim : cardinal`. ## Main statements * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. * `dim_quotient_add_dim`: if V' is a submodule of V, then dim (V/V') + dim V' = dim V. * `dim_range_add_dim_ker`: the rank-nullity theorem. -/ noncomputable theory universes u u' u'' v' w w' variables {K : Type u} {V V₂ V₃ V₄ : Type u'} variables {ι : Type w} {ι' : Type w'} {η : Type u''} {φ : η → Type*} -- TODO: relax these universe constraints open_locale classical big_operators section vector_space variables [field K] [add_comm_group V] [vector_space K V] include K open submodule function set variables (K V) /-- the dimension of a vector space, defined as a term of type `cardinal` -/ def vector_space.dim : cardinal := cardinal.min (nonempty_subtype.2 (@exists_is_basis K V _ _ _)) (λ b, cardinal.mk b.1) variables {K V} open vector_space section theorem is_basis.le_span (zero_ne_one : (0 : K) ≠ 1) {v : ι → V} {J : set V} (hv : is_basis K v) (hJ : span K J = ⊤) : cardinal.mk (range v) ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { have := cardinal.mk_range_eq_of_injective (linear_independent.injective zero_ne_one hv.1), let S : J → set ι := λ j, ↑(is_basis.repr hv j).support, let S' : J → set V := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span K J ≤ comap hv.repr (finsupp.supported K K (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : hv.repr (v i) ∈ (finsupp.supported K K (⋃ j, S j)) := this trivial, rw [hv.repr_eq_single, finsupp.mem_supported, finsupp.support_single_ne_zero zero_ne_one.symm] at this, subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, refine le_of_not_lt (λ IJ, _), suffices : cardinal.mk (⋃ j, S' j) < cardinal.mk (range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ (finset.finite_to_set _).image _) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { rcases exists_finite_card_le_of_finite_of_linear_independent_of_span (cardinal.lt_omega_iff_finite.1 oJ) hv.1.to_subtype_range _ with ⟨fI, hi⟩, { rwa [← cardinal.nat_cast_le, cardinal.finset_card, set.finite.coe_to_finset, cardinal.finset_card, set.finite.coe_to_finset] at hi, }, { rw hJ, apply set.subset_univ } }, end end /-- dimension theorem -/ theorem mk_eq_mk_of_basis {v : ι → V} {v' : ι' → V} (hv : is_basis K v) (hv' : is_basis K v') : cardinal.lift.{w w'} (cardinal.mk ι) = cardinal.lift.{w' w} (cardinal.mk ι') := begin rw ←cardinal.lift_inj.{(max w w') u'}, rw [cardinal.lift_lift, cardinal.lift_lift], apply le_antisymm, { convert cardinal.lift_le.{u' (max w w')}.2 (hv.le_span zero_ne_one hv'.2), { rw cardinal.lift_max.{w u' w'}, apply (cardinal.mk_range_eq_of_injective (hv.injective zero_ne_one)).symm, }, { rw cardinal.lift_max.{w' u' w}, apply (cardinal.mk_range_eq_of_injective (hv'.injective zero_ne_one)).symm, }, }, { convert cardinal.lift_le.{u' (max w w')}.2 (hv'.le_span zero_ne_one hv.2), { rw cardinal.lift_max.{w' u' w}, apply (cardinal.mk_range_eq_of_injective (hv'.injective zero_ne_one)).symm, }, { rw cardinal.lift_max.{w u' w'}, apply (cardinal.mk_range_eq_of_injective (hv.injective zero_ne_one)).symm, }, } end theorem is_basis.mk_range_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.mk (range v) = dim K V := begin have := show ∃ v', dim K V = _, from cardinal.min_eq _ _, rcases this with ⟨v', e⟩, rw e, apply cardinal.lift_inj.1, rw cardinal.mk_range_eq_of_injective (h.injective zero_ne_one), convert @mk_eq_mk_of_basis _ _ _ _ _ _ _ _ _ h v'.property end theorem is_basis.mk_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.lift.{w u'} (cardinal.mk ι) = cardinal.lift.{u' w} (dim K V) := by rw [←h.mk_range_eq_dim, cardinal.mk_range_eq_of_injective (h.injective zero_ne_one)] variables [add_comm_group V₂] [vector_space K V₂] /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : V ≃ₗ[K] V₂) : dim K V = dim K V₂ := by letI := classical.dec_eq V; letI := classical.dec_eq V₂; exact let ⟨b, hb⟩ := exists_is_basis K V in cardinal.lift_inj.1 $ hb.mk_eq_dim.symm.trans (f.is_basis hb).mk_eq_dim @[simp] lemma dim_bot : dim K (⊥ : submodule K V) = 0 := by letI := classical.dec_eq V; rw [← cardinal.lift_inj, ← (@is_basis_empty_bot pempty K V _ _ _ not_nonempty_pempty).mk_eq_dim, cardinal.mk_pempty] @[simp] lemma dim_top : dim K (⊤ : submodule K V) = dim K V := linear_equiv.dim_eq (linear_equiv.of_top _ rfl) lemma dim_of_field (K : Type*) [field K] : dim K K = 1 := by rw [←cardinal.lift_inj, ← (@is_basis_singleton_one punit K _ _).mk_eq_dim, cardinal.mk_punit] lemma dim_span {v : ι → V} (hv : linear_independent K v) : dim K ↥(span K (range v)) = cardinal.mk (range v) := by rw [←cardinal.lift_inj, ← (is_basis_span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι K V v _ _ _ zero_ne_one hv)] lemma dim_span_set {s : set V} (hs : linear_independent K (λ x, x : s → V)) : dim K ↥(span K s) = cardinal.mk s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } lemma cardinal_le_dim_of_linear_independent {ι : Type u'} {v : ι → V} (hv : linear_independent K v) : (cardinal.mk ι) ≤ (dim.{u u'} K V) := begin obtain ⟨ι', v', is⟩ := exists_sum_is_basis hv, simpa using le_trans (cardinal.lift_mk_le.{u' u' u'}.2 ⟨@function.embedding.inl ι ι'⟩) (le_of_eq is.mk_eq_dim), end lemma cardinal_le_dim_of_linear_independent' {s : set V} (hs : linear_independent K (λ x, x : s → V)) : cardinal.mk s ≤ dim K V := begin -- extend s to a basis obtain ⟨b, ss, h⟩ := exists_subset_is_basis hs, rw [←h.mk_range_eq_dim, subtype.range_coe], apply cardinal.mk_le_of_injective (inclusion_injective ss), end lemma dim_span_le (s : set V) : dim K (span K s) ≤ cardinal.mk s := begin classical, rcases exists_linear_independent (linear_independent_empty K V) (set.empty_subset s) with ⟨b, hb, _, hsb, hlib⟩, have hsab : span K s = span K b, from span_eq_of_le _ hsb (span_le.2 (λ x hx, subset_span (hb hx))), convert cardinal.mk_le_mk_of_subset hb, rw [hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : dim K (span K (↑s : set V)) < cardinal.omega := calc dim K (span K (↑s : set V)) ≤ cardinal.mk (↑s : set V) : dim_span_le ↑s ... = s.card : by rw ←cardinal.finset_card ... < cardinal.omega : cardinal.nat_lt_omega _ theorem dim_prod : dim K (V × V₂) = dim K V + dim K V₂ := begin letI := classical.dec_eq V, letI := classical.dec_eq V₂, rcases exists_is_basis K V with ⟨b, hb⟩, rcases exists_is_basis K V₂ with ⟨c, hc⟩, rw [← cardinal.lift_inj, ← @is_basis.mk_eq_dim K (V × V₂) _ _ _ _ _ (is_basis_inl_union_inr hb hc), cardinal.lift_add, cardinal.lift_mk, ← hb.mk_eq_dim, ← hc.mk_eq_dim, cardinal.lift_mk, cardinal.lift_mk, cardinal.add_def (ulift b) (ulift c)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr (@equiv.ulift b) (@equiv.ulift c)).symm ⟩), end theorem dim_quotient_add_dim (p : submodule K V) : dim K p.quotient + dim K p = dim K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq theorem dim_quotient_le (p : submodule K V) : dim K p.quotient ≤ dim K V := by { rw ← dim_quotient_add_dim p, exact cardinal.le_add_right _ _ } /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₂) : dim K f.range + dim K f.ker = dim K V := begin haveI := λ (p : submodule K V), classical.dec_eq p.quotient, rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_range_le (f : V →ₗ[K] V₂) : dim K f.range ≤ dim K V := by rw ← dim_range_add_dim_ker f; exact le_add_right (le_refl _) lemma dim_map_le (f : V →ₗ V₂) (p : submodule K V) : dim K (p.map f) ≤ dim K p := begin have h := dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_range_of_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K f.range = dim K V₂ := begin refine linear_equiv.dim_eq (linear_equiv.of_bijective (submodule.subtype _) _ _), exact linear_map.ker_eq_bot.2 subtype.val_injective, rwa [range_subtype, linear_map.range_eq_top] end lemma dim_eq_of_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K V = dim K V₂ + dim K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] lemma dim_le_of_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K V₂ ≤ dim K V := by rw [dim_eq_of_surjective f h]; refine le_add_right (le_refl _) lemma dim_eq_of_injective (f : V →ₗ[K] V₂) (h : injective f) : dim K V = dim K f.range := by rw [← dim_range_add_dim_ker f, linear_map.ker_eq_bot.2 h]; simp [dim_bot] lemma dim_submodule_le (s : submodule K V) : dim K s ≤ dim K V := by { rw ← dim_quotient_add_dim s, exact cardinal.le_add_left _ _ } lemma dim_le_of_injective (f : V →ₗ[K] V₂) (h : injective f) : dim K V ≤ dim K V₂ := by { rw [dim_eq_of_injective f h], exact dim_submodule_le _ } lemma dim_le_of_submodule (s t : submodule K V) (h : s ≤ t) : dim K s ≤ dim K t := dim_le_of_injective (of_le h) $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq section variables [add_comm_group V₃] [vector_space K V₃] variables [add_comm_group V₄] [vector_space K V₄] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₃ →ₗ[K] V) (eb : V₄ →ₗ[K] V) (cd : V₂ →ₗ[K] V₃) (ce : V₂ →ₗ[K] V₄) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : dim K V + dim K V₂ = dim K V₃ + dim K V₄ := have hf : surjective (coprod db eb), begin refine (range_eq_top.1 $ top_unique $ _), rwa [← map_top, ← prod_top, map_coprod_prod] end, begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : dim K (s ⊔ t : submodule K V) + dim K (s ⊓ t : submodule K V) = dim K s + dim K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_refl _ end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, have : b₁ = b₂ := congr_arg subtype.val eq, subst this, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : dim K (s ⊔ t : submodule K V) ≤ dim K s + dim K t := by rw [← dim_sup_add_dim_inf_eq]; exact le_add_right (le_refl _) end section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, vector_space K (φ i)] open linear_map lemma dim_pi : vector_space.dim K (Πi, φ i) = cardinal.sum (λi, vector_space.dim K (φ i)) := begin choose b hb using assume i, exists_is_basis K (φ i), have : is_basis K (λ (ji : Σ j, b j), std_basis K (λ j, φ j) ji.fst ji.snd.val), by apply pi.is_basis_std_basis _ hb, rw [←cardinal.lift_inj, ← this.mk_eq_dim], simp [λ i, (hb i).mk_range_eq_dim.symm, cardinal.sum_mk] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [vector_space K V] : vector_space.dim K (η → V) = fintype.card η * vector_space.dim K V := by rw [dim_pi, cardinal.sum_const, cardinal.fintype_card] lemma dim_fun_eq_lift_mul : vector_space.dim K (η → V) = (fintype.card η : cardinal.{max u'' u'}) * cardinal.lift.{u' u''} (vector_space.dim K V) := by rw [dim_pi, cardinal.sum_const_eq_lift_mul, cardinal.fintype_card, cardinal.lift_nat_cast] lemma dim_fun' : vector_space.dim K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_of_field K, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : dim K (fin n → K) = n := by simp [dim_fun'] end fintype lemma exists_mem_ne_zero_of_ne_bot {s : submodule K V} (h : s ≠ ⊥) : ∃ b : V, b ∈ s ∧ b ≠ 0 := begin classical, by_contradiction hex, have : ∀x∈s, (x:V) = 0, { simpa only [not_exists, not_and, not_not, ne.def] using hex }, exact (h $ bot_unique $ assume s hs, (submodule.mem_bot K).2 $ this s hs) end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : vector_space.dim K s > 0) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [(>), eq, dim_bot] at h; exact lt_irrefl _ h lemma exists_is_basis_fintype (h : dim K V < cardinal.omega) : ∃ s : (set V), (is_basis K (subtype.val : s → V)) ∧ nonempty (fintype s) := begin cases exists_is_basis K V with s hs, rw [←cardinal.lift_lt, ← is_basis.mk_eq_dim hs, cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h, exact ⟨s, hs, h⟩ end section rank /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V₂) : cardinal := dim K f.range lemma rank_le_domain (f : V →ₗ[K] V₂) : rank f ≤ dim K V := by rw [← dim_range_add_dim_ker f]; exact le_add_right (le_refl _) lemma rank_le_range (f : V →ₗ[K] V₂) : rank f ≤ dim K V₂ := dim_submodule_le _ lemma rank_add_le (f g : V →ₗ[K] V₂) : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ dim K (f.range ⊔ g.range : submodule K V₂) : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V₂), from mem_sup.2 ⟨_, mem_image_of_mem _ (mem_univ _), _, mem_image_of_mem _ (mem_univ _), rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ @[simp] lemma rank_zero : rank (0 : V →ₗ[K] V₂) = 0 := by rw [rank, linear_map.range_zero, dim_bot] lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V₂) : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left' h)) variables [add_comm_group V₃] [vector_space K V₃] lemma rank_comp_le1 (g : V →ₗ[K] V₂) (f : V₂ →ₗ[K] V₃) : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact image_subset _ (subset_univ _) end lemma rank_comp_le2 (g : V →ₗ[K] V₂) (f : V₂ →ₗ V₃) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end rank lemma dim_zero_iff_forall_zero : vector_space.dim K V = 0 ↔ ∀ x : V, x = 0 := begin split, { intros h x, cases exists_is_basis K V with w hw, have card_mk_range := hw.mk_range_eq_dim, rw [h, cardinal.mk_emptyc_iff, subtype.range_coe] at card_mk_range, simpa [card_mk_range] using hw.mem_span x }, { intro h, have : (⊤ : submodule K V) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_pos_iff_exists_ne_zero : 0 < vector_space.dim K V ↔ ∃ x : V, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end end vector_space section unconstrained_universes variables {E : Type v'} variables [field K] [add_comm_group V] [vector_space K V] [add_comm_group E] [vector_space K E] open vector_space /-- Version of linear_equiv.dim_eq without universe constraints. -/ theorem linear_equiv.dim_eq_lift (f : V ≃ₗ[K] E) : cardinal.lift.{u' v'} (dim K V) = cardinal.lift.{v' u'} (dim K E) := begin cases exists_is_basis K V with b hb, rw [← cardinal.lift_inj.1 hb.mk_eq_dim, ← (f.is_basis hb).mk_eq_dim, cardinal.lift_mk], end end unconstrained_universes
e658978c956aec04033d20e70f95cc185b8a4f38
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world5/level4.lean
5bde5af8d86916ca431a87e98830bee44a3f7416
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
1,809
lean
/- Tactic : apply If you have a function `h : P → Q` and your goal is `⊢ Q` then `apply h` changes the goal to `⊢ P`. The logic is simple: if you are trying to create a term of type `Q`, but `h` is a function which turns terms of type `P` into terms of type `Q`, then it will suffice to construct a term of type `P`. A mathematician might say: "we need to construct an element of $Q$, but we have a function $h:P\to Q$ so it suffices to construct an element of $P$". Or alternatively "we need to prove $Q$, but we have a proof $h$ that $P\implies Q$ so it suffices to prove $P$". -/ /- # Function world. ## Level 4 : `apply`. Let's do the same level again: ![diagram](/function_diag.jpg) We are given $p \in P$ and our goal is to find an element of $U$, or in other words to find a path through the maze that links $P$ to $U$. In level 3 we solved this by using `have`s to move forward, from $P$ to $Q$ to $T$ to $U$. Using the `apply` tactic we can instead construct the path backwards, moving from $U$ to $T$ to $Q$ to $P$. Our goal is to construct an element of the set $U$. But $l:T\to U$ is a function, so it would suffice to construct an element of $T$. Tell Lean this by starting the proof below with `apply l,` and notice that our assumptions don't change but *the goal changes* from `⊢ U` to `⊢ T`. Keep `apply`ing functions until your goal is `P`, and try not to get lost! Now solve this goal with `exact p`. Note: you will need to learn the difference between `exact p` (which works) and `exact P` (which doesn't, because $P$ is not an element of $P$). -/ /- Lemma : no-side-bar We can solve a maze. -/ lemma maze (P Q R S T U: Type) (p : P) (h : P → Q) (i : Q → R) (j : Q → T) (k : S → T) (l : T → U) : U := begin apply l, apply j, apply h, exact p, end
4133c5fedc2644a287cbdcc81960f8162542a4ba
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/783.lean
3d19b694944b64299d8176988ee0014c0cc89c64
[ "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
125
lean
structure MyStruct where {α : Type u} {β : Type v} a : α b : β #check { a := 10, b := true : MyStruct }